From 6bba43316963b4dc01bd5a048bdb34c4c9b308be Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:24:36 +0100 Subject: [PATCH 01/26] Plan joint process and confidential metadata completion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Eigentümerauftrag R7/R8 gemeinsam in einem PR; konkreter Plan vor Produktionscode. EN: Source-bound scope, platform/helper and API compatibility gates, native acceptance and exact rollback. No runtime or host-policy change. Co-authored-by: Codex --- .../PROCESS_METADATA_COMPLETION_PLAN.md | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/security/PROCESS_METADATA_COMPLETION_PLAN.md diff --git a/docs/security/PROCESS_METADATA_COMPLETION_PLAN.md b/docs/security/PROCESS_METADATA_COMPLETION_PLAN.md new file mode 100644 index 0000000..d1eb89b --- /dev/null +++ b/docs/security/PROCESS_METADATA_COMPLETION_PLAN.md @@ -0,0 +1,103 @@ +# R7/R8 joint completion plan / Gemeinsamer Abschlussplan + +DE: Eigentümerauftrag vom 27.11.2026: R7 und R8 gemeinsam in genau einem PR +bearbeiten und alle konkreten Lücken schließen. Grundlage sind die bereits +vorgelegten R7/R8-Pläne in SECRET_LIFETIME_REMEDIATION und die ausdrückliche +Entscheidung in SECRET_PROCESS_CAPABILITY_ADR: Unterstützung zuerst entwickeln, +Windows/GUI nicht pauschal abschalten. Dieser Plan konkretisiert den Auftrag vor +Produktionscode. Basis: Main b813bc612c6ad796e7b5bdf6d4462c9089e90acd, R6 abgenommen. +EN: One joint implementation PR, no partial-completion merge. Existing R6 +acceptance stays intact. No host deployment or settings change is authorized. + +## Scope and acceptance / Umfang und Abnahme + +| ID | Actual gap / Konkrete Lücke | Change and acceptance / Änderung und Abnahme | +|---|---|---| +| P1 | Linux startup only attempts hardening | Read back actual core/dumpability state; mandatory checked capability before private CLI/server ingress; syscall/readback denial tests in bounded own children. | +| P2 | Windows NOHEAP is partial | Separate real Windows capabilities from Linux properties; review process/dump/handle policy against Microsoft APIs; native success/failure/access tests. No invented complete flag. | +| P3 | Library/HTTP host responsibility implicit | Explicit host-policy contract/capability boundary; no implicit irreversible host mutation; check actual router and direct operation entry points. | +| P4 | zenity/kdialog/PowerShell private widgets/strings | Verified helper path with stable prelocked input/event/encoding/output storage and checked process startup before input. Existing generic password widgets are not accepted merely because masked. | +| P5 | Helper child lifecycle | Bounded startup/handshake; cancel/EOF/broken pipe/timeout/unwind; only intended handles inherited; terminate/reap only own children. No secret arguments or general IPC endpoint. | +| M1 | Source relative names, skipped names and traversal records | Reuse ConfidentialText/SecretWorkspace; preallocate locked records, bounded fallible growth; no ordinary format!/lowercase/clone staging on confidential paths. Preserve sorting and skip semantics. | +| M2 | PathSet BTree nodes and traversal stacks | Lock concrete records before private population; explicit bounded locked indexing, no private nodes left in ordinary collection allocations. Preserve all conflict/Unicode/depth rules. | +| M3 | Temp/target/original paths and FS adapters | Locked UTF-8/UTF-16 path ownership and formatting; borrow OS representations where possible; audit reached std/platform conversions. External OS filesystem namespace is a disclosure boundary, not permission for application staging. | +| M4 | Hidden v4 sender key/signature/identity | Separate hidden confidential output from public v3 declarations; prelocked signing/output/hash/parse/retention; redacted Debug, fallible duplication only. Same wire bytes and signature equations. | +| M5 | Reports, progress, CLI/context, API serialization | Explicit requested disclosure, prelocked escaping/format/transport workspaces; redact default Debug/errors; no temporary plain Strings or unbounded output collection. Preserve authenticated-before-output rules. | +| M6 | Shared lock registry records | Review actual address/reference-count/guard storage and synchronization; avoid recursive self-locking and unprotected private registry nodes. Prove overlapping locks and denial cleanup remain correct. | +| M7 | Ordinary public key metadata and caller inputs | Distinguish intentionally plaintext public-key JSON and caller-owned external memory from internal confidential retention. Explicit types/contracts; never retrospectively claim caller allocations locked. | +| V1 | Source and API compatibility | Inventory every changed Rust signature and caller; preserve CLI/JSON and v1/v2/v3/v4 bytes. Necessary fallible confidential Rust types require documented migration rather than silent clone fallback. | +| V2 | Full acceptance | Native Linux/Windows/ARM64, both feature configurations, MSRV, strict lint/audit/history scan, all eight actual fuzz targets; source-bound error/unwind/denial observations. | + +DE: Jede Zeile braucht nachweislich echte Caller-/Owner-Belege; eine neue Typbezeichnung, +ein gesetztes Flag oder ein Dokumentationssatz allein schließen keine Zeile. +EN: Neither disabled functional coverage nor a known private scratch allocation +renamed as a compiler boundary counts as closure. + +## Files and implementation order / Dateien und Reihenfolge + +1. DE: Zuerst aktuelle Caller-/Typ-/Retentionmatrix und reproduzierbare Fehlerfälle. + EN: Record exact source hashes and establish real-path failures before fixes. +2. DE: src/hardening/{mod,memlock}.rs, Plattformadapter und eigene Testmodule; + src/cli/{mod,serve,context_child,context_dialog}.rs, dialog/ und Helper-Einstieg. + EN: Develop verified platform/helper support before installing its gate. +3. DE: src/files/{walk,paths,original,output,confidential_text, + confidential_entries,signed_io,tail_v4}.rs, fsutil und tatsächliche API-/CLI- + Fortschritts-/Report-Verbraucher. Kleine Module und vorhandene Owner nutzen. + EN: Follow data flow through every dependent caller, not isolated wrappers. +4. DE: docs/SPEC.md und .en.md, ROADMAP, MEMORY_HARDENING, API-/GUI-/Listing- + Verträge, Änderungsnotizen, Audit-/Inventar-/Abnahmematrix gemeinsam pflegen. + EN: Keep historical evidence, add an authoritative current acceptance map. + +## Platform/helper selection / Plattform- und Helperauswahl + +DE: Bestehende externe Passwortdialoge sind kein verifizierter Pfad. GTK4.18.6 +PasswordEntryBuffer verwendet gtk_secure_realloc; dessen Secure-Memory-Allocator +enthält GTK_SECURE_USE_FALLBACK und gewöhnliches g_realloc/g_free. Daher keine +Freigabe dieses Backends allein aufgrund der GtkPasswordEntry-Dokumentation. +Vor Auswahl einer Bibliothek müssen Event-/IME-/UTF-/Widget-/Pipe-Scratch und +Wipe-/Lockfehler belegt sein. Falls der vorhandene Backend-Vertrag dies nicht +erlaubt: gezielter nativer Helper, keine nachträgliche Sperre eines String-Ergebnisses. +EN: Backend selection needs source evidence and native tests. Preserve current +supported user flows; incompatible platform changes need an explicit decision, +not an undocumented terminal substitution or blanket GUI refusal. + +DE: Windows-Prozess-DACLs, WER, LocalDumps und Debugrechte sind unterschiedliche +Schutzflächen. LocalDumps ist laut Microsoft unabhängig von übriger WER-Meldung. +Keine Registry-/ACL-/Privileg-/Hoständerung ohne konkrete Freigabe; keine Garantie +gegen Administrator, Kernel, Stromverlust oder kompromittierten Eingabestack. +EN: A partial process capability must never masquerade as Linux NotDumpable. +Read-only deployment diagnosis is distinct from changing machine policy. + +## Dependencies / Abhängigkeiten + +DE: #128/#149/#150 sind offen; ihre relevanten Prozess-/Handle-Verträge werden +hier abgeglichen, keine automatische Schließung ihrer gesamten Scopes. #98 ist +offen: dokumentierte API-Typ-/Disclosure-Migration mit Versionierung abstimmen. +#117 ist completed: Authentisierung, Grenzen und No-extraction-Vertrag erhalten. +#148 und R6 sind abgenommen und werden weder dupliziert noch abgeschwächt. +EN: Source review explicitly includes newer PADMÉ/ANON/hidden-sender/privacy +Main integrations. No second cryptographic implementation or new wire format. + +## Verification, backup and rollback / Prüfung, Sicherung und Rückweg + +DE: Vor Schluss sämtliche Zeilen auf dem exakten integrierten Head abnehmen: +echte Positiv-/Negativ-/Grenz-/Tamperfälle, Ressourcenverweigerung vor Secret- +Eintritt, vollständiger Wipe vor Unlock/Free bei Erfolg/Fehler/Unwind, keine +Teilausgabe, keine Geheimwerte/Adressen in Logs. Native Tests statt bloßer Cross- +Kompilierung. Root-forbid bleibt; unnötiges unsafe entfernen, notwendige native +Grenzen einzeln mit Ausrichtung/Lebensdauer/Aliasing/API-Vertrag rechtfertigen. +EN: No tests mirror only type names; no bypass, weaker gates or parameter reductions. + +DE: Vollständiges Bundle, unabhängiger Restore/fsck und Datei-/Modusvergleich, +Signaturprüfung, separater Reverse-Index zum exakten vorherigen Main-Baum vor +Merge. Bestehende Worktrees/Sicherungen behalten; Löschfreigabe gegebenenfalls +erst für den konkreten gesicherten Remote-Head. Kein automatischer Sicherheits- +Revert, keine Migration, Installation, Veröffentlichung oder Dienständerung. +EN: The joint PR stays draft until every concrete row passes. Do not mark R7/R8 +or whole147 complete while a platform/helper/metadata row remains unverified. + +Sources / Quellen: +- https://github.com/GNOME/gtk/blob/4.18.6/gtk/gtkpasswordentrybuffer.c +- https://github.com/GNOME/gtk/blob/4.18.6/gtk/gtksecurememory.c +- https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights +- https://learn.microsoft.com/en-us/windows/win32/wer/collecting-user-mode-dumps From f14f068480214acf927742e9d048cc64780ed1fd Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:14:16 +0100 Subject: [PATCH 02/26] Protect path index nodes and verified sender identities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Gemeinsamer R7/R8-Arbeitsstand in Draft355: gesperrter AVL-Pfadindex mit echten Denial-/Unwind-Nachweisen; gesperrte Absender-ID und geteilter Ergebnis-Slot, explizite fallible Rust-Ownership. Tatsächliche Prozessfähigkeiten auslesen. Konkrete eigene Windows-CI-DACL-Probe nach gesonderter Freigabe. Main356-Integritätstests vollständig erhalten. Noch kein R7/R8-Abschluss, kein Teilmerge. EN: Protect actual path index records and verified sender identities before population. Preserve wire/CLI/JSON contracts, explicitly migrate Rust key_id/Clone access, redact identity Debug. Add actual read-only process capability observation and approved bounded own Windows process-access probe. Integrate Main356 test/audit coverage. Full platform/helper, signature scratch, remaining metadata paths and joint acceptance stay open. Refs #147. --- .github/workflows/process-access-probe.yml | 32 +++ CHANGELOG.md | 9 + docs/FILE_FORMAT.md | 10 +- docs/SPEC.en.md | 7 + docs/SPEC.md | 7 + docs/security/ATTACK_TEST_MATRIX.md | 2 + .../CONFIDENTIAL_PATH_INDEX_VALIDATION.md | 62 +++++ docs/security/CONFIDENTIAL_SENDER_IDENTITY.md | 55 ++++ docs/security/CONTAINER_INTEGRITY_AUDIT.md | 145 ++++++++++ .../WINDOWS_PROCESS_ACCESS_PROBE_PLAN.md | 65 +++++ docs/security/attack-baseline.json | 4 +- docs/security/attack-matrix.json | 182 +++++++++++-- fuzz/fuzz_targets/pqkf_header.rs | 8 +- platform/pqkeep-platform/Cargo.toml | 8 +- .../examples/process_access_probe.rs | 161 ++++++++++++ scripts/test_process_access_probe.ps1 | 54 ++++ src/cli/files_json.rs | 2 +- src/cli/signing.rs | 2 +- src/files/confidential_path_index.rs | 248 ++++++++++++++++++ .../confidential_path_index_denial_tests.rs | 119 +++++++++ src/files/confidential_path_index_tests.rs | 114 ++++++++ src/files/decrypt_v2.rs | 2 +- src/files/hidden_result.rs | 39 +++ src/files/hidden_result_tests.rs | 27 ++ src/files/mod.rs | 10 +- src/files/path_components_tests.rs | 13 +- src/files/paths.rs | 27 +- src/files/paths_tests.rs | 12 +- src/files/recovery_v4_tests.rs | 156 +++++++++++ src/files/signed_by.rs | 67 +++++ src/files/signed_by_denial_tests.rs | 107 ++++++++ src/files/signed_by_tests.rs | 39 +++ src/files/signed_io.rs | 33 +-- src/files/tail_v4.rs | 12 +- src/files/tail_v4_tests.rs | 7 +- src/hardening/mod.rs | 50 +++- tests/common/integrity.rs | 179 +++++++++++++ tests/common/mod.rs | 1 + tests/files_hidden_sender.rs | 19 +- tests/files_signed.rs | 6 +- tests/integrity_chunks.rs | 146 +++++++++++ tests/integrity_headers.rs | 82 ++++++ tests/integrity_kill.rs | 110 ++++++++ tests/process_capability.rs | 96 +++++++ 44 files changed, 2418 insertions(+), 118 deletions(-) create mode 100644 .github/workflows/process-access-probe.yml create mode 100644 docs/security/CONFIDENTIAL_PATH_INDEX_VALIDATION.md create mode 100644 docs/security/CONFIDENTIAL_SENDER_IDENTITY.md create mode 100644 docs/security/CONTAINER_INTEGRITY_AUDIT.md create mode 100644 docs/security/WINDOWS_PROCESS_ACCESS_PROBE_PLAN.md create mode 100644 platform/pqkeep-platform/examples/process_access_probe.rs create mode 100644 scripts/test_process_access_probe.ps1 create mode 100644 src/files/confidential_path_index.rs create mode 100644 src/files/confidential_path_index_denial_tests.rs create mode 100644 src/files/confidential_path_index_tests.rs create mode 100644 src/files/hidden_result.rs create mode 100644 src/files/hidden_result_tests.rs create mode 100644 src/files/recovery_v4_tests.rs create mode 100644 src/files/signed_by.rs create mode 100644 src/files/signed_by_denial_tests.rs create mode 100644 src/files/signed_by_tests.rs create mode 100644 tests/common/integrity.rs create mode 100644 tests/integrity_chunks.rs create mode 100644 tests/integrity_headers.rs create mode 100644 tests/integrity_kill.rs create mode 100644 tests/process_capability.rs diff --git a/.github/workflows/process-access-probe.yml b/.github/workflows/process-access-probe.yml new file mode 100644 index 0000000..ee6ffcf --- /dev/null +++ b/.github/workflows/process-access-probe.yml @@ -0,0 +1,32 @@ +# DE/EN: Explizite öffentliche eigene Prozessprobe, keine vollständige R7-Abnahme. +name: Process access probe + +on: + pull_request: + paths: + - 'platform/pqkeep-platform/**' + - 'scripts/test_process_access_probe.ps1' + - '.github/workflows/process-access-probe.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: process-access-probe-${{ github.ref }} + cancel-in-progress: true + +jobs: + windows: + name: Owned Windows process access probe + runs-on: windows-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: rustup show active-toolchain + - run: cargo build --locked -p pqkeep-platform --example process_access_probe --features process-access-probe + - name: Eigene Prozess-DACL und Leseverweigerung / own DACL and denied access + shell: pwsh + run: ./scripts/test_process_access_probe.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index b8f4773..7d835e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ German release notes: see `docs/releases/`. ## [Unreleased] +- DE: **Integritäts-Audit der Container** (#335): alle Entschlüsselungspfade (v1–v4) geprüft, kein Befund; + neue Regressionstests (jedes Header-Byte, Blocktausch/Abschneiden auf Dateiebene, Frische, Fehlerpläne + v4, Kill während `decrypt`). Hinweis: Nach Kill/Stromausfall kann temporärer Klartext unter verstecktem + Namen bleiben – Vollverschlüsselung empfohlen, namenlose Temporärdateien folgen in #338. + EN: **Container integrity audit** (#335): all decrypt paths (v1–v4) reviewed, no finding; new + regression tests (every header byte, file-level chunk swap/cut, freshness, v4 fault plans, kill during + `decrypt`). Note: after kill/power loss temporary plaintext may remain under a hidden name – full-disk + encryption recommended, unnamed temporary files follow in #338. + - DE: **Stufe „Privatsphäre hoch“ vollständig** (#316): `--privacy high` (Menü, Kontextmenü) setzt zufälligen Namen, Füllung, beim Signieren den verborgenen Absender und bei ML-KEM-1024-Empfängern die **experimentellen anonymen Empfänger** – mit Warnung; abwählbar mit `--no-anonymous-recipients` bzw. per diff --git a/docs/FILE_FORMAT.md b/docs/FILE_FORMAT.md index a289191..18d022d 100644 --- a/docs/FILE_FORMAT.md +++ b/docs/FILE_FORMAT.md @@ -143,6 +143,11 @@ sehen nur „signiert, Absender verborgen“; wer entschlüsseln kann, prüft de tauschen (TOCTOU); das betrifft nur Angreifer mit Schreibrechten im Quellordner. - Ordner werden per „Prüfen + Umbenennen“ veröffentlicht; ein exakt gleichzeitig angelegtes Ziel wäre ein theoretisches Rennen (unter Windows schlägt das Umbenennen dann fehl). +- Wird PQKeep beim Entschlüsseln hart beendet (Kill, Absturz, Stromausfall), kann eine + **temporäre Klartextdatei** mit verstecktem Namen (`.name.tmp-…`, Linux 0600) liegen bleiben; unter + dem Zielnamen erscheint nie etwas Ungeprüftes. Gegen Reste auf dem Datenträger hilft nur eine + **Vollverschlüsselung** (LUKS, BitLocker); namenlose Temporärdateien sind in #338 geplant + ([Audit](security/CONTAINER_INTEGRITY_AUDIT.md)). - Speicherbedarf konstant (etwa zwei Blöcke), unabhängig von der Dateigröße. --- @@ -227,7 +232,10 @@ decrypting, but before any output. The file grows by about 7 KB. **Limitations:** approximate total size is visible; timestamps/ownership/permissions are not kept; originals are not deleted; a local attacker with write access to the source directory could swap a file for a symlink between check and open (TOCTOU); directory publishing is check + rename; memory use -is constant. +is constant; if PQKeep is killed while decrypting (kill, crash, power loss) a **temporary plaintext +file** with a hidden name (`.name.tmp-…`, Linux 0600) may remain – nothing unverified ever appears under +the target name; against leftovers on the medium only **full-disk encryption** (LUKS, BitLocker) helps; +unnamed temporary files are planned in #338 ([audit](security/CONTAINER_INTEGRITY_AUDIT.md)). ## Archivliste / Archive listing (#117) diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 997289f..2810bbf 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -1,5 +1,12 @@ # MASTER PROJECT SPECIFICATION v2.23: PQKeep (Core, CLI & API) – English translation +> R7/R8 work in progress (#147, joint PR #355): verified sender identities use +> fallible locked ownership. Rust API: `SignedBy::key_id()` replaces the public +> Vec field, `try_duplicate()` replaces `Clone`; `Report` no longer implements `Clone`. +> CLI/JSON/format contracts remain unchanged. Partial remediation only; signature +> scratch, process/helper and other metadata paths remain open. See +> [confidential sender identity](security/CONFIDENTIAL_SENDER_IDENTITY.md). + > **Translation note:** This is the English translation of [`SPEC.md`](SPEC.md) (German), version > 2.22. Both versions are maintained together; every change to one is made to the other in the > same pull request. If they ever contradict each other, the German version applies until the diff --git a/docs/SPEC.md b/docs/SPEC.md index 53c201b..142d38f 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -1,5 +1,12 @@ # MASTER-PROJEKT-SPEZIFIKATION v2.23: PQKeep (Core, CLI & API) +> R7/R8-Arbeitsstand (#147, gemeinsamer PR #355): Geprüfte Absenderidentität wird +> fallibel in gesperrtem Speicher gehalten; Rust-API `SignedBy::key_id()` statt +> öffentlichem Vec-Feld, `try_duplicate()` statt `Clone`; `Report` ohne `Clone`. +> CLI-/JSON-/Formatverträge bleiben erhalten. Teilbehebung, kein Gesamtabschluss; +> Signatur-Scratch, Prozess-/Helper- und übrige Metadatenpfade weiter offen. +> Details: [vertrauliche Absenderidentität](security/CONFIDENTIAL_SENDER_IDENTITY.md). + > **English translation:** [`SPEC.en.md`](SPEC.en.md) – beide Fassungen werden im selben Pull Request gemeinsam geändert; bei Widersprüchen gilt bis zur Korrektur die deutsche. / Both versions are changed together in the same pull request; in case of contradiction the German one applies until fixed. > Änderung v2.19 (22.11.2026, Eigentümerauftrag zur autonomen Sicherheitsbehebung bis main): Secret-Speicher einschließlich KDF-/HKDF-Arbeitspuffern zwingend sperren; Fehler statt ungesperrtem Fallback, begrenzte Eingaben und sichere Freigabe. Keine Änderung von Format-/Ableitungsbytes. Details: [LOCKED_SECRETS.md](security/LOCKED_SECRETS.md). diff --git a/docs/security/ATTACK_TEST_MATRIX.md b/docs/security/ATTACK_TEST_MATRIX.md index 6d70c89..052d5ea 100644 --- a/docs/security/ATTACK_TEST_MATRIX.md +++ b/docs/security/ATTACK_TEST_MATRIX.md @@ -24,6 +24,7 @@ follows with the next baseline run. 1.4.0 adds QA1-FMT-012 (#316, PADMÉ padding): 62 cases; CI evidence follows likewise. 1.5.0 adds QA1-FMT-013 (#316/#340, anonymous recipients, experimental, partial): 63 cases. 1.6.0 adds QA1-FMT-014 (#316, hidden sender): 64 cases. +1.7.0 adds QA1-FMT-015 (#335, container integrity matrix); QA1-FMT-003 covered, QA1-REC-003 partial (kill test, limit L1 → #338): 65 cases. [Execution evidence](FAULT_RECOVERY_EVIDENCE.md) pins signed source/CI; broad original gaps stay open. ### Files, status and execution @@ -189,6 +190,7 @@ CI-Nachweis folgt mit dem nächsten Baseline-Lauf. 1.4.0 ergänzt QA1-FMT-012 (#316, Füllung nach PADMÉ): 62 Fälle; CI-Nachweis folgt ebenso. 1.5.0 ergänzt QA1-FMT-013 (#316/#340, anonyme Empfänger, experimentell, teilweise): 63 Fälle. 1.6.0 ergänzt QA1-FMT-014 (#316, verborgener Absender): 64 Fälle. +1.7.0 ergänzt QA1-FMT-015 (#335, Integritätsmatrix der Container); QA1-FMT-003 abgedeckt, QA1-REC-003 teilweise (Kill-Test, Grenze L1 → #338): 65 Fälle. [Ausführungsnachweise](FAULT_RECOVERY_EVIDENCE.md) verknüpfen Quelle/CI; breite Altlücken bleiben offen. ### Dateien, Status und Ausführung diff --git a/docs/security/CONFIDENTIAL_PATH_INDEX_VALIDATION.md b/docs/security/CONFIDENTIAL_PATH_INDEX_VALIDATION.md new file mode 100644 index 0000000..a858fda --- /dev/null +++ b/docs/security/CONFIDENTIAL_PATH_INDEX_VALIDATION.md @@ -0,0 +1,62 @@ +# Confidential path nodes / Vertrauliche Pfadknoten + +DE: Teilbehebung M2 des vor Code signierten und ausdrücklich freigegebenen +[gemeinsamen R7/R8-Plans](PROCESS_METADATA_COMPLETION_PLAN.md), Basis Mainb813bc6. +Kein vollständiger R7-/R8-Abschluss und kein Teilmerge. Stand: lokal entwickelt, +native CI/Windows/ARM64 und abschließender Gesamtvergleich stehen noch aus. +EN: Earlier protected path strings did not protect ordinary BTree node records. +This patch protects actual index node storage, not just their payload names. + +## Ownership and indexing / Ownership und Index + +DE: Vorher zwei Standard-BTreeSets: private Vergleichstexte gesperrt, Knoten mit +Owner-/Kindreferenzen ungeschützt. Jetzt ein intern balancierter AVL-Index mit +SecretState für Root/Belegung und SecretWorkspace für sämtliche Knoten. Nur +öffentliche Defaults vor der Sperre; Name/Dateiart/Links/Höhe danach setzen. +Kein frei zugänglicher Standard-BTree-Allocator, der die bisherigen Knoten vor +deren privater Befüllung sperren könnte. Kein neuer Kryptoalgorithmus/unsafe. +EN: Node indices give borrowed in-place rotations; no private node arrays returned +or moved as aggregate values. Balanced lookup retains logarithmic search depth; +no quadratic full scan for late file ancestors. No performance-parity claim. + +DE: Wachstum von16 Plätzen, Verdopplung begrenzt durch bestehendes MAX_ENTRIES. +Neues vollständiges Array vor privater Befüllung sperren. Schlüssel ausschließlich +fallibel in geschützte Ziele duplizieren; Recordfelder im gesperrten Slot setzen. +Erst nach vollständigem Erfolg den alten Owner ersetzen. Fehler zerstören nur +die teilweise neue Fläche; alter Baum/Root/Belegung bleiben gültig. Knoten löschen +verschachtelte Owner, anschließend löscht der vorhandene SecretBuffer auch die +gesamte frühere Kapazität/Padding vor Unlock/Free. +EN: Existing Unicode folding, sigma aliases, case conflicts, path/depth limits, +later directory parents and file-prefix conflicts are unchanged. Public PathSet +signatures remain unchanged; tests inspect the new single index without weakening +their original conflict/state/owner assertions. + +## Executed local evidence / Ausgeführte lokale Nachweise + +- DE: Aktueller API-Stand:4 Elternprüfungen grün, ein ausdrücklich durch den + Elternprozess ausgeführter ignorierter Kindeinstieg. Auf-/absteigende und + permutierte257-Einträge-Folgen gegen unabhängigen BTreeMap-Referenzindex; + jede Zwischenstufe mit AVL-Höhen-/Ordnungsprüfung, sämtliche Lookups und + zusätzliche lower-bound/Präfix-Gegenproben. +- EN: Actual State/node first/last addresses and nested key owners remain locked. + Explicit node field wipe observed while node allocation remains protected. +- DE: Isoliertes eigenes Kind: echter Unwind, exakte Sperrfreigabe, vorab gesperrte + Quellen und danach wirkliches RLIMIT_MEMLOCK.current=0. Tatsächlicher Indexaufruf + muss MemoryLock liefern, nicht skippen. Vorhandene Einträge/Belegung unverändert; + Sperren nach Drop exakt zurück auf Baseline, Elternlimit unverändert. +- EN: All14 existing path/component groups pass. Earlier no-API checkpoint passes + all54 file-module tests; later denial addition still requires final no-API/native + acceptance. Do not count an earlier compiled checkpoint as current source proof. +- DE: Strenges Linux-All-targets-Clippy mit/ohne API erfolgreich; nach Ergänzung + des echten Denial-/Unwind-Falls API-Clippy erneut erfolgreich. Root-/Plattform- + Formatierung und bisheriger Limit-/Diffcheck grün; Gesamtchecks vor Commit erneut. + +DE: Geschützte Vollprotokolle/Quellhashes unter +`analysis/issue-147-r7-r8-20261127T182246Z`: joint-local-v1/v2/v3, +implementation-plan-approval.json. Frühere Compile-/Test-Lintfehler erhalten: +alte interne Zwei-Baum-Testzugriffe und direkter Timeout-panic wurden korrigiert, +keine Suppression einer Produktionsregel. Der versehentliche All-workspace- +Formatter-Diff ist gesichert; alle21 betroffenen Vendor-Dateien bytegenau auf +den unveränderten Basisstand zurückgesetzt. +EN: No provider/algorithm/format/KDF/worker/gate changes. Registry, source/output +path ownership, report/progress/hidden-sender and process/helper rows remain open. diff --git a/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md b/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md new file mode 100644 index 0000000..edea4e6 --- /dev/null +++ b/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md @@ -0,0 +1,55 @@ +# Confidential sender identity / Vertrauliche Absenderidentität + +DE: Teilbehebung der Identitäts-Retention aus M4 im gemeinsamen R7/R8-PR355. +Keine vollständige M4-Abnahme: vertrauliche Signaturkodierung und -verifikation +haben weiterhin gesondert zu bearbeitende Provider-/Scratchpfade. M5-Ausgaben +und Reportzähler sind ebenfalls noch nicht vollständig geschützt. +EN: Local implementation in progress, not a complete R8 or issue147 closure. + +## Data flow / Datenfluss + +DE: Vorher kopierte hidden_sender den verborgenen öffentlichen Schlüssel aus +dem gesperrten Trailer in einen gewöhnlichen Signer.public_key-Vec. fingerprint +lieferte anschließend einen gewöhnlichen Schlüssel-ID-Vec; SignedBy erlaubte +Clone und Debug der Identität. Jetzt den geliehenen Trailer-Schlüssel direkt mit +LockedHash verarbeiten. Hashzustand und Ausgabe vor Befüllung sperren; +auch der SecretBytes-Owner des Ergebnisses liegt in einem vorab gesperrten +SecretState. Keine zwischenzeitliche Signer-/Schlüsselkopie und keine normale +Hashausgabe. Dieselbe Konstruktion gilt für den geprüften öffentlichen v3-Absender. +EN: Public v3 header Signer remains intentionally public and unchanged. Its +verified result uses the same protected identity type as hidden v4 senders. + +DE: Shared HiddenResult hält den tatsächlichen RefCell>-Slot +in stabilem SecretState. Rc teilt nur Ownership; kein frei kopierbarer Identitäts- +Payload. Leerer Slot vor der Sperre, danach store/take. Bei Ersetzung und Ende +werden verschachtelte Owner gelöscht, bevor SecretState die gesamten früheren +Recordbytes einschließlich Padding löscht und entsperrt. Die erwartete Identität +bei --signer wird ebenso fallibel gesperrt; Konstruktorfehler werden weitergegeben. +EN: Source key and caller-owned expected public-key inputs are borrowed; this +does not retrospectively lock caller allocations. Shared ownership is separate +from disclosure. No new dependency, unsafe code or cryptographic equation. + +## Rust migration / Rust-Migration + +DE: SignedBy.key_id: Vec wird durch eine private gesperrte Ownership und +SignedBy::key_id() -> &[u8] ersetzt. Ausgabe bewusst ausleihen, statt impliziter +Dereferenzierung oder Serialisierung. SignedBy::try_duplicate() -> Result +ersetzt Clone; Debug gibt nur SignedBy([REDACTED]) aus. Report implementiert deshalb +ebenfalls kein infallibles Clone mehr. Bestehende Rust-Caller müssen Feldzugriffe +in Methodenaufrufe ändern und gewünschte Kopien ausdrücklich fallibel behandeln. +EN: This is an intentional Rust source API change under the approved joint plan +and the open versioned-API work in #98. CLI text, JSON signer hex, authenticated +output order, header/trailer bytes and public key fingerprints stay compatible. + +## Acceptance / Abnahme + +DE: Eigene Tests vergleichen tatsächliche Hashbytes mit dem unabhängigen +öffentlichen Sha3_256-Digest, prüfen konkrete Owner-/erste-/letzte Byteadressen, +redigiertes Debug, unabhängige fallible Kopie und stabilen geteilten Ergebnis-Slot. +Zusätzlicher begrenzter Linux-Kindprozess prüft echten Unwind und tatsächliche +Sperrverweigerung für Duplikat, Ergebnis-Slot und Hashkonstruktion. Das Elternlimit +bleibt unverändert. Bereits gesperrte gemeinsame Seiten dürfen zunächst Erfolg +liefern; echte spätere Verweigerung ist zwingend, ohne Skip/Fallback. +EN: Tests and lint results are recorded separately with the exact source checkpoint +in the protected analysis directory. Native Windows/ARM64 and final joint acceptance +remain pending; compilation alone is not native execution. diff --git a/docs/security/CONTAINER_INTEGRITY_AUDIT.md b/docs/security/CONTAINER_INTEGRITY_AUDIT.md new file mode 100644 index 0000000..8d7a64c --- /dev/null +++ b/docs/security/CONTAINER_INTEGRITY_AUDIT.md @@ -0,0 +1,145 @@ +# Container-Integrität / Container integrity (#335) + +Deutsch zuerst, [English below](#english). + +**Stand:** 27.11.2026, Quelle `main` nach #353. **Art:** Audit (Code-Lesen) und Abgleich mit +vorhandenen Tests; keine Produktänderung. **Ergebnis:** kein ausnutzbarer Befund; Testlücken +G1–G7 werden in einem zweiten PR geschlossen, Grenzen L1–L3 bleiben dokumentiert. + +## Umfang + +Alle produktiven Lesepfade für `.pqkf`: `decrypt` (Datei, Ordner, Strom), `decrypt +--original-name` (`files::decrypt_original`), `check`, `list` und `inspect` – über alle Formate: +v1, v2 (mehrere Zugänge, Faktordatei), v3 (sichtbare Absender-Signatur), v4 (Strom, Füllung `PAD`, +anonyme Empfänger `ANON` – experimentell, verborgener Absender `HIDDEN_SENDER`). Nicht Teil: +Datei-Races beim Öffnen und Veröffentlichen (#338), Ressourcengrenzen und Fuzzing (#153), +Geheimnis-Lebensdauer im Speicher (#147). + +## Bausteine und Belege + +| Eigenschaft | Umsetzung (Code) | Beleg (Tests, Matrix) | +|---|---|---| +| Frischer Dateischlüssel je Datei | `aead::generate_key()` je Aufruf in `files/encrypt.rs` (`write_archive`, auch je Quelle bei `--each`) und `files/stream_v4.rs` | `crypto_stream::same_input_gives_different_ciphertext_with_new_key` (nur Ebene STREAM) → **G4** | +| Eindeutige Nonce | `crypto/stream.rs`: 7 Byte Zufallspräfix je Datei ‖ Zähler u32 (big endian) ‖ Kennung „letzter Block“; Zähler nur über `checked_add` | `crypto_stream::wrong_key_prefix_or_aad`; Grenze nur Code → **G7** | +| Zählergrenze | Nach Block 2^32 − 1 bricht `advance` mit `Error::Crypto` ab (Ver- wie Entschlüsseln), nie Wiederholung; Obergrenze ≈ 256 TiB | nur Code-Lesen (**G7**) | +| Hüllen der Zugänge | v1/v2: je Zugang zufällige 96-Bit-Nonce unter einmaligem KEK (Salz bzw. KEM-Chiffrat je Datei); v4 eigene Domäne `PQKeep/file/v4\0`; anonyme Zugänge eigener HKDF-Info | `files_v2_tamper::c04_*`, `files_anonymous`, QA1-FMT-004/-013 | +| Header als AAD | Strom-AAD = SHA3-256 des **neu kodierten** Headers (`FileHeader::stream_aad`, `HeaderV2::stream_aad`); daher muss der Parser kanonisch sein | v2: Fuzzer `pqkf_header_v2` verlangt `encode == gelesene Bytes`; v1: Fuzzer `pqkf_header` prüft nur erneutes Kodieren → **G1**; Byte-Kippen v1/v2 in `files_tamper_keys`, `files_v2_tamper` (teils Stichproben, QA1-FMT-003) → **G2** | +| Schlüsselbindung | v3 `commit` im Absenderblock, v4 `commit` in jedem Header, geprüft vor dem Strom (`check_commit`, `check_commit_v4`) | `files_signed`, `files_stream_v4`, QA1-FMT-010/-011 | +| Abschluss | STREAM: letzter Block mit Kennung 1, Leser erkennt ihn per Vorauslesen (`stream_io::refill`), Datei mit exakter Blockvielfacher-Länge endet mit leerem letzten Block; Archiv: Ende-Eintrag mit Eintragszahl, danach nichts (`DecryptReader::finish`); v4: Trailer `U64 ‖ U64 ‖ PQKFEND\0`, Füllung nur Nullbytes, kanonische Länge, ggf. Absenderblock | `crypto_stream::{truncated_and_appended, exact_multiple_cannot_be_cut_at_boundary, swapped_and_removed_chunks}`, `tail_v4_tests`, QA1-REC-001 | +| Prüfsumme je Datei im Archiv | SHA3-256 je Eintrag (`ArchiveReader::copy_file`), zusätzlich zur AEAD | QA1-REC-001 | +| Veröffentlichung erst nach voller Prüfung | Datei: `write_file` → Archivende, `finish`, Signatur (`verify`) → `TempOutput::publish`; Ordner: `fill_dir` → `finish` → `verify` → `publish`; Strom: `copy_payload` (Trailer, ggf. verborgener Absender) → kürzen → `verify` → `publish`; Originalname: gleiche Funktionen, dann `publish_child` | QA1-REC-007/-008/-012, `files_output`, `files_original` | +| Keine Ausgabe bei Fehler | `TempOutput` entfernt bei `Drop` nur die eigene Temporärausgabe (`.name.tmp-…`, Linux 0600); das Ziel erscheint nie | QA1-REC-008/-009/-010 | +| `check`/`list` | `scan::read` liest vollständig wie `decrypt` (Archivende, Trailer, Signatur); `list` gibt Einträge nur nach Erfolg zurück | `files_check`, `files_list`, QA1-REC-004 | +| Signatur v3 / verborgener Absender | v3: Hash über Header ‖ Chiffrat, Signatur am Dateiende, Prüfung vor dem Veröffentlichen; v4 verborgen: Hash über Klartext in gesperrtem Speicher, Prüfung im Trailer vor dem Veröffentlichen | `files_signed`, `files_hidden_sender`, QA1-FMT-010/-014 | + +## Matrix Format × Pfad + +✔ = Schutz im Code und Test vorhanden; ◐ = Schutz im Code, Test lückenhaft (Lücke in Klammern); +— = Pfad gibt es für dieses Format nicht. + +| Format | decrypt Datei/Ordner | decrypt Strom | --original-name | check | list | +|---|---|---|---|---|---| +| v1 | ✔ (G1) | — | ✔ | ✔ | ✔ | +| v2 | ✔ | — | ✔ | ✔ | ✔ | +| v3 | ◐ (G2, G3) | — | ◐ (G2) | ✔ | ◐ (G2) | +| v4 Datei/Ordner (PAD/ANON/HIDDEN) | ◐ (G2, G3, G5) | — | ◐ (G2) | ✔ | ◐ (G2) | +| v4 Strom (auch PAD/HIDDEN) | — | ◐ (G3, G5) | abgewiesen ✔ | ✔ | nur Bytes ✔ | + +Alle Pfade: Abbruch durch Kill (G6), Frische (G4), Zählergrenze (G7). + +## Lücken und Stand + +Stand nach PR 2 (#335): **G1–G6 geschlossen, ohne Befund** – alle Varianten werden abgewiesen, nie +eine Ausgabe. Belege: `fuzz/fuzz_targets/pqkf_header.rs` (G1, verlangt `encode == gelesene Bytes`; +lokal 5,8 Mio. Läufe mit echten v1-Headern als Startdaten), `tests/integrity_headers.rs` (G2, jedes +Header-Byte aller acht Formatvarianten mit `decrypt`, reihum `check`/`list`/`--original-name`), +`tests/integrity_chunks.rs` (G3, G4), `src/files/recovery_v4_tests.rs` (G5), +`tests/integrity_kill.rs` (G6, Linux). Offen: **G7** (nach #147). Angriffsmatrix 1.7.0: +QA1-FMT-003 abgedeckt, QA1-REC-003 teilweise (Grenze L1), neu QA1-FMT-015. + + +- **G1** v1-Header-Fuzzer prüft nur, dass erneutes Kodieren stabil ist, nicht `encode == gelesene + Bytes` wie bei v2. Da die AAD aus dem neu kodierten Header entsteht, soll auch v1 strikt + kanonisch belegt sein (Fuzz-Ziel und Test). +- **G2** Jedes Header-Byte kippen ist für v1 (`check`) belegt, für v2 teils Stichproben, für v3/v4 + nicht vollständig – und nicht für alle Pfade (`decrypt`, `check`, `list`, `--original-name`). +- **G3** Blöcke tauschen, doppeln, entfernen und an jeder Blockgrenze abschneiden ist nur auf + Ebene STREAM getestet; auf Dateiebene fehlen Archiv und Strom mit Füllung bzw. verborgenem + Absender, Abschneiden **im** Trailer und ein Block aus einer zweiten Datei. +- **G4** Frische nur auf Ebene STREAM: zweimal dieselbe Quelle soll auch auf Dateiebene anderen + Präfix, andere Schlüsselbindung und anderes Chiffrat ergeben (v1–v4). +- **G5** Fehlerpläne beim Entschlüsseln (QA1-REC-008) decken v1/v2 ab; v4-Strom und v4-Archiv mit + Füllung bzw. verborgenem Absender fehlen. +- **G6** Kill während `decrypt` (QA1-REC-003): Ziel darf nie erscheinen; ein Temporärrest muss + beim nächsten Lauf erkannt werden (Linux). +- **G7** Zählergrenze nur durch Code-Lesen belegt; ein Test bräuchte einen Test-Zugang in + `src/crypto` – erst nach #147, um dessen Umbau nicht zu stören. + +## Hinweis (kein Befund) + +- `fill_dir` summiert `report.bytes` ohne `checked_add`, `scan::directory` mit. Ein Überlauf + bräuchte 2^64 tatsächlich gelesene Bytes, ist also nicht erreichbar; Angleichen optional (eigene + Freigabe, Produktivcode). + +## Grenzen (bleiben) + +- **L1** Nach Kill, Absturz oder Stromausfall kann **temporärer Klartext** (versteckter Name, + Linux 0600) bleiben; es gibt keine sichere Löschung. Er wird nie unter dem Zielnamen + veröffentlicht. +- **L2** Veröffentlichung von Ordnern sowie der Weg ohne Hardlinks (z. B. FAT) sind „prüfen und + umbenennen“, nicht atomar → #338. +- **L3** Ältere, schon veröffentlichte Programmversionen werden nicht ausgeführt (QA1-FMT-008); + sie melden neue Formate laut Code als „nicht unterstützt“. + +--- + +## English + +**Status:** 2026-11-27, source `main` after #353. **Kind:** audit (code reading) and comparison +with existing tests; no product change. **Result:** no exploitable finding; test gaps G1–G7 are +closed in a second PR, limits L1–L3 stay documented. + +**Scope:** all productive read paths for `.pqkf` – `decrypt` (file, directory, stream), `decrypt +--original-name`, `check`, `list`, `inspect` – across v1, v2 (several slots, factor file), v3 +(visible sender signature) and v4 (stream, padding `PAD`, anonymous recipients `ANON` – +experimental, hidden sender `HIDDEN_SENDER`). Not covered: file races when opening and +publishing (#338), resource limits and fuzzing (#153), secret lifetime in memory (#147). + +**Building blocks:** fresh file key per file (`aead::generate_key()` per call, also per source +with `--each`); nonce = 7-byte random prefix per file ‖ u32 counter (big endian) ‖ last flag, the +counter only advances via `checked_add` and aborts after chunk 2^32 − 1 (≈ 256 TiB) instead of +repeating; slot wraps use random 96-bit nonces under single-use KEKs (per-file salt or KEM +ciphertext), v4 with its own domain; the stream AAD is SHA3-256 of the **re-encoded** header, so +the parser must be canonical (v2 fuzzer requires `encode == bytes read`, v1 fuzzer only checks +stable re-encoding → G1); key commitment (v3 sender block, every v4 header) is checked before the +stream; end detection via the last flag (read-ahead; an exact chunk multiple ends with an empty +last chunk), the archive end entry with entry count and nothing after it, and for v4 the trailer +(zero-only canonical padding, optional sender block); per-entry SHA3-256 in archives; publication +only after complete verification (archive end, `finish`, signature) via `TempOutput`, which on +`Drop` removes only its own temporary output (`.name.tmp-…`, Linux 0600) – the target never +appears; `check`/`list` read completely like `decrypt`, `list` returns entries only on success; +v3 signature over header ‖ ciphertext, hidden sender over the plaintext hash, both verified before +publishing. Evidence: tests and attack cases listed in the German table above. + +**Matrix:** v1 and v2 are covered on all paths (v1 header canonicality G1); v3, v4 files/ +directories and v4 streams are protected in code, with test gaps G2 (every header byte on all +paths), G3 (file-level chunk swap/duplicate/remove, cuts at every boundary and inside the trailer, +a chunk from a second file) and G5 (fault plans for v4); all paths: kill during decrypt (G6), +freshness at file level (G4), counter limit (G7, code reading only – a test needs a test hook in +`src/crypto`, deferred until after #147). + +**Status after PR 2 (#335): G1–G6 closed, no finding** – every variant is rejected, never any +output (evidence: `fuzz/fuzz_targets/pqkf_header.rs`, `tests/integrity_headers.rs`, +`tests/integrity_chunks.rs`, `src/files/recovery_v4_tests.rs`, `tests/integrity_kill.rs`); open: G7 +(after #147). Attack matrix 1.7.0: QA1-FMT-003 covered, QA1-REC-003 partial (limit L1), new +QA1-FMT-015. + +**Note (no finding):** `fill_dir` sums `report.bytes` without `checked_add` (`scan::directory` +uses it); an overflow needs 2^64 bytes actually read and is unreachable; aligning is optional and +needs its own approval. + +**Limits:** L1 after kill, crash or power loss **temporary plaintext** (hidden name, Linux 0600) +may remain – no secure deletion, never published under the target name; L2 directory +publication and the path without hard links (e.g. FAT) are check-and-rename, not atomic → #338; +L3 already released old versions are not executed (QA1-FMT-008); by code they report new formats +as "unsupported". diff --git a/docs/security/WINDOWS_PROCESS_ACCESS_PROBE_PLAN.md b/docs/security/WINDOWS_PROCESS_ACCESS_PROBE_PLAN.md new file mode 100644 index 0000000..332ce3c --- /dev/null +++ b/docs/security/WINDOWS_PROCESS_ACCESS_PROBE_PLAN.md @@ -0,0 +1,65 @@ +# Windows own-process access probe / Eigene Windows-Prozessprobe + +DE: Konkrete technische Probe unter P2 des freigegebenen gemeinsamen R7/R8-Plans. +Kein Produktions-Gate und kein R7-Abschluss. Neue Rechteänderung ausschließlich +am eigenen kurzlebigen Windows-CI-Testprozess benötigt eine zusätzliche konkrete +Freigabe gemäß globaler AGENTS.md. Vor dieser Freigabe Workflow nicht pushen/ausführen. +EN: Local source development and cross compilation only until that approval. + +## Action / Aktion + +DE: Neuer eigener Kindprozess `process_access_probe target` öffnet vor der Änderung +ein eigenes nicht vererbbares READ_CONTROL/WRITE_DAC-Handle. Anschließend setzt +er ausschließlich seine Prozessobjekt-DACL auf die feste öffentliche SDDL +`D:P(A;;0x00121001;;;OW)` und liest den tatsächlichen Descriptor zurück. +Owner Rights ersetzt implizite Besitzerrechte; ausdrücklich erlaubt bleiben nur +ReadControl, Synchronize, QueryLimited und Terminate. Kein Token-/Konten-/Thread-/ +Registry-/Datei-/Dienstrecht wird verändert. Kein Privileg wird aktiviert. +EN: The second owned inspector attempts only OpenProcess, never memory reading, +writing, thread creation or handle duplication. Sensitive rights must return +AccessDenied; limited query/synchronization must remain available. + +DE: Das PowerShell-Skript prüft die vom eigenen Process-Objekt gehaltene PID gegen +die feste READY-Zeile und beendet/reapt ausschließlich beide selbst gestarteten +Kinder. Je Start/Prüfung/Exit zehn Sekunden, eigener Kill/Wait im finally, Joblimit +15 Minuten. Keine unbekannten Zielprozesse, keine Geheimnisse/Testschlüssel. +EN: No installation, administrator command, sudo, credentials or network endpoint. + +## Files and risk / Dateien und Risiko + +- `platform/pqkeep-platform/examples/process_access_probe.rs`: nur explizites Beispiel, + Feature `process-access-probe`, vorhandenes windows-sys0.61.2. +- `scripts/test_process_access_probe.ps1`: begrenzter Besitzer-/Inspektorprozess. +- `.github/workflows/process-access-probe.yml`: Windows-CI, contents:read, + gepinnter bestehender Checkout, kein persistiertes Git-Credential. +- `platform/pqkeep-platform/Cargo.toml`: ausschließlich Dev-Feature/Win32-Authorization. + +DE: Die Probe kann Zugriff des eigenen Besitzers auf das Prozessobjekt einschränken. +Das ist beabsichtigt und wird durch den zweiten eigenen Prozess getestet. Ein vorab +geöffnetes Handle bleibt bis zum normalen Ende gehalten. Elternprozess und übrige +Runner-Prozesse werden nicht verändert; bei Fehler beendet nur der eigene Parent +seine beiden bereits gehaltenen Kinder. Neue FFI-Stellen sind einzeln begründet. +EN: No policy application in the normal CLI/library path or implicit example execution. + +## Backup and return / Sicherung und Rückweg + +DE: Keine persistente Systemkonfiguration wird geschrieben; Prozessende beseitigt +das Testobjekt. Bestehende System-/Konten-/Registry-ACLs bleiben unberührt. Original- +Main und signierter Plan bleiben erhalten; lokale Quellen/Proposal werden vollständig +mit Hashes gesichert. Bei abgelehnter Probe: Workflow nicht veröffentlichen. +EN: Do not weaken a live process policy as an automatic recovery. Terminate only +the own ephemeral test process; no machine rollback or host restart is needed. + +## Limits / Grenzen + +DE: Selbst erfolgreiche OpenProcess-Verweigerung beweist weder Schutz bestehender +Handles noch Thread-Kontextschutz, WER/LocalDumps-Abwehr, IME-/GUI-Sicherheit oder +Schutz gegen privilegierte Zugriffe. Diese Flächen bleiben eigene R7-Abnahmezeilen. +Keine dieser Grenzen wird aufgrund dieser Probe als geschlossen markiert. +EN: Native execution is mandatory; a successful cross check is not that execution. + +Primary sources / Primärquellen: +- https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights +- https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-special-identities-groups +- https://learn.microsoft.com/en-us/windows/win32/secauthz/sid-strings +- https://learn.microsoft.com/en-us/windows/win32/wer/collecting-user-mode-dumps diff --git a/docs/security/attack-baseline.json b/docs/security/attack-baseline.json index 51e290f..273a621 100644 --- a/docs/security/attack-baseline.json +++ b/docs/security/attack-baseline.json @@ -1,7 +1,7 @@ { "schema_version": 1, - "baseline_version": "1.6.0", - "matrix_version": "1.6.0", + "baseline_version": "1.7.0", + "matrix_version": "1.7.0", "evidence": [ { "id": "B1-linux-x86_64", diff --git a/docs/security/attack-matrix.json b/docs/security/attack-matrix.json index f8cd96b..f83f899 100644 --- a/docs/security/attack-matrix.json +++ b/docs/security/attack-matrix.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "matrix_version": "1.6.0", + "matrix_version": "1.7.0", "reviewed_source_commit": "ab65cd0cf736366acf2d6fad8569fe76b291c2da", "cases": [ { @@ -980,7 +980,7 @@ "en": "v1 decrypt samples every seventh header byte; check mutates every byte of a small v1 file. v2 coverage varies by access path." }, "implementation_state": "implemented", - "coverage_status": "partial", + "coverage_status": "covered", "automation": "automated", "platforms": [ "linux-x86_64", @@ -1025,6 +1025,30 @@ "symbol": "mutated_file_never_panics_or_leaks", "kind": "rust-integration", "stage": "existing" + }, + { + "path": "tests/integrity_headers.rs", + "symbol": "v1_and_v2_headers", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "tests/integrity_headers.rs", + "symbol": "v3_header_with_visible_sender", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "tests/integrity_headers.rs", + "symbol": "v4_file_headers", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "tests/integrity_headers.rs", + "symbol": "v4_stream_headers", + "kind": "rust-integration", + "stage": "existing" } ], "ci_refs": [ @@ -1043,7 +1067,8 @@ ], "priority": "P1", "issues": [ - 151 + 151, + 335 ], "v2_ids": [], "evidence_refs": [ @@ -1051,14 +1076,8 @@ "B1-windows-x86_64", "B1-linux-arm64" ], - "gap": { - "de": "v1-Decrypt testet jedes siebte Headerbyte; check jedes Byte einer kleinen v1-Datei. v2 je Zugang teils Stichproben.", - "en": "v1 decrypt samples every seventh header byte; check mutates every byte of a small v1 file. v2 coverage varies by access path." - }, - "next_evidence": { - "de": "Konkrete fehlende Variante im verknüpften Issue prüfen; keine Produktänderung in #151.", - "en": "Review the missing variant in the linked issue; no production change in #151." - }, + "gap": null, + "next_evidence": null, "retired": false, "replacement": null }, @@ -3187,13 +3206,12 @@ "de": "Drop läuft bei SIGKILL/Abort nicht; temporärer Klartext kann bleiben, Dauerhaftigkeit ist nicht bewiesen.", "en": "Drop does not run on SIGKILL/abort; temporary plaintext may remain and durability is unproven." }, - "implementation_state": "documented-only", - "coverage_status": "missing", - "automation": "automatable", + "implementation_state": "implemented", + "coverage_status": "partial", + "automation": "automated", "platforms": [ "linux-x86_64", - "linux-arm64", - "windows-x86_64" + "linux-arm64" ], "features": [ "default", @@ -3203,21 +3221,42 @@ "de": "Nur synthetische Testdaten; OS-/Featurebedingungen der referenzierten Tests beachten.", "en": "Synthetic test data only; observe OS/feature conditions of referenced tests." }, - "test_refs": [], - "ci_refs": [], + "test_refs": [ + { + "path": "tests/integrity_kill.rs", + "symbol": "killed_decrypt_never_publishes_the_target", + "kind": "rust-integration", + "stage": "existing" + } + ], + "ci_refs": [ + { + "workflow": ".github/workflows/ci.yml", + "job": "test", + "matrix_filter": [ + "ubuntu-latest", + "ubuntu-22.04", + "ubuntu-22.04-arm" + ], + "gate": "required-except-arm64", + "stage": "existing" + } + ], "priority": "P1", "issues": [ - 152 + 152, + 335, + 338 ], "v2_ids": [], "evidence_refs": [], "gap": { - "de": "Drop läuft bei SIGKILL/Abort nicht; temporärer Klartext kann bleiben, Dauerhaftigkeit ist nicht bewiesen.", - "en": "Drop does not run on SIGKILL/abort; temporary plaintext may remain and durability is unproven." + "de": "Nach SIGKILL kann temporärer Klartext (versteckter Name, 0600) bleiben; Stromausfall/Dauerhaftigkeit nicht belegbar; Windows-Kill nicht automatisiert.", + "en": "After SIGKILL temporary plaintext (hidden name, 0600) may remain; power loss/durability cannot be proven; Windows kill not automated." }, "next_evidence": { - "de": "Konkrete fehlende Variante im verknüpften Issue prüfen; keine Produktänderung in #151.", - "en": "Review the missing variant in the linked issue; no production change in #151." + "de": "#338: namenlose Temporärdatei (O_TMPFILE + linkat) bzw. Windows „beim Schließen löschen“; Vollverschlüsselung empfohlen.", + "en": "#338: unnamed temporary file (O_TMPFILE + linkat) or Windows delete-on-close; full-disk encryption recommended." }, "retired": false, "replacement": null @@ -5765,6 +5804,103 @@ "next_evidence": null, "retired": false, "replacement": null + }, + { + "id": "QA1-FMT-015", + "category": "Container", + "component_paths": [ + "src/crypto/stream.rs", + "src/crypto/stream_io.rs", + "src/files/decrypt.rs", + "src/files/output.rs", + "src/files/tail_v4.rs", + "docs/security/CONTAINER_INTEGRITY_AUDIT.md" + ], + "scenario": { + "de": "Integritätsmatrix aller Formate (v1–v4 inkl. Strom, Füllung, sichtbarer/verborgener Absender, anonymer Empfänger) auf Dateiebene: Blöcke tauschen, doppeln, entfernen, an jeder Blockgrenze abschneiden, anhängen, Blöcke einer zweiten Datei einsetzen; dieselbe Quelle zweimal verschlüsseln; Fehler beim Schreiben/Synchronisieren/Veröffentlichen während decrypt von v4; v1-Header nicht kanonisch kodieren", + "en": "Integrity matrix of all formats (v1–v4 incl. stream, padding, visible/hidden sender, anonymous recipients) at file level: swap, duplicate, remove chunks, cut at every chunk boundary, append, insert chunks of a second file; encrypt the same source twice; write/sync/publish failures during v4 decrypt; encode a v1 header non-canonically." + }, + "expected_behavior": { + "de": "decrypt und check scheitern ohne Ausgabe und ohne Temporärrest; zweimal verschlüsselt ergibt anderen Präfix, andere Schlüsselbindung (v4) und anderes Chiffrat; Fehler veröffentlichen nie ein Ziel; nur kanonische v1-Header werden gelesen", + "en": "decrypt and check fail without output and without temporary leftovers; encrypting twice gives a different prefix, key commitment (v4) and ciphertext; failures never publish a target; only canonical v1 headers are read" + }, + "boundary": { + "de": "Die Zählergrenze (2^32 Blöcke) ist nur durch Code-Lesen belegt (Test-Zugang in src/crypto erst nach #147); Datei-Races beim Veröffentlichen gehören zu #338.", + "en": "The counter limit (2^32 chunks) is only established by code reading (test hook in src/crypto only after #147); file races while publishing belong to #338." + }, + "implementation_state": "implemented", + "coverage_status": "covered", + "automation": "automated", + "platforms": [ + "linux-x86_64", + "linux-arm64", + "windows-x86_64" + ], + "features": [ + "default", + "no-default" + ], + "preconditions": { + "de": "Nur synthetische Testdaten; OS-/Featurebedingungen der referenzierten Tests beachten.", + "en": "Synthetic test data only; observe OS/feature conditions of referenced tests." + }, + "test_refs": [ + { + "path": "tests/integrity_chunks.rs", + "symbol": "chunk_manipulations_fail_on_every_format", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "tests/integrity_chunks.rs", + "symbol": "same_source_twice_is_fresh_on_every_format", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "tests/integrity_headers.rs", + "symbol": "unchanged_files_open_on_every_path", + "kind": "rust-integration", + "stage": "existing" + }, + { + "path": "src/files/recovery_v4_tests.rs", + "symbol": "rec008_v4_decrypt_failures_never_publish", + "kind": "rust-unit", + "stage": "existing" + }, + { + "path": "fuzz/fuzz_targets/pqkf_header.rs", + "symbol": "fuzz_target!", + "kind": "fuzz", + "stage": "existing" + } + ], + "ci_refs": [ + { + "workflow": ".github/workflows/ci.yml", + "job": "test", + "matrix_filter": [ + "ubuntu-latest", + "ubuntu-22.04", + "ubuntu-22.04-arm", + "windows-latest" + ], + "gate": "required-except-arm64", + "stage": "existing" + } + ], + "priority": "P1", + "issues": [ + 151, + 335 + ], + "v2_ids": [], + "evidence_refs": [], + "gap": null, + "next_evidence": null, + "retired": false, + "replacement": null } ] } diff --git a/fuzz/fuzz_targets/pqkf_header.rs b/fuzz/fuzz_targets/pqkf_header.rs index cb6a59d..2237efc 100644 --- a/fuzz/fuzz_targets/pqkf_header.rs +++ b/fuzz/fuzz_targets/pqkf_header.rs @@ -1,5 +1,7 @@ -//! DE: Header-Parser von `.pqkf`-Dateien: nie Panik; gültige Header kodieren sich identisch. -//! EN: `.pqkf` header parser: never panic; valid headers re-encode identically. +//! DE: Header-Parser von `.pqkf`-Dateien (v1): nie Panik; gültige Header kodieren sich byte-genau +//! wie gelesen (kanonisch – die Strom-AAD entsteht aus dem neu kodierten Header, #335 G1). +//! EN: `.pqkf` header parser (v1): never panic; valid headers re-encode byte-exactly as read +//! (canonical – the stream AAD is derived from the re-encoded header, #335 G1). #![no_main] use std::io::Cursor; @@ -10,7 +12,9 @@ use pqkeep::files::FileHeader; fuzz_target!(|data: &[u8]| { let mut cursor = Cursor::new(data); if let Ok(header) = FileHeader::read(&mut cursor) { + let consumed = usize::try_from(cursor.position()).expect("position"); let encoded = header.encode(); + assert_eq!(encoded, data[..consumed]); let again = FileHeader::read(&mut Cursor::new(&encoded)).expect("reparse"); assert_eq!(again.encode(), encoded); } diff --git a/platform/pqkeep-platform/Cargo.toml b/platform/pqkeep-platform/Cargo.toml index a159056..23ad80b 100644 --- a/platform/pqkeep-platform/Cargo.toml +++ b/platform/pqkeep-platform/Cargo.toml @@ -11,11 +11,17 @@ description = "Narrow synchronous platform adapters for PQKeep" windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] } [target.'cfg(windows)'.dev-dependencies] -windows-sys = { version = "=0.61.2", features = ["Win32_Security"] } +windows-sys = { version = "=0.61.2", features = ["Win32_Security", "Win32_Security_Authorization"] } [features] # DE/EN: Ausschließlich feste öffentliche Testereignisse / fixed public test events only. native-input-fixture = [] +# DE/EN: Nur ausdrücklich gestartete öffentliche Prozessprobe / explicitly run public probe only. +process-access-probe = [] + +[[example]] +name = "process_access_probe" +required-features = ["process-access-probe"] [lints.rust] unsafe_op_in_unsafe_fn = "deny" diff --git a/platform/pqkeep-platform/examples/process_access_probe.rs b/platform/pqkeep-platform/examples/process_access_probe.rs new file mode 100644 index 0000000..4f9b950 --- /dev/null +++ b/platform/pqkeep-platform/examples/process_access_probe.rs @@ -0,0 +1,161 @@ +//! DE: Öffentliche, ausdrücklich gestartete Prozessobjekt-Probe; kein Produktions-Gate. +//! Keine Threadsperre, Alt-Handle-Rücknahme, WER-/Dump-Garantie oder R7-Abnahme. +//! EN: Public explicitly invoked process-object probe, not a production gate. +//! No thread protection, existing-handle revocation, dump guarantee or R7 acceptance. + +#[cfg(windows)] +mod windows { + use std::io::{self, Read, Write}; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use windows_sys::Win32::Foundation::{HANDLE, LocalFree}; + use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW; + use windows_sys::Win32::Security::{ + DACL_SECURITY_INFORMATION, GetKernelObjectSecurity, PROTECTED_DACL_SECURITY_INFORMATION, + PSECURITY_DESCRIPTOR, SetKernelObjectSecurity, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, OpenProcess}; + + const READ_CONTROL: u32 = 0x0002_0000; + const WRITE_DAC: u32 = 0x0004_0000; + // DE: Nur QueryLimited/Terminate/Synchronize/ReadControl für den Besitzer. + // EN: Owner gets QueryLimited/Terminate/Synchronize/ReadControl only. + const POLICY: windows_sys::core::PCWSTR = windows_sys::w!("D:P(A;;0x00121001;;;OW)"); + + struct Descriptor(PSECURITY_DESCRIPTOR); + + impl Drop for Descriptor { + fn drop(&mut self) { + // SAFETY: Successful ConvertStringSecurityDescriptor allocated this exact + // pointer with LocalAlloc; one owner, no use after this destructor. + unsafe { LocalFree(self.0) }; + } + } + + fn open(pid: u32, rights: u32) -> io::Result { + // SAFETY: Public process ID and documented access mask; never inherit. + let handle = unsafe { OpenProcess(rights, 0, pid) }; + if handle.is_null() { + return Err(io::Error::last_os_error()); + } + // SAFETY: OpenProcess returned a new, valid, uniquely owned real handle. + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) + } + + fn descriptor() -> io::Result<(Descriptor, u32)> { + let (mut descriptor, mut length) = (std::ptr::null_mut(), 0); + // SAFETY: Static NUL-terminated public SDDL, revision1, initialized exclusive + // out parameters. The API allocates only on success; ownership goes to Descriptor. + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + POLICY, + 1, + &raw mut descriptor, + &raw mut length, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + if descriptor.is_null() { + return Err(io::Error::other("missing descriptor")); + } + Ok((Descriptor(descriptor), length)) + } + + fn restrict(handle: HANDLE) -> io::Result<()> { + let (descriptor, length) = descriptor()?; + if !(20..=256).contains(&length) { + return Err(io::Error::other("unexpected public descriptor length")); + } + // SAFETY: Live own-process handle opened with WRITE_DAC; complete valid + // descriptor retained through this synchronous call; no other object touched. + if unsafe { + SetKernelObjectSecurity( + handle, + DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + descriptor.0, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // DE/EN: Ausschließlich feste öffentliche Policybytes / fixed public policy only. + let (mut actual, mut needed) = ([0u32; 64], 0); + // SAFETY: Retained handle has READ_CONTROL. The initialized destination + // is256bytes with DWORD alignment, exactly matching nLength; + // out count is exclusively borrowed. + if unsafe { + GetKernelObjectSecurity( + handle, + DACL_SECURITY_INFORMATION, + actual.as_mut_ptr().cast(), + 256, + &raw mut needed, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // SAFETY: Conversion reported a live allocation of length bytes; validated + //20..=256 above; Descriptor retains ownership throughout this borrow. + let expected = + unsafe { std::slice::from_raw_parts(descriptor.0.cast::(), length as usize) }; + // SAFETY: Initialized64-DWORD array owns256bytes; u8 permits every + // bit pattern and alignment; immutable view does not outlive the array. + let actual = unsafe { std::slice::from_raw_parts(actual.as_ptr().cast::(), 256) }; + if needed != length || actual.get(..needed as usize) != Some(expected) { + return Err(io::Error::other("process descriptor readback mismatch")); + } + Ok(()) + } + + fn target() -> io::Result<()> { + // SAFETY: No arguments/pointers; returns only this process's public ID. + let pid = unsafe { GetCurrentProcessId() }; + let handle = open(pid, READ_CONTROL | WRITE_DAC)?; + restrict(handle.as_raw_handle())?; + writeln!(io::stdout(), "READY {pid}")?; + io::stdout().flush()?; + // DE: Nur öffentlicher Steuerkanal, keine Geheimnisse; EOF beendet die Probe. + // EN: Public control only, no secrets; EOF terminates the probe. + let mut control = [0u8; 1]; + let _ = io::stdin().read(&mut control)?; + Ok(()) + } + + fn inspect(pid: u32) -> io::Result<()> { + for rights in [0x10, 0x20, 0x08, 0x40, 0x02, WRITE_DAC, 0x80000] { + match open(pid, rights) { + Ok(_) => return Err(io::Error::other("sensitive process access allowed")), + Err(error) if error.raw_os_error() == Some(5) => (), + Err(_) => return Err(io::Error::other("unexpected process query failure")), + } + } + let _query = open(pid, 0x1000 | 0x0010_0000)?; + println!("PASS: sensitive access denied; limited query and synchronization allowed"); + Ok(()) + } + + pub(super) fn run() -> io::Result<()> { + let mut args = std::env::args().skip(1); + match (args.next().as_deref(), args.next()) { + (Some("target"), None) => target(), + (Some("inspect"), Some(pid)) if args.next().is_none() => inspect( + pid.parse() + .map_err(|_| io::Error::other("invalid process ID"))?, + ), + _ => Err(io::Error::other("invalid public probe arguments")), + } + } +} + +#[cfg(windows)] +fn main() -> std::io::Result<()> { + windows::run() +} + +#[cfg(not(windows))] +fn main() { + eprintln!("DE/EN: Nur Windows-Prozessprobe / Windows process probe only"); + std::process::exit(2); +} diff --git a/scripts/test_process_access_probe.ps1 b/scripts/test_process_access_probe.ps1 new file mode 100644 index 0000000..06d4b11 --- /dev/null +++ b/scripts/test_process_access_probe.ps1 @@ -0,0 +1,54 @@ +# DE: Nur eigene kurzlebige öffentliche Testprozesse; keine Geheimnisse oder Hoständerung. +# EN: Owned short-lived public test processes only; no secrets or host settings. +$ErrorActionPreference = 'Stop' + +function New-Probe([string[]]$Arguments) { + $start = [System.Diagnostics.ProcessStartInfo]::new() + $start.FileName = (Resolve-Path 'target/debug/examples/process_access_probe.exe').Path + $start.UseShellExecute = $false + $start.RedirectStandardInput = $true + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + foreach ($argument in $Arguments) { $start.ArgumentList.Add($argument) } + $process = [System.Diagnostics.Process]::new() + $process.StartInfo = $start + if (-not $process.Start()) { throw 'Probe did not start' } + return $process +} + +function Stop-OwnedProbe($Process) { + if ($null -ne $Process) { + if (-not $Process.HasExited) { + $Process.Kill() + if (-not $Process.WaitForExit(5000)) { throw 'Owned probe did not terminate' } + } + $Process.Dispose() + } +} + +$target = $null +$inspector = $null +try { + $target = New-Probe -Arguments @('target') + $ready = $target.StandardOutput.ReadLineAsync() + if (-not $ready.Wait(10000)) { throw 'Own target readiness timeout' } + if ($ready.Result -cne "READY $($target.Id)") { throw 'Own target identity mismatch' } + $inspector = New-Probe -Arguments @('inspect', [string]$target.Id) + $inspector.StandardInput.Close() + if (-not $inspector.WaitForExit(10000)) { throw 'Own inspector timeout' } + $result = $inspector.StandardOutput.ReadToEnd() + if ($inspector.ExitCode -ne 0 -or -not $result.StartsWith('PASS:')) { + throw 'Own inspector rejected process access policy' + } + $target.StandardInput.Close() + if (-not $target.WaitForExit(10000)) { throw 'Own target exit timeout' } + if ($target.ExitCode -ne 0) { throw 'Own target rejected policy readback' } + Write-Output ($result.Trim()) + Write-Output 'PASS: only own target DACL changed; both owned children exited' +} finally { + try { + Stop-OwnedProbe $inspector + } finally { + Stop-OwnedProbe $target + } +} diff --git a/src/cli/files_json.rs b/src/cli/files_json.rs index 9c353df..cfb4573 100644 --- a/src/cli/files_json.rs +++ b/src/cli/files_json.rs @@ -64,7 +64,7 @@ fn body(entries: &[(Value, Option, Outcome)]) -> (Map, u /// (hex) or `null` (#44). pub(super) fn signer(r: &Report) -> Value { r.signer.as_ref().map_or(Value::Null, |s| { - pqkeep::envelope::hex_encode(&s.key_id).into() + pqkeep::envelope::hex_encode(s.key_id()).into() }) } diff --git a/src/cli/signing.rs b/src/cli/signing.rs index 29ebc57..275db4e 100644 --- a/src/cli/signing.rs +++ b/src/cli/signing.rs @@ -242,7 +242,7 @@ pub fn load_expected(lang: Lang, m: &ArgMatches) -> CliResult) { if let Some(s) = signer { - let hex = envelope::hex_encode(&s.key_id); + let hex = envelope::hex_encode(s.key_id()); println!("{}: {}", texts(lang).signed_by, fingerprint(&hex)); // DE: Für das Fertig-Fenster des Kontextmenüs eine eigene Steuerzeile – nie aus Text // erraten (#287). EN: A dedicated control line for the context menu's final window – diff --git a/src/files/confidential_path_index.rs b/src/files/confidential_path_index.rs new file mode 100644 index 0000000..96084c8 --- /dev/null +++ b/src/files/confidential_path_index.rs @@ -0,0 +1,248 @@ +//! DE: Balancierter Pfadindex mit vor Befüllung gesperrten Knoten. +//! EN: Balanced path index with nodes locked before population. + +use super::{ConfidentialText, paths::MAX_ENTRIES}; +use crate::crypto::secret_workspace::SecretWorkspace; +use crate::crypto::{secret_buffer::SecretBuffer, secret_state::SecretState}; +use crate::{Error, Result}; +use std::cmp::Ordering; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct Node { + key: Option, + left: Option, + right: Option, + height: u8, + file: bool, +} + +impl Zeroize for Node { + fn zeroize(&mut self) { + self.key.take(); + self.left.zeroize(); + self.right.zeroize(); + self.height.zeroize(); + self.file.zeroize(); + } +} + +impl ZeroizeOnDrop for SecretBuffer {} + +struct State { + nodes: SecretWorkspace, + root: Option, + used: usize, +} + +impl Drop for State { + fn drop(&mut self) { + self.nodes.zeroize(); + self.root.zeroize(); + self.used.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +/// DE: Auch Baumwurzel und Belegung bleiben im gesperrten Zustand. +/// EN: Tree root and occupancy also remain in protected state. +#[derive(Default)] +pub(super) struct Index(Option>); + +impl Index { + pub(super) fn get(&self, key: &[u8]) -> Option { + let state = self.0.as_ref()?.get(); + let mut next = state.root; + while let Some(index) = next { + let node = &state.nodes.expose()[index]; + match key.cmp(node.key.as_ref()?.bytes()) { + Ordering::Equal => return Some(node.file), + Ordering::Less => next = node.left, + Ordering::Greater => next = node.right, + } + } + None + } + + pub(super) fn has_prefix(&self, prefix: &[u8]) -> bool { + self.lower_bound(prefix) + .is_some_and(|key| key.starts_with(prefix)) + } + + fn lower_bound(&self, key: &[u8]) -> Option<&[u8]> { + let state = self.0.as_ref()?.get(); + let (mut next, mut candidate) = (state.root, None); + while let Some(index) = next { + let node = &state.nodes.expose()[index]; + let text = node.key.as_ref()?.bytes(); + if text < key { + next = node.right; + } else { + candidate = Some(text); + next = node.left; + } + } + candidate + } + + pub(super) fn insert(&mut self, key: ConfidentialText, file: bool) -> Result<()> { + if self.get(key.bytes()).is_some() { + return Err(Error::InvalidInput { field: "path" }); + } + if self.0.is_none() { + self.0 = Some(SecretState::new(State { + nodes: SecretWorkspace::zeroed(16)?, + root: None, + used: 0, + })?); + } + let state = self.0.as_mut().ok_or(Error::MemoryLock)?.get_mut(); + state.reserve()?; + let index = state.used; + let slot = &mut state.nodes.expose_mut()[index]; + slot.key = Some(key); + slot.file = file; + slot.height = 1; + state.used += 1; + state.root = Some(state.insert_at(state.root, index)); + Ok(()) + } +} + +impl State { + fn reserve(&mut self) -> Result<()> { + if self.used < self.nodes.expose().len() { + return Ok(()); + } + let limit = usize::try_from(MAX_ENTRIES).map_err(|_| Error::MemoryLock)?; + let capacity = self.used.saturating_mul(2).min(limit); + if capacity <= self.used { + return Err(Error::InvalidInput { field: "entries" }); + } + let mut next = SecretWorkspace::::zeroed(capacity)?; + // DE: Fallible Kopien nur zwischen gesperrten Zielen; alter Baum bleibt bei Fehler gültig. + // EN: Fallible copies only into locked storage; errors leave the old tree intact. + for (old, new) in self.nodes.expose().iter().zip(next.expose_mut()) { + new.key = old + .key + .as_ref() + .map(ConfidentialText::try_duplicate) + .transpose()?; + new.left = old.left; + new.right = old.right; + new.height = old.height; + new.file = old.file; + } + self.nodes = next; + Ok(()) + } + + fn height(&self, index: Option) -> u8 { + index.map_or(0, |i| self.nodes.expose()[i].height) + } + + fn refresh(&mut self, index: usize) { + let node = &self.nodes.expose()[index]; + let height = self.height(node.left).max(self.height(node.right)) + 1; + self.nodes.expose_mut()[index].height = height; + } + + fn rotate_left(&mut self, root: usize, right: usize) -> usize { + self.nodes.expose_mut()[root].right = self.nodes.expose()[right].left; + self.nodes.expose_mut()[right].left = Some(root); + self.refresh(root); + self.refresh(right); + right + } + + fn rotate_right(&mut self, root: usize, left: usize) -> usize { + self.nodes.expose_mut()[root].left = self.nodes.expose()[left].right; + self.nodes.expose_mut()[left].right = Some(root); + self.refresh(root); + self.refresh(left); + left + } + + fn balance(&mut self, root: usize) -> usize { + self.refresh(root); + let node = &self.nodes.expose()[root]; + let (left, right) = (node.left, node.right); + if self.height(left) > self.height(right) + 1 { + if let Some(mut left) = left { + let node = &self.nodes.expose()[left]; + if self.height(node.right) > self.height(node.left) + && let Some(right) = node.right + { + left = self.rotate_left(left, right); + self.nodes.expose_mut()[root].left = Some(left); + } + return self.rotate_right(root, left); + } + } else if self.height(right) > self.height(left) + 1 + && let Some(mut right) = right + { + let node = &self.nodes.expose()[right]; + if self.height(node.left) > self.height(node.right) + && let Some(left) = node.left + { + right = self.rotate_right(right, left); + self.nodes.expose_mut()[root].right = Some(right); + } + return self.rotate_left(root, right); + } + root + } + + fn insert_at(&mut self, root: Option, added: usize) -> usize { + let Some(root) = root else { return added }; + let nodes = self.nodes.expose(); + // DE: Nur bereits befüllte Indizes erreichbar; keine privaten Knoten als Wert bewegen. + // EN: Only populated indices are reachable; never move a private node by value. + if nodes[added].key < nodes[root].key { + let child = self.insert_at(nodes[root].left, added); + self.nodes.expose_mut()[root].left = Some(child); + } else { + let child = self.insert_at(nodes[root].right, added); + self.nodes.expose_mut()[root].right = Some(child); + } + self.balance(root) + } +} + +#[cfg(test)] +#[path = "confidential_path_index_tests.rs"] +mod tests; + +#[cfg(all(test, target_os = "linux"))] +#[path = "confidential_path_index_denial_tests.rs"] +mod denial_tests; + +#[cfg(test)] +impl Index { + pub(super) fn iter(&self) -> impl Iterator { + self.0.iter().flat_map(|state| { + state + .get() + .nodes + .expose() + .iter() + .filter_map(|node| node.key.as_ref()) + }) + } + + pub(super) fn len(&self) -> usize { + self.0.as_ref().map_or(0, |state| state.get().used) + } + + pub(super) fn file_count(&self) -> usize { + self.0.as_ref().map_or(0, |state| { + state + .get() + .nodes + .expose() + .iter() + .filter(|node| node.file) + .count() + }) + } +} diff --git a/src/files/confidential_path_index_denial_tests.rs b/src/files/confidential_path_index_denial_tests.rs new file mode 100644 index 0000000..d2bf79a --- /dev/null +++ b/src/files/confidential_path_index_denial_tests.rs @@ -0,0 +1,119 @@ +//! DE: Tatsächliche Ressourcenverweigerung und Unwind im begrenzten eigenen Kind. +//! EN: Actual resource denial and unwind in a bounded owned child. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::hardening::memlock; +use rustix::process::{Resource, getrlimit, setrlimit}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +#[test] +fn growth_denial_preserves_index_and_unwind_releases_actual_locks() { + let before = getrlimit(Resource::Memlock); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "files::confidential_path_index::denial_tests::index_denial_child", + "--ignored", + "--test-threads=1", + ]) + .env("PQKEEP_PATH_INDEX_DENIAL_CHILD", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(status) = child.try_wait().unwrap() { + let output = child.wait_with_output().unwrap(); + assert!( + status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); + break; + } + let timed_out = Instant::now() >= deadline; + if timed_out { + child.kill().unwrap(); + child.wait().unwrap(); + } + assert!(!timed_out); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[test] +#[ignore = "DE/EN: Eigenes begrenztes Kind / bounded owned child only"] +fn index_denial_child() { + assert_eq!( + std::env::var("PQKEEP_PATH_INDEX_DENIAL_CHILD").unwrap(), + "1" + ); + let baseline = memlock::stats().locked_pages; + let result = std::panic::catch_unwind(|| { + let mut index = Index::default(); + for n in 0..32 { + index + .insert( + ConfidentialText::from_text(&format!("unwind-{n}")).unwrap(), + true, + ) + .unwrap(); + } + super::tests::assert_storage_locked(&index); + std::panic::resume_unwind(Box::new(())); + }); + assert!(result.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + actual_growth_denial(baseline); +} + +fn actual_growth_denial(baseline: usize) { + let mut index = Index::default(); + for n in 0..16 { + index + .insert( + ConfidentialText::from_text(&format!("retained-{n:04}")).unwrap(), + true, + ) + .unwrap(); + } + // DE: Quellen vor der Limitabsenkung sperren, damit die tatsächliche Indexoperation geprüft wird. + // EN: Prelock sources before lowering the limit to test the actual index operation. + let prepared: Vec<_> = (0..512) + .map(|n| ConfidentialText::from_text(&format!("additional-{n:04}")).unwrap()) + .collect(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + let failures_before = memlock::stats().failed_attempts; + let mut refused = false; + for key in prepared { + let before = index.len(); + match index.insert(key, true) { + Ok(()) => assert_eq!(index.len(), before + 1), + Err(error) => { + assert!(matches!(error, Error::MemoryLock)); + assert_eq!(index.len(), before); + refused = true; + break; + } + } + } + assert!( + refused, + "DE/EN: Tatsächliche Sperrverweigerung erforderlich / actual lock denial required" + ); + assert!(memlock::stats().failed_attempts > failures_before); + for n in 0..16 { + assert_eq!(index.get(format!("retained-{n:04}").as_bytes()), Some(true)); + } + super::tests::assert_storage_locked(&index); + drop(index); + assert_eq!(memlock::stats().locked_pages, baseline); +} diff --git a/src/files/confidential_path_index_tests.rs b/src/files/confidential_path_index_tests.rs new file mode 100644 index 0000000..3c5e2bd --- /dev/null +++ b/src/files/confidential_path_index_tests.rs @@ -0,0 +1,114 @@ +//! DE: Gegenproben und tatsächliche Knoten-/Owner-Sperren des vertraulichen Index. +//! EN: Reference comparisons and actual confidential index node/owner locks. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::hardening::memlock; +use std::collections::BTreeMap; + +fn check_balance(state: &State, root: Option) -> u8 { + let Some(root) = root else { return 0 }; + let node = &state.nodes.expose()[root]; + let left = check_balance(state, node.left); + let right = check_balance(state, node.right); + assert!(left.abs_diff(right) <= 1); + assert_eq!(node.height, left.max(right) + 1); + if let Some(left) = node.left { + assert!(state.nodes.expose()[left].key < node.key); + } + if let Some(right) = node.right { + assert!(state.nodes.expose()[right].key > node.key); + } + node.height +} + +pub(super) fn assert_storage_locked(index: &Index) { + let state = index.0.as_ref().unwrap().get(); + let start = std::ptr::from_ref(state).addr(); + assert!(memlock::is_locked(start)); + assert!(memlock::is_locked(start + size_of::() - 1)); + let nodes = state.nodes.expose(); + let start = nodes.as_ptr().addr(); + assert!(memlock::is_locked(start)); + assert!(memlock::is_locked(start + size_of_val(nodes) - 1)); + for node in nodes.iter().take(state.used) { + let key = node.key.as_ref().unwrap(); + key.assert_owner_locked(); + assert!(memlock::is_locked(key.bytes().as_ptr().addr())); + } +} + +#[test] +fn ascending_descending_and_permuted_growth_match_ordered_reference() { + for order in 0..3 { + let mut index = Index::default(); + let mut reference = BTreeMap::new(); + for i in 0..257 { + let n = match order { + 0 => i, + 1 => 256 - i, + _ => (i * 97) % 257, + }; + let name = format!("name-{n:04}"); + let file = n % 3 == 0; + index + .insert(ConfidentialText::from_text(&name).unwrap(), file) + .unwrap(); + reference.insert(name, file); + let state = index.0.as_ref().unwrap().get(); + assert_eq!(state.used, reference.len()); + assert!(check_balance(state, state.root) <= 10); + for (key, file) in &reference { + assert_eq!(index.get(key.as_bytes()), Some(*file)); + } + } + for n in 0..300 { + let query = format!("name-{n:04}a"); + let expected = reference + .range(query.clone()..) + .next() + .map(|(key, _)| key.as_bytes()); + assert_eq!(index.lower_bound(query.as_bytes()), expected); + } + assert_storage_locked(&index); + } +} + +#[test] +fn duplicate_and_prefix_queries_preserve_tree_and_confidential_ownership() { + let mut index = Index::default(); + index + .insert(ConfidentialText::from_text("a/b").unwrap(), true) + .unwrap(); + index + .insert(ConfidentialText::from_text("a-").unwrap(), false) + .unwrap(); + assert!(index.has_prefix(b"a/")); + assert!(!index.has_prefix(b"ab/")); + assert!( + index + .insert(ConfidentialText::from_text("a/b").unwrap(), false) + .is_err() + ); + assert_eq!(index.len(), 2); + assert_eq!(index.get(b"a/b"), Some(true)); + assert_storage_locked(&index); +} + +#[test] +fn concrete_node_fields_wipe_while_record_allocation_remains_locked() { + let mut index = Index::default(); + index + .insert(ConfidentialText::from_text("private-name").unwrap(), true) + .unwrap(); + let state = index.0.as_mut().unwrap().get_mut(); + let node = &mut state.nodes.expose_mut()[0]; + let address = std::ptr::from_ref(node).addr(); + assert!(memlock::is_locked(address)); + node.zeroize(); + assert!(node.key.is_none()); + assert!(node.left.is_none() && node.right.is_none()); + assert_eq!(node.height, 0); + assert!(!node.file); + assert!(memlock::is_locked(address)); +} diff --git a/src/files/decrypt_v2.rs b/src/files/decrypt_v2.rs index 1b2802c..c07e62e 100644 --- a/src/files/decrypt_v2.rs +++ b/src/files/decrypt_v2.rs @@ -173,7 +173,7 @@ pub(super) fn open_header( Some((SignatureCheck::new(bytes, s.clone()), Some(body_len))) } None if hidden => { - let (check, result) = SignatureCheck::hidden(signer); + let (check, result) = SignatureCheck::hidden(signer)?; if let Some(t) = tail.as_mut() { t.hidden = Some((header.encode()?, result)); } diff --git a/src/files/hidden_result.rs b/src/files/hidden_result.rs new file mode 100644 index 0000000..d6b95e6 --- /dev/null +++ b/src/files/hidden_result.rs @@ -0,0 +1,39 @@ +//! DE: Geteilten Trailer-Ergebniszustand vor Identitätseintritt sperren. +//! EN: Lock shared trailer result state before identity ingress. + +use super::SignedBy; +use crate::{Result, crypto::secret_state::SecretState}; +use std::{cell::RefCell, rc::Rc}; +use zeroize::ZeroizeOnDrop; + +struct State(RefCell>); + +impl Drop for State { + fn drop(&mut self) { + self.0.get_mut().take(); + } +} +impl ZeroizeOnDrop for State {} + +// DE: Rc enthält nur gemeinsame Ownership; der befüllte Slot bleibt stabil gesperrt. +// EN: Rc holds shared ownership only; the populated slot stays stably locked. +#[derive(Clone)] +pub(super) struct HiddenResult(Rc>); + +impl HiddenResult { + pub(super) fn new() -> Result { + Ok(Self(Rc::new(SecretState::new(State(RefCell::new(None)))?))) + } + + pub(super) fn store(&self, signer: SignedBy) { + *self.0.get().0.borrow_mut() = Some(signer); + } + + pub(super) fn take(&self) -> Option { + self.0.get().0.borrow_mut().take() + } +} + +#[cfg(test)] +#[path = "hidden_result_tests.rs"] +mod tests; diff --git a/src/files/hidden_result_tests.rs b/src/files/hidden_result_tests.rs new file mode 100644 index 0000000..b6eefa8 --- /dev/null +++ b/src/files/hidden_result_tests.rs @@ -0,0 +1,27 @@ +//! DE: Geteilter gesperrter Slot, einmalige Entnahme und Ersetzung. +//! EN: Shared locked slot, one-time take and replacement. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::files::locked_owner_tests::locked; + +#[test] +fn shared_slot_stays_locked_before_and_after_identity_population() { + let result = HiddenResult::new().unwrap(); + let other = result.clone(); + let address = std::ptr::from_ref(result.0.get()); + locked(result.0.get()); + assert!(result.take().is_none()); + result.store(SignedBy::from_public_key(b"public first identity").unwrap()); + locked(other.0.get()); + assert_eq!(std::ptr::from_ref(other.0.get()), address); + other.store(SignedBy::from_public_key(b"public replacement identity").unwrap()); + drop(result); + let signed = other.take().unwrap(); + assert_eq!( + signed, + SignedBy::from_public_key(b"public replacement identity").unwrap() + ); + assert!(other.take().is_none()); + locked(other.0.get()); +} diff --git a/src/files/mod.rs b/src/files/mod.rs index 8ced1a8..7979226 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -16,6 +16,7 @@ mod anon_v4; mod archive; mod check; mod confidential_entries; +mod confidential_path_index; mod confidential_text; mod decrypt; mod decrypt_v2; @@ -25,6 +26,7 @@ mod encrypt_v2; pub mod format; pub mod format_v2; pub mod format_v4; +mod hidden_result; mod list; #[cfg(test)] mod locked_owner_tests; @@ -32,7 +34,11 @@ mod original; mod output; pub mod paths; pub mod random_name; +#[cfg(test)] +#[path = "recovery_v4_tests.rs"] +mod recovery_v4_tests; mod scan; +mod signed_by; mod signed_io; mod signer_v3; mod slot_v2; @@ -58,7 +64,7 @@ pub use format_v2::{HeaderV2, Slot}; pub use list::{EntryKind, ListEntry, Listing, MAX_LIST_ENTRIES, MAX_LIST_PATH_BYTES, list}; pub use original::{ChooseTarget, decrypt_original}; pub use random_name::{is_random_name, random_name, random_target}; -pub use signed_io::SignedBy; +pub use signed_by::SignedBy; pub use signer_v3::Signer; pub use slot_v2::MAX_RECIPIENTS; pub use stream_v4::{encrypt_stream, encrypt_stream_to}; @@ -145,7 +151,7 @@ pub enum Unlock<'a> { } /// DE: Bericht über einen Vorgang. EN: Report of an operation. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Default, PartialEq, Eq)] pub struct Report { /// DE: Anzahl Dateien. EN: Number of files. pub files: u64, diff --git a/src/files/path_components_tests.rs b/src/files/path_components_tests.rs index 5436cdb..28cc455 100644 --- a/src/files/path_components_tests.rs +++ b/src/files/path_components_tests.rs @@ -81,7 +81,7 @@ fn borrowed_and_public_path_sets_preserve_unicode_and_prefix_conflicts() { ("childless", true, true), ("CHILDLESS/x", true, false), ] { - let before = (private.entries.len(), private.files.len()); + let before = (private.entries.len(), private.entries.file_count()); assert_eq!( public.insert(&validate(path).unwrap(), file).is_ok(), expected @@ -93,11 +93,14 @@ fn borrowed_and_public_path_sets_preserve_unicode_and_prefix_conflicts() { expected ); if !expected { - assert_eq!((private.entries.len(), private.files.len()), before); + assert_eq!( + (private.entries.len(), private.entries.file_count()), + before + ); } assert_eq!(public.entries.len(), private.entries.len()); - assert_eq!(public.files.len(), private.files.len()); - for (left, right) in public.entries.iter().zip(&private.entries) { + assert_eq!(public.entries.file_count(), private.entries.file_count()); + for (left, right) in public.entries.iter().zip(private.entries.iter()) { assert!(left.bytes().eq(right.bytes())); left.assert_owner_locked(); right.assert_owner_locked(); @@ -111,7 +114,7 @@ fn public_slice_rejections_and_existing_part_semantics_remain_unchanged() { assert!(set.insert(&[], true).is_err()); assert!(set.insert(&["good", ".."], true).is_err()); assert!(set.insert(&vec!["d"; MAX_DEPTH + 1], true).is_err()); - assert!(set.entries.is_empty() && set.files.is_empty()); + assert!(set.entries.len() == 0 && set.entries.file_count() == 0); // DE: Kein neuer Teile-Slice-Vertrag; interne Rohpfade werden vollständig getrennt geprüft. // EN: No new part-slice contract; internal raw paths are fully split and validated. set.insert(&["one/two"], true).unwrap(); diff --git a/src/files/paths.rs b/src/files/paths.rs index 633e1b2..30c0586 100644 --- a/src/files/paths.rs +++ b/src/files/paths.rs @@ -14,8 +14,6 @@ use super::ConfidentialText; use crate::crypto::SecretBytes; -use std::collections::BTreeSet; -use std::ops::Bound; use crate::{Error, Result}; @@ -111,8 +109,7 @@ pub(super) fn validate_only(path: &str) -> Result<()> { /// file/directory conflicts ("a" as a file and "a/b"). #[derive(Default)] pub struct PathSet { - entries: BTreeSet, - files: BTreeSet, + entries: super::confidential_path_index::Index, } fn lower_chars(part: &str) -> impl Iterator + '_ { @@ -176,35 +173,21 @@ impl PathSet { ) -> Result<()> { let key = folded_key(parts)?; for (index, byte) in key.bytes().iter().enumerate() { - if *byte == b'/' && self.files.contains(&key.bytes()[..index]) { + if *byte == b'/' && self.entries.get(&key.bytes()[..index]) == Some(true) { return Err(invalid()); } } - if self.entries.contains(key.bytes()) { + if self.entries.get(key.bytes()).is_some() { return Err(invalid()); } if is_file { let mut prefix = SecretBytes::zeroed(key.bytes().len() + 1)?; prefix.expose_mut()[..key.bytes().len()].copy_from_slice(key.bytes()); prefix.expose_mut()[key.bytes().len()] = b'/'; - if self - .entries - .range::<[u8], _>((Bound::Included(prefix.expose()), Bound::Unbounded)) - .next() - .is_some_and(|p| p.bytes().starts_with(prefix.expose())) - { + if self.entries.has_prefix(prefix.expose()) { return Err(invalid()); } } - let file_key = if is_file { - Some(key.try_duplicate()?) - } else { - None - }; - self.entries.insert(key); - if let Some(key) = file_key { - self.files.insert(key); - } - Ok(()) + self.entries.insert(key, is_file) } } diff --git a/src/files/paths_tests.rs b/src/files/paths_tests.rs index b3dfa83..7cb6f4a 100644 --- a/src/files/paths_tests.rs +++ b/src/files/paths_tests.rs @@ -137,17 +137,17 @@ fn later_directory_parent_and_non_descendant_prefixes_remain_valid() { fn normalized_keys_are_locked_and_conflicts_do_not_mutate_state() { let mut set = PathSet::default(); set.insert(&["Ä", "İΣ"], true).unwrap(); - for key in set.entries.iter().chain(&set.files) { + for key in set.entries.iter() { key.assert_owner_locked(); assert!(crate::hardening::memlock::is_locked( key.bytes().as_ptr().addr() )); assert_eq!(format!("{key:?}"), "[REDACTED]"); } - let before = (set.entries.len(), set.files.len()); + let before = (set.entries.len(), set.entries.file_count()); assert!(set.insert(&["ä", "i\u{307}ς"], false).is_err()); assert!(set.insert(&["Ä"], true).is_err()); - assert_eq!((set.entries.len(), set.files.len()), before); + assert_eq!((set.entries.len(), set.entries.file_count()), before); set.insert(&["ä", "other"], true).unwrap(); } @@ -188,13 +188,13 @@ fn private_name_owners_stay_locked_through_tree_growth() { let name = format!("entry-{index:04}"); set.insert(&[&name], true).unwrap(); } - for key in set.entries.iter().chain(&set.files) { + for key in set.entries.iter() { key.assert_owner_locked(); } } assert_eq!(set.entries.len(), 128); - assert_eq!(set.files.len(), 128); + assert_eq!(set.entries.file_count(), 128); assert!(set.insert(&["ENTRY-0000"], true).is_err()); assert_eq!(set.entries.len(), 128); - assert_eq!(set.files.len(), 128); + assert_eq!(set.entries.file_count(), 128); } diff --git a/src/files/recovery_v4_tests.rs b/src/files/recovery_v4_tests.rs new file mode 100644 index 0000000..ecab258 --- /dev/null +++ b/src/files/recovery_v4_tests.rs @@ -0,0 +1,156 @@ +//! DE: REC-008 für Format v4 (#335, Lücke G5): Fehler beim Öffnen, Schreiben (auch teilweise), +//! Synchronisieren und Veröffentlichen während `decrypt` von Strom (mit Füllung bzw. verborgenem +//! Absender) und Archiv (Datei mit Füllung und verborgenem Absender, Ordner mit Füllung) – das Ziel +//! erscheint nie, die Quelle bleibt unverändert, keine Temporärreste. +//! EN: REC-008 for format v4 (#335, gap G5): failures while opening, writing (also partially), +//! syncing and publishing during `decrypt` of streams (with padding or hidden sender) and archives +//! (file with padding and hidden sender, directory with padding) – the target never appears, the +//! source stays unchanged, no temporary leftovers. +#![allow(clippy::unwrap_used)] + +use std::io::ErrorKind; +use std::path::Path; + +use crate::crypto::{DsaAlgorithm, KeyAlgorithm, kdf}; +use crate::envelope::{KeyFile, Metadata, UnlockedKey}; +use crate::fault_fixture_tests::{assert_no_temps, plan}; +use crate::fault_io_tests::{Action, Failure, Point, Scope}; +use crate::files::{self, EncryptOptions, Protection, Unlock}; +use crate::security::{StrongPassphrase, generator}; +use crate::{Error, Result}; + +fn params() -> kdf::KdfParams { + kdf::KdfParams { + memory_kib: kdf::MIN_MEMORY_KIB, + iterations: kdf::MIN_ITERATIONS, + parallelism: 1, + } +} + +fn signer(pass: &StrongPassphrase) -> UnlockedKey { + let meta = Metadata { + name: "synthetic".to_owned(), + organization: None, + company: None, + department: None, + account_type: None, + }; + let algorithm = KeyAlgorithm::Dsa(DsaAlgorithm::MlDsa87); + let file = KeyFile::generate(pass, algorithm, &meta, ¶ms()).unwrap(); + file.unlock(pass.as_ref()).unwrap() +} + +/// DE: Ein Fall: Quelle, Verschlüsselungsweg und Optionen. EN: One case: source, way and options. +struct Case { + stream: bool, + tree: bool, + options: EncryptOptions, + signed: bool, +} + +const CASES: [Case; 4] = [ + Case { + stream: true, + tree: false, + options: opts(true, false), + signed: false, + }, + Case { + stream: true, + tree: false, + options: opts(false, true), + signed: true, + }, + Case { + stream: false, + tree: false, + options: opts(true, true), + signed: true, + }, + Case { + stream: false, + tree: true, + options: opts(true, false), + signed: false, + }, +]; + +const fn opts(pad: bool, hide_sender: bool) -> EncryptOptions { + EncryptOptions { + pad, + anonymous: false, + hide_sender, + } +} + +fn encrypt(case: &Case, root: &Path, pass: &StrongPassphrase, key: &UnlockedKey) -> Result<()> { + let source = root.join("source"); + let payload = vec![0x5a; 65_537]; + if case.tree { + std::fs::create_dir_all(source.join("nested")).unwrap(); + std::fs::write(source.join("a"), &payload).unwrap(); + std::fs::write(source.join("nested/b"), b"synthetic").unwrap(); + } else { + std::fs::write(&source, &payload).unwrap(); + } + let p = Protection::Passphrase { + passphrase: pass, + params: params(), + }; + let signer = case.signed.then_some(key); + let archive = root.join("archive.pqkf"); + if case.stream { + files::encrypt_stream_to(&mut &payload[..], &archive, &p, signer, case.options)?; + } else { + files::encrypt_with_options(&source, &archive, &p, signer, case.options)?; + } + Ok(()) +} + +#[test] +fn rec008_v4_decrypt_failures_never_publish() { + let pass = generator::generate(&generator::Options::default()).unwrap(); + let key = signer(&pass); + let fail = Failure::Kind(ErrorKind::StorageFull); + for case in &CASES { + let root = tempfile::tempdir().unwrap(); + encrypt(case, root.path(), &pass, &key).unwrap(); + let archive = root.path().join("archive.pqkf"); + let before = std::fs::read(&archive).unwrap(); + let unlock = Unlock::Passphrase(pass.as_ref()); + let mut faults: Vec<_> = [ + Point::BeforeOpen, + Point::AfterTempCreate, + Point::BeforeFileSync, + Point::BeforePublish, + ] + .map(|p| plan(p, Action::Fail(fail))) + .into(); + faults.extend([0, 1, 65_536].map(|after| { + plan( + Point::Write, + Action::Partial { + after, + failure: fail, + }, + ) + })); + for fault in faults { + let target = root.path().join("out"); + let scope = Scope::new(root.path(), fault); + let result = files::decrypt(&archive, &target, &unlock); + let trace = scope.finish(); + assert_eq!(result, Err(Error::Io(ErrorKind::StorageFull))); + assert!(!trace.contains(&Point::AfterPublish)); + assert!(!target.exists()); + assert!( + std::fs::read(&archive).unwrap() == before, + "Archiv verändert / changed" + ); + assert_no_temps(root.path()); + } + let valid = root.path().join("valid"); + files::decrypt(&archive, &valid, &unlock).unwrap(); + assert!(valid.exists()); + } +} diff --git a/src/files/signed_by.rs b/src/files/signed_by.rs new file mode 100644 index 0000000..9f18d95 --- /dev/null +++ b/src/files/signed_by.rs @@ -0,0 +1,67 @@ +//! DE: Geprüfte Identität ohne ungesperrte Hash-/Descriptor-Kopie. +//! EN: Verified identity without an unlocked hash or descriptor copy. + +use crate::Result; +use crate::crypto::{SecretBytes, locked_hash::LockedHash, secret_state::SecretState}; +use sha3::Sha3_256; +use std::fmt; + +/// DE: Geprüfter Absender; Identität nur ausdrücklich ausleihen. +/// EN: Verified sender; borrow identity only by explicit disclosure. +pub struct SignedBy(SecretState); + +impl SignedBy { + pub(super) fn from_public_key(key: &[u8]) -> Result { + let mut out = Self::prepare()?; + let mut hash = LockedHash::::new()?; + hash.update(key); + *out.0.get_mut() = hash.finalize()?; + Ok(out) + } + + pub(super) fn from_key_id(id: &[u8]) -> Result { + let mut out = Self::prepare()?; + *out.0.get_mut() = SecretBytes::from_slice(id)?; + Ok(out) + } + + fn prepare() -> Result { + Ok(Self(SecretState::new(SecretBytes::zeroed(0)?)?)) + } + + /// DE: SHA3-256 des Absenderschlüssels; nur für angeforderte Ausgabe. + /// EN: Sender key SHA3-256; only for requested disclosure. + #[must_use] + pub fn key_id(&self) -> &[u8] { + self.0.get().expose() + } + + /// DE: Ziel vor der expliziten Kopie sperren; kein Clone-Fallback. + /// EN: Lock before explicit duplication; no Clone fallback. + /// # Errors + /// DE/EN: [`crate::Error::MemoryLock`]. + pub fn try_duplicate(&self) -> Result { + Self::from_key_id(self.key_id()) + } +} + +impl PartialEq for SignedBy { + fn eq(&self, other: &Self) -> bool { + self.key_id() == other.key_id() + } +} +impl Eq for SignedBy {} + +impl fmt::Debug for SignedBy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SignedBy([REDACTED])") + } +} + +#[cfg(test)] +#[path = "signed_by_tests.rs"] +mod tests; + +#[cfg(all(test, target_os = "linux"))] +#[path = "signed_by_denial_tests.rs"] +mod denial_tests; diff --git a/src/files/signed_by_denial_tests.rs b/src/files/signed_by_denial_tests.rs new file mode 100644 index 0000000..892fee3 --- /dev/null +++ b/src/files/signed_by_denial_tests.rs @@ -0,0 +1,107 @@ +//! DE: Echte Sperrverweigerung und Unwind ohne Änderung des Elternlimits. +//! EN: Actual lock denial and unwind without changing the parent limit. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::{Error, files::hidden_result::HiddenResult, hardening::memlock}; +use rustix::process::{Resource, getrlimit, setrlimit}; +use std::{ + process::{Command, Stdio}, + time::{Duration, Instant}, +}; + +#[test] +fn identity_denial_and_unwind_are_checked_in_an_owned_child() { + let before = getrlimit(Resource::Memlock); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "files::signed_by::denial_tests::identity_denial_child", + "--ignored", + "--test-threads=1", + ]) + .env("PQKEEP_IDENTITY_DENIAL_CHILD", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(status) = child.try_wait().unwrap() { + let output = child.wait_with_output().unwrap(); + assert!( + status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); + break; + } + let timed_out = Instant::now() >= deadline; + if timed_out { + child.kill().unwrap(); + child.wait().unwrap(); + } + assert!(!timed_out); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn identity_denial_child() { + assert_eq!(std::env::var("PQKEEP_IDENTITY_DENIAL_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let unwind = std::panic::catch_unwind(|| { + let shared = HiddenResult::new().unwrap(); + shared.store(SignedBy::from_public_key(b"public unwind fixture").unwrap()); + let other = shared.clone(); + let signed = other.take().unwrap(); + let _duplicate = signed.try_duplicate().unwrap(); + shared.store(signed); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + actual_denial(); + assert_eq!(memlock::stats().locked_pages, baseline); +} + +fn actual_denial() { + let signed = SignedBy::from_public_key(b"public retained fixture").unwrap(); + let expected = signed.try_duplicate().unwrap(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + // DE: Bereits gesperrte gemeinsame Seiten können weitere kleine Owner aufnehmen. + // EN: Already locked shared pages may accommodate additional small owners. + assert_eventual_denial(|| signed.try_duplicate()); + assert_eq!(signed, expected); + crate::files::locked_owner_tests::locked(signed.0.get()); + signed.0.get().assert_metadata_locked(); + assert_eventual_denial(HiddenResult::new); + assert_eventual_denial(|| SignedBy::from_public_key(b"public hash fixture")); +} + +fn assert_eventual_denial(mut create: impl FnMut() -> Result) { + let failures = memlock::stats().failed_attempts; + let mut retained = Vec::new(); + let mut denied = false; + for _ in 0..1024 { + match create() { + Ok(value) => retained.push(value), + Err(error) => { + assert!(matches!(error, Error::MemoryLock)); + denied = true; + break; + } + } + } + assert!( + denied, + "DE/EN: Tatsächliche Verweigerung erforderlich / actual denial required" + ); + assert!(memlock::stats().failed_attempts > failures); +} diff --git a/src/files/signed_by_tests.rs b/src/files/signed_by_tests.rs new file mode 100644 index 0000000..e39827d --- /dev/null +++ b/src/files/signed_by_tests.rs @@ -0,0 +1,39 @@ +//! DE: Tatsächliche Identitäts-Owner und unveränderte Hashbytes prüfen. +//! EN: Check actual identity owners and unchanged hash bytes. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::files::locked_owner_tests::locked; +use sha3::Digest; + +#[test] +fn identity_hash_matches_public_reference_and_all_owners_are_locked() { + let key = b"public synthetic sender identity"; + let signed = SignedBy::from_public_key(key).unwrap(); + let expected = Sha3_256::digest(key); + assert_eq!(signed.key_id(), expected.as_slice()); + locked(signed.0.get()); + signed.0.get().assert_metadata_locked(); + assert!(crate::hardening::memlock::is_locked( + signed.key_id().as_ptr().addr() + )); + assert!(crate::hardening::memlock::is_locked( + signed.key_id().as_ptr().addr() + 31 + )); + assert_eq!(format!("{signed:?}"), "SignedBy([REDACTED])"); +} + +#[test] +fn duplication_keeps_source_and_locks_an_independent_destination() { + let signed = SignedBy::from_public_key(b"public reference").unwrap(); + let duplicate = signed.try_duplicate().unwrap(); + assert_eq!(signed, duplicate); + assert_ne!(signed.key_id().as_ptr(), duplicate.key_id().as_ptr()); + locked(duplicate.0.get()); + duplicate.0.get().assert_metadata_locked(); + drop(signed); + assert_eq!( + duplicate.key_id(), + Sha3_256::digest(b"public reference").as_slice() + ); +} diff --git a/src/files/signed_io.rs b/src/files/signed_io.rs index 67a4444..6668f7d 100644 --- a/src/files/signed_io.rs +++ b/src/files/signed_io.rs @@ -17,17 +17,11 @@ use std::rc::Rc; use sha3::{Digest, Sha3_512}; use super::signer_v3::{FILE_SIG_CONTEXT, FILE_SIGNATURE_LEN, SIGNER_DSA, Signer, message}; +pub(super) use super::{SignedBy, hidden_result::HiddenResult}; use crate::crypto::{KeyAlgorithm, dsa}; use crate::envelope::{PublicKeyFile, UnlockedKey}; use crate::{Error, Result}; -/// DE: Geprüfter Absender einer Datei. EN: Verified sender of a file. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SignedBy { - /// DE: Schlüssel-ID (SHA3-256 des öffentlichen Schlüssels). EN: Key ID (SHA3-256 of the public key). - pub key_id: Vec, -} - /// DE: Prüft, dass `key` ein ML-DSA-87-Schlüssel ist (vor jeder Arbeit). /// EN: Checks that `key` is an ML-DSA-87 key (before any work). /// @@ -160,9 +154,6 @@ impl Read for Body { } } -/// DE: Ergebnis eines verborgenen Absenders (füllt der Trailer-Leser). EN: Result of a hidden sender. -pub(crate) type HiddenResult = Rc>>; - /// DE: Signaturprüfung: v3/v4-SIGNED (Σ am Dateiende) oder verborgener Absender (Trailer, #316). /// EN: Signature check: v3/v4-SIGNED (Σ at the end) or hidden sender (trailer, #316). pub(crate) struct SignatureCheck { @@ -171,7 +162,7 @@ pub(crate) struct SignatureCheck { signer: Option, /// DE: Verborgener Absender: Ergebnis und verlangte Schlüssel-ID (`--signer`). /// EN: Hidden sender: result and required key ID (`--signer`). - hidden: Option<(HiddenResult, Option>)>, + hidden: Option<(HiddenResult, Option)>, } impl SignatureCheck { @@ -186,18 +177,20 @@ impl SignatureCheck { /// DE: Prüfung für einen verborgenen Absender; der Trailer-Leser trägt das Ergebnis ein. /// EN: Check for a hidden sender; the trailer reader fills in the result. - pub(super) fn hidden(expected: Option<&PublicKeyFile>) -> (Self, HiddenResult) { - let result: HiddenResult = Rc::new(RefCell::new(None)); + pub(super) fn hidden(expected: Option<&PublicKeyFile>) -> Result<(Self, HiddenResult)> { + let result = HiddenResult::new()?; let check = Self { tail: Rc::new(RefCell::new(Tail::default())), header: Vec::new(), signer: None, hidden: Some(( - Rc::clone(&result), - expected.map(PublicKeyFile::key_id).map(<[u8]>::to_vec), + result.clone(), + expected + .map(|key| SignedBy::from_key_id(key.key_id())) + .transpose()?, )), }; - (check, result) + Ok((check, result)) } /// DE: Prüft nach vollständig gelesenem `C`. EN: Verifies after `C` has been read completely. @@ -207,8 +200,8 @@ impl SignatureCheck { /// missing, file too long or truncated), [`Error::InvalidSignature`]. pub(super) fn verify(self) -> Result { if let Some((result, expected)) = self.hidden { - let signed = result.borrow_mut().take().ok_or(Error::Decrypt)?; - if expected.is_some_and(|id| id != signed.key_id) { + let signed = result.take().ok_or(Error::Decrypt)?; + if expected.is_some_and(|id| id != signed) { return Err(Error::InvalidSignature); } return Ok(signed); @@ -222,9 +215,7 @@ impl SignatureCheck { if !dsa::verify(SIGNER_DSA, key, &msg, FILE_SIG_CONTEXT, &signature) { return Err(Error::InvalidSignature); } - Ok(SignedBy { - key_id: signer.key_id(), - }) + SignedBy::from_public_key(key) } } diff --git a/src/files/tail_v4.rs b/src/files/tail_v4.rs index c5a6347..779bbfc 100644 --- a/src/files/tail_v4.rs +++ b/src/files/tail_v4.rs @@ -15,7 +15,7 @@ use super::format_v4::{ HIDDEN_BLOCK_LEN, TRAILER_LEN, check_trailer, hidden_message, padding_for, trailer, trailer_len, }; use super::signed_io::{HiddenResult, SignedBy}; -use super::signer_v3::{FILE_SIG_CONTEXT, SIGNER_DSA, SIGNER_KEY_LEN, SIGNER_ML_DSA_87, Signer}; +use super::signer_v3::{FILE_SIG_CONTEXT, SIGNER_DSA, SIGNER_KEY_LEN, SIGNER_ML_DSA_87}; use crate::crypto::stream::PlainHash; use crate::crypto::stream::{CHUNK_SIZE, DecryptReader, EncryptWriter}; use crate::crypto::{SecretBytes, dsa}; @@ -145,7 +145,7 @@ fn check_tail(d: &Drained, before: u64, tail: &TailRead, hash: Option } if let Some((header, result)) = &tail.hidden { let hash = hash.ok_or(Error::Crypto)?.finalize()?; - *result.borrow_mut() = Some(hidden_sender(block, header, hash.expose(), payload, pad)?); + result.store(hidden_sender(block, header, hash.expose(), payload, pad)?); } Ok(payload) } @@ -169,13 +169,7 @@ fn hidden_sender( if !dsa::verify(SIGNER_DSA, key, msg.expose(), FILE_SIG_CONTEXT, sig) { return Err(Error::InvalidSignature); } - let signer = Signer { - public_key: key.to_vec(), - commit: [0; 32], - }; - Ok(SignedBy { - key_id: signer.key_id(), - }) + SignedBy::from_public_key(key) } /// DE: Strom: Nutzdaten (und Füllung) nach `out`, dann Prüfung. Liefert (Nutzlänge, geschrieben); diff --git a/src/files/tail_v4_tests.rs b/src/files/tail_v4_tests.rs index ea8207e..eeb9374 100644 --- a/src/files/tail_v4_tests.rs +++ b/src/files/tail_v4_tests.rs @@ -3,6 +3,7 @@ use super::*; use crate::crypto::stream::EncryptWriter; use crate::crypto::stream::PREFIX_LEN; +use crate::files::Signer; use crate::files::format_v4::TRAILER_MAGIC; use crate::files::format_v4::{padding_for, trailer}; @@ -167,13 +168,13 @@ fn hidden_check(plain: &[u8], header: &[u8]) -> (Result<(u64, u64)>, Option bool { self.core_dumps_disabled && self.not_dumpable @@ -47,9 +48,23 @@ pub fn harden_process() -> HardeningReport { platform::harden() } +/// DE: Liest aktuelle Prozessfähigkeiten ohne Änderung der Host-Policy. +/// Unbekannte/fehlgeschlagene Abfragen liefern keine bestätigte Fähigkeit. +/// Kein vollständiger Schutz gegen privilegierten Zugriff oder externe Dumps. +/// EN: Read current process capabilities without changing host policy. +/// Unknown/failed queries never confirm a capability. This is not complete +/// protection against privileged access or external dumps. +#[must_use] +pub fn observe_process() -> HardeningReport { + platform::observe() +} + #[cfg(target_os = "linux")] mod platform { - use rustix::process::{DumpableBehavior, Resource, Rlimit, set_dumpable_behavior, setrlimit}; + use rustix::process::{ + DumpableBehavior, Resource, Rlimit, dumpable_behavior, getrlimit, set_dumpable_behavior, + setrlimit, + }; use super::HardeningReport; @@ -59,9 +74,21 @@ mod platform { current: Some(0), maximum: Some(0), }; + let core_set = setrlimit(Resource::Core, zero).is_ok(); + let dumpable_set = set_dumpable_behavior(DumpableBehavior::NotDumpable).is_ok(); + let actual = observe(); + HardeningReport { + core_dumps_disabled: core_set && actual.core_dumps_disabled, + not_dumpable: dumpable_set && actual.not_dumpable, + wer_heap_reporting_disabled: false, + } + } + + pub(super) fn observe() -> HardeningReport { + let core = getrlimit(Resource::Core); HardeningReport { - core_dumps_disabled: setrlimit(Resource::Core, zero).is_ok(), - not_dumpable: set_dumpable_behavior(DumpableBehavior::NotDumpable).is_ok(), + core_dumps_disabled: core.current == Some(0) && core.maximum == Some(0), + not_dumpable: matches!(dumpable_behavior(), Ok(DumpableBehavior::NotDumpable)), wer_heap_reporting_disabled: false, } } @@ -97,6 +124,17 @@ mod platform { wer_heap_reporting_disabled: pqkeep_platform::suppress_wer_heap_reporting().is_ok(), } } + + pub(super) fn observe() -> HardeningReport { + HardeningReport { + core_dumps_disabled: false, + not_dumpable: false, + wer_heap_reporting_disabled: matches!( + pqkeep_platform::current_wer_flags(), + Ok(pqkeep_platform::WerFlags::Present(flags)) if flags & 1 != 0 + ), + } + } } #[cfg(not(any(target_os = "linux", windows)))] @@ -110,4 +148,8 @@ mod platform { wer_heap_reporting_disabled: false, } } + + pub(super) fn observe() -> HardeningReport { + harden() + } } diff --git a/tests/common/integrity.rs b/tests/common/integrity.rs new file mode 100644 index 0000000..188c971 --- /dev/null +++ b/tests/common/integrity.rs @@ -0,0 +1,179 @@ +//! DE: Hilfen für die Integritätstests (#335): je Format eine kleine Datei mit Empfänger-Schlüssel +//! (ohne Argon2id, damit viele Varianten schnell laufen), Header-Länge, Strom-Bereich und eine +//! Prüfung, dass ein Lesepfad scheitert, ohne etwas zu veröffentlichen. +//! EN: Helpers for the integrity tests (#335): per format a small file with a recipient key +//! (without Argon2id so many variants run fast), header length, stream range and a check that a +//! read path fails without publishing anything. + +use std::path::{Path, PathBuf}; + +use pqkeep::crypto::{DsaAlgorithm, KemAlgorithm, KeyAlgorithm}; +use pqkeep::envelope::{PublicKeyFile, UnlockedKey}; +use pqkeep::files::{self, EncryptOptions, Protection, Unlock}; + +/// DE: Länge eines vollen verschlüsselten Blocks. EN: Length of a full encrypted chunk. +pub const ENC_CHUNK: usize = 64 * 1024 + 16; +/// DE: Länge der sichtbaren Signatur (v3). EN: Length of the visible signature (v3). +pub const SIG_LEN: usize = 4627; + +/// DE: Format bzw. Option, die eine Datei bekommt. EN: Format or option a file gets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + V1, + V2, + V3, + V4Pad, + V4Hidden, + V4Anon, + V4Stream, + V4StreamHidden, +} + +pub const ALL: [Kind; 8] = [ + Kind::V1, + Kind::V2, + Kind::V3, + Kind::V4Pad, + Kind::V4Hidden, + Kind::V4Anon, + Kind::V4Stream, + Kind::V4StreamHidden, +]; + +/// DE: Schlüssel für alle Fälle. EN: Keys for all cases. +pub struct Keys { + pub kem: (PublicKeyFile, UnlockedKey), + pub other: PublicKeyFile, + pub kem1024: (PublicKeyFile, UnlockedKey), + pub signer: UnlockedKey, +} + +fn pair(algorithm: KeyAlgorithm) -> (PublicKeyFile, UnlockedKey) { + let (file, pass) = super::key_file(algorithm); + ( + file.public_part().unwrap(), + file.unlock(pass.as_ref()).unwrap(), + ) +} + +pub fn keys() -> Keys { + Keys { + kem: pair(KeyAlgorithm::Kem(KemAlgorithm::MlKem768)), + other: pair(KeyAlgorithm::Kem(KemAlgorithm::MlKem768)).0, + kem1024: pair(KeyAlgorithm::Kem(KemAlgorithm::MlKem1024)), + signer: pair(KeyAlgorithm::Dsa(DsaAlgorithm::MlDsa87)).1, + } +} + +impl Keys { + /// DE: Entsperren passend zum Fall. EN: Unlock matching the case. + pub fn unlock(&self, kind: Kind) -> Unlock<'_> { + match kind { + Kind::V4Anon => Unlock::Key(&self.kem1024.1), + _ => Unlock::Key(&self.kem.1), + } + } +} + +/// DE: Verschlüsselt `plain` als Datei bzw. Strom im Format `kind`. EN: Encrypts `plain`. +pub fn seal(dir: &Path, name: &str, kind: Kind, k: &Keys, plain: &[u8]) -> Vec { + let src = dir.join(format!("{name}.src")); + std::fs::write(&src, plain).unwrap(); + let enc = dir.join(format!("{name}.pqkf")); + let one = [&k.kem.0]; + let two = [&k.kem.0, &k.other]; + let anon = [&k.kem1024.0]; + let (recipients, signer, options): (&[&PublicKeyFile], _, _) = match kind { + Kind::V1 => (&one, None, EncryptOptions::default()), + Kind::V2 => (&two, None, EncryptOptions::default()), + Kind::V3 => (&one, Some(&k.signer), EncryptOptions::default()), + // DE: Strom und Datei mit gleichen Optionen; der Weg folgt aus `is_stream`. + // EN: Stream and file with the same options; the way follows from `is_stream`. + Kind::V4Pad | Kind::V4Stream => (&one, None, opts(true, false, false)), + Kind::V4Hidden | Kind::V4StreamHidden => (&one, Some(&k.signer), opts(false, false, true)), + Kind::V4Anon => (&anon, None, opts(false, true, false)), + }; + let p = Protection::Slots { + passphrase: None, + recipients, + }; + if is_stream(kind) { + files::encrypt_stream_to(&mut &plain[..], &enc, &p, signer, options).unwrap(); + } else { + files::encrypt_with_options(&src, &enc, &p, signer, options).unwrap(); + } + let bytes = std::fs::read(&enc).unwrap(); + std::fs::remove_file(&enc).unwrap(); + std::fs::remove_file(&src).unwrap(); + bytes +} + +fn opts(pad: bool, anonymous: bool, hide_sender: bool) -> EncryptOptions { + EncryptOptions { + pad, + anonymous, + hide_sender, + } +} + +pub fn is_stream(kind: Kind) -> bool { + matches!(kind, Kind::V4Stream | Kind::V4StreamHidden) +} + +/// DE: Länge des Headers (v1 bzw. v2–v4). EN: Header length (v1 or v2–v4). +pub fn header_len(bytes: &[u8]) -> usize { + if u16::from_le_bytes([bytes[8], bytes[9]]) == 1 { + let header = files::FileHeader::read(&mut &bytes[..]).unwrap(); + header.encode().len() + } else { + super::v2_files::header_len(bytes) + } +} + +/// DE: Bereich des verschlüsselten Stroms (ohne Header und sichtbare Signatur). +/// EN: Range of the encrypted stream (without header and visible signature). +pub fn body(kind: Kind, bytes: &[u8]) -> std::ops::Range { + let end = bytes.len() - if kind == Kind::V3 { SIG_LEN } else { 0 }; + header_len(bytes)..end +} + +/// DE: Lesepfade. EN: Read paths. +#[derive(Clone, Copy, Debug)] +pub enum Path4 { + Decrypt, + Check, + List, + Original, +} + +/// DE: `bytes` muss auf `path` scheitern; nichts wird veröffentlicht, keine Temporärreste. +/// EN: `bytes` must fail on `path`; nothing is published, no temporary leftovers. +pub fn must_fail(dir: &Path, bytes: &[u8], unlock: &Unlock<'_>, path: Path4, what: &str) { + let input = dir.join("probe.pqkf"); + std::fs::write(&input, bytes).unwrap(); + let out = dir.join("probe.out"); + let restored: PathBuf = dir.join("restored"); + let result = match path { + Path4::Decrypt => files::decrypt(&input, &out, unlock).map(|_| ()), + Path4::Check => files::check(&input, unlock).map(|_| ()), + Path4::List => files::list(&input, unlock).map(|_| ()), + Path4::Original => { + let choose = |_: &Path| Some(restored.clone()); + files::decrypt_original(&input, dir, unlock, None, &choose).map(|_| ()) + } + }; + assert!( + result.is_err(), + "{what} ({path:?}) wurde angenommen / was accepted" + ); + assert!( + !out.exists() && !restored.exists(), + "{what}: Ausgabe / output" + ); + std::fs::remove_file(&input).unwrap(); + let left = super::dir_names(dir); + assert!( + left.iter().all(|n| !n.contains(".tmp-")), + "{what}: {left:?}" + ); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 6b04a50..07ecea4 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -7,6 +7,7 @@ pub mod archive; pub mod fake_dialog; +pub mod integrity; pub mod rekey; pub mod v2_files; pub mod v2_header; diff --git a/tests/files_hidden_sender.rs b/tests/files_hidden_sender.rs index 7c84637..830dacd 100644 --- a/tests/files_hidden_sender.rs +++ b/tests/files_hidden_sender.rs @@ -70,6 +70,10 @@ fn opened( result } +fn assert_sender(report: files::Report, public: &PublicKeyFile) { + assert_eq!(report.signer.unwrap().key_id(), public.key_id()); +} + #[test] fn file_directory_and_stream_roundtrip_with_hidden_sender() { let dir = tempfile::tempdir().unwrap(); @@ -91,12 +95,8 @@ fn file_directory_and_stream_roundtrip_with_hidden_sender() { let _ = std::fs::remove_file(&enc); files::encrypt_with_options(src, &enc, &p, Some(&key), options).unwrap(); assert_hidden(&enc, &key, content); - let report = opened(&enc, &unlock, None).unwrap(); - assert_eq!(report.signer.unwrap().key_id, public.key_id()); - assert_eq!( - files::check(&enc, &unlock).unwrap().signer.unwrap().key_id, - public.key_id() - ); + assert_sender(opened(&enc, &unlock, None).unwrap(), &public); + assert_sender(files::check(&enc, &unlock).unwrap(), &public); assert!(files::list(&enc, &unlock).is_ok()); } let enc = dir.path().join("s.pqkf"); @@ -104,10 +104,7 @@ fn file_directory_and_stream_roundtrip_with_hidden_sender() { let plain = vec![9u8; 70_000]; files::encrypt_stream_to(&mut &plain[..], &enc, &p, Some(&key), options).unwrap(); assert_hidden(&enc, &key, Content::Stream); - assert_eq!( - opened(&enc, &unlock, None).unwrap().signer.unwrap().key_id, - public.key_id() - ); + assert_sender(opened(&enc, &unlock, None).unwrap(), &public); assert_eq!(std::fs::read(enc.with_file_name("klar")).unwrap(), plain); let header = files::inspect_v2(&enc).unwrap(); assert_eq!( @@ -145,7 +142,7 @@ fn anonymous_recipient_with_hidden_sender() { let header = files::inspect_v2(&enc).unwrap(); assert_eq!(header.v4.unwrap().options & OPT_ANON, OPT_ANON); let report = opened(&enc, &Unlock::Key(&unlocked), Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id, public.key_id()); + assert_eq!(report.signer.unwrap().key_id(), public.key_id()); } #[test] diff --git a/tests/files_signed.rs b/tests/files_signed.rs index 7987003..f28a741 100644 --- a/tests/files_signed.rs +++ b/tests/files_signed.rs @@ -72,7 +72,7 @@ fn signed_passphrase_file_is_v3_and_names_the_sender() { assert_eq!(v2::version(&bytes), 3); let unlock = Unlock::Passphrase(pass.as_ref()); let report = open(&w, &bytes, &unlock, None).unwrap(); - assert_eq!(report.signer.unwrap().key_id, public.key_id()); + assert_eq!(report.signer.unwrap().key_id(), public.key_id()); // DE: Verlangter, richtiger Absender. EN: Required, correct sender. assert!(open(&w, &bytes, &unlock, Some(&public)).is_ok()); // DE: Header zeigt den Absender ungeprüft. EN: Header shows the sender unverified. @@ -111,12 +111,12 @@ fn signed_works_with_recipients_factor_and_check() { }, ] { let report = open(&w, &bytes, &unlock, Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id, public.key_id()); + assert_eq!(report.signer.unwrap().key_id(), public.key_id()); } let input = w.work.join("check.pqkf"); std::fs::write(&input, &bytes).unwrap(); let report = files::check_with(&input, &Unlock::Key(&anna), Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id, public.key_id()); + assert_eq!(report.signer.unwrap().key_id(), public.key_id()); assert!(files::list(&input, &Unlock::Key(&ben)).is_ok()); std::fs::remove_file(&input).unwrap(); } diff --git a/tests/integrity_chunks.rs b/tests/integrity_chunks.rs new file mode 100644 index 0000000..e9044b1 --- /dev/null +++ b/tests/integrity_chunks.rs @@ -0,0 +1,146 @@ +//! DE: Integrität (#335, Lücken G3/G4): Auf Dateiebene für jedes Format (v1–v4, Archiv und Strom, +//! mit Füllung, sichtbarer bzw. verborgener Signatur, anonymen Empfängern) Blöcke tauschen, +//! doppeln, entfernen, an jeder Blockgrenze und kurz vor dem Ende abschneiden, anhängen und Blöcke +//! einer zweiten Datei einsetzen – `decrypt` und `check` scheitern ohne Ausgabe. Frische: zweimal +//! dieselbe Quelle ergibt anderen Präfix, andere Schlüsselbindung (v4) und anderes Chiffrat. +//! EN: Integrity (#335, gaps G3/G4): at file level for every format (v1–v4, archive and stream, +//! with padding, visible or hidden signature, anonymous recipients) swap, duplicate and remove +//! chunks, cut at every chunk boundary and just before the end, append, and insert chunks of a +//! second file – `decrypt` and `check` fail without output. Freshness: the same source twice gives +//! a different prefix, key commitment (v4) and ciphertext. + +// DE: Tests dürfen unwrap/expect nutzen. EN: Tests may use unwrap/expect. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::integrity::{self, ALL, ENC_CHUNK, Kind, Path4, must_fail}; + +/// DE: Drei Blöcke (zwei volle, ein kurzer letzter). EN: Three chunks (two full, a short last one). +fn plain() -> Vec { + (0..2 * 64 * 1024 + 777usize) + .map(|i| u8::try_from(i % 251).unwrap()) + .collect() +} + +/// DE: Setzt Header, veränderten Strom und ggf. die sichtbare Signatur zusammen. +/// EN: Joins header, altered stream and the visible signature if any. +fn rebuild(kind: Kind, good: &[u8], body: &[u8]) -> Vec { + let range = integrity::body(kind, good); + [&good[..range.start], body, &good[range.end..]].concat() +} + +fn chunks(body: &[u8]) -> Vec<&[u8]> { + body.chunks(ENC_CHUNK).collect() +} + +/// DE: Alle Strom-Varianten eines Falls. EN: All stream variants of a case. +fn variants(kind: Kind, good: &[u8], other: &[u8]) -> Vec<(String, Vec)> { + let body = &good[integrity::body(kind, good)]; + let foreign = &other[integrity::body(kind, other)]; + let c = chunks(body); + let f = chunks(foreign); + assert!(c.len() >= 3, "{kind:?}: {} Blöcke / chunks", c.len()); + let mut out = vec![ + ( + "Tausch 0/1 / swap".into(), + [c[1], c[0], &c[2..].concat()].concat(), + ), + ( + "Doppel 0 / duplicate".into(), + [c[0], c[0], &c[1..].concat()].concat(), + ), + ("ohne 1 / without".into(), [c[0], &c[2..].concat()].concat()), + ( + "fremd 1 / foreign".into(), + [c[0], f[1], &c[2..].concat()].concat(), + ), + ( + "fremd letzter / foreign last".into(), + [&c[..c.len() - 1].concat(), *f.last().unwrap()].concat(), + ), + ("angehängt / appended".into(), [body, f[0]].concat()), + ( + "1 Byte mehr / one byte more".into(), + [body, &[0u8][..]].concat(), + ), + ( + "1 Byte weniger / one byte less".into(), + body[..body.len() - 1].to_vec(), + ), + ( + "16 Byte weniger / 16 bytes less".into(), + body[..body.len() - 16].to_vec(), + ), + ]; + for k in 0..c.len() { + out.push((format!("Schnitt nach Block {k} / cut"), c[..k].concat())); + } + out.into_iter() + .map(|(what, b)| (what, rebuild(kind, good, &b))) + .collect() +} + +#[test] +fn chunk_manipulations_fail_on_every_format() { + let dir = tempfile::tempdir().unwrap(); + let keys = integrity::keys(); + let data = plain(); + for kind in ALL { + let good = integrity::seal(dir.path(), "a", kind, &keys, &data); + let other = integrity::seal(dir.path(), "b", kind, &keys, &data); + let unlock = keys.unlock(kind); + for (what, bad) in variants(kind, &good, &other) { + let what = format!("{kind:?}: {what}"); + must_fail(dir.path(), &bad, &unlock, Path4::Decrypt, &what); + must_fail(dir.path(), &bad, &unlock, Path4::Check, &what); + } + // DE: Unverändert öffnet die Datei. EN: Unchanged, the file opens. + let input = dir.path().join("gut.pqkf"); + std::fs::write(&input, &good).unwrap(); + let out = dir.path().join("gut.out"); + pqkeep::files::decrypt(&input, &out, &unlock).unwrap(); + assert_eq!(std::fs::read(&out).unwrap(), data, "{kind:?}"); + std::fs::remove_file(&out).unwrap(); + std::fs::remove_file(&input).unwrap(); + } +} + +/// DE: Nonce-Präfix aus dem geparsten Header. EN: Nonce prefix from the parsed header. +fn prefix(bytes: &[u8]) -> [u8; 7] { + if u16::from_le_bytes([bytes[8], bytes[9]]) == 1 { + pqkeep::files::FileHeader::read(&mut &bytes[..]) + .unwrap() + .prefix + } else { + pqkeep::files::HeaderV2::read(&mut &bytes[..]) + .unwrap() + .prefix + } +} + +#[test] +fn same_source_twice_is_fresh_on_every_format() { + let dir = tempfile::tempdir().unwrap(); + let keys = integrity::keys(); + for kind in ALL { + let a = integrity::seal(dir.path(), "a", kind, &keys, b"gleich / same"); + let b = integrity::seal(dir.path(), "b", kind, &keys, b"gleich / same"); + assert_ne!(prefix(&a), prefix(&b), "{kind:?}: Präfix / prefix"); + let (ra, rb) = (integrity::body(kind, &a), integrity::body(kind, &b)); + assert_ne!( + &a[ra.clone()][..16], + &b[rb][..16], + "{kind:?}: Chiffrat / ciphertext" + ); + assert_ne!(&a[..ra.start], &b[..ra.start], "{kind:?}: Header"); + if u16::from_le_bytes([a[8], a[9]]) == 4 { + let commit = |x: &[u8]| { + let path = dir.path().join("c.pqkf"); + std::fs::write(&path, x).unwrap(); + pqkeep::files::inspect_v2(&path).unwrap().v4.unwrap().commit + }; + assert_ne!(commit(&a), commit(&b), "{kind:?}: commit"); + } + } +} diff --git a/tests/integrity_headers.rs b/tests/integrity_headers.rs new file mode 100644 index 0000000..411169b --- /dev/null +++ b/tests/integrity_headers.rs @@ -0,0 +1,82 @@ +//! DE: Integrität (#335, Lücke G2, QA1-FMT-003): Jedes Header-Byte einer kleinen Datei in jedem +//! Format (v1–v4: mehrere Empfänger, sichtbare Signatur, Füllung, verborgener Absender, anonyme +//! Empfänger, Strom) wird gekippt; `decrypt` scheitert für jedes Byte, zusätzlich je Byte reihum +//! `check`, `list` oder `decrypt --original-name` – nie eine Ausgabe, nie ein Temporärrest. Die +//! Pfade teilen sich das Öffnen des Headers; reihum hält die Laufzeit klein. +//! EN: Integrity (#335, gap G2, QA1-FMT-003): every header byte of a small file in every format +//! (v1–v4: several recipients, visible signature, padding, hidden sender, anonymous recipients, +//! stream) is flipped; `decrypt` fails for every byte, plus per byte in turn `check`, `list` or +//! `decrypt --original-name` – never any output, never a temporary leftover. The paths share +//! header opening; rotating keeps the run time small. + +// DE: Tests dürfen unwrap/expect nutzen. EN: Tests may use unwrap/expect. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use common::integrity::{self, ALL, Kind, Path4, must_fail}; + +const OTHERS: [Path4; 3] = [Path4::Check, Path4::List, Path4::Original]; + +fn every_header_byte(kind: Kind) { + let dir = tempfile::tempdir().unwrap(); + let keys = integrity::keys(); + let unlock = keys.unlock(kind); + let good = integrity::seal(dir.path(), "gut", kind, &keys, b"Integritaet / integrity"); + let len = integrity::header_len(&good); + assert!(len > 32, "{kind:?}: {len}"); + for i in 0..len { + let mut bad = good.clone(); + bad[i] ^= 0x01; + let what = format!("{kind:?} Byte {i}/{len}"); + must_fail(dir.path(), &bad, &unlock, Path4::Decrypt, &what); + must_fail(dir.path(), &bad, &unlock, OTHERS[i % OTHERS.len()], &what); + } +} + +#[test] +fn v1_and_v2_headers() { + every_header_byte(Kind::V1); + every_header_byte(Kind::V2); +} + +#[test] +fn v3_header_with_visible_sender() { + every_header_byte(Kind::V3); +} + +#[test] +fn v4_file_headers() { + for kind in [Kind::V4Pad, Kind::V4Hidden, Kind::V4Anon] { + every_header_byte(kind); + } +} + +#[test] +fn v4_stream_headers() { + for kind in [Kind::V4Stream, Kind::V4StreamHidden] { + every_header_byte(kind); + } +} + +#[test] +fn unchanged_files_open_on_every_path() { + let dir = tempfile::tempdir().unwrap(); + let keys = integrity::keys(); + for kind in ALL { + let bytes = integrity::seal(dir.path(), "gut", kind, &keys, b"ok"); + let input = dir.path().join("ok.pqkf"); + std::fs::write(&input, &bytes).unwrap(); + let out = dir.path().join("ok.out"); + pqkeep::files::decrypt(&input, &out, &keys.unlock(kind)).unwrap(); + assert_eq!(std::fs::read(&out).unwrap(), b"ok", "{kind:?}"); + std::fs::remove_file(&out).unwrap(); + assert_eq!( + pqkeep::files::check(&input, &keys.unlock(kind)) + .unwrap() + .bytes, + 2 + ); + std::fs::remove_file(&input).unwrap(); + } +} diff --git a/tests/integrity_kill.rs b/tests/integrity_kill.rs new file mode 100644 index 0000000..41eb4e4 --- /dev/null +++ b/tests/integrity_kill.rs @@ -0,0 +1,110 @@ +//! DE: Integrität (#335, Lücke G6, QA1-REC-003): `pqkeep decrypt` wird mitten im Schreiben per +//! SIGKILL beendet – das Ziel erscheint nie. Bekannte Grenze (L1, Abhilfe in #338): Ein +//! Temporärrest mit verstecktem Namen und Rechten 0600 kann bleiben; er wird beim nächsten Lauf +//! nicht übernommen, das erneute Entschlüsseln gelingt und veröffentlicht nur geprüfte Daten. +//! EN: Integrity (#335, gap G6, QA1-REC-003): `pqkeep decrypt` is killed with SIGKILL while +//! writing – the target never appears. Known limit (L1, remedy in #338): a temporary leftover with +//! a hidden name and mode 0600 may remain; the next run does not adopt it, decrypting again +//! succeeds and publishes only verified data. +#![cfg(target_os = "linux")] +#![allow(clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use std::io::{Read, Write}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use pqkeep::crypto::{KemAlgorithm, KeyAlgorithm}; +use pqkeep::envelope::{self, Overwrite}; +use pqkeep::files::{self, EncryptOptions, Protection}; + +const SIZE: u64 = 256 * 1024 * 1024; + +fn temps(dir: &Path) -> Vec { + common::dir_names(dir) + .into_iter() + .filter(|n| n.contains(".tmp-")) + .collect() +} + +const ARGS: [&str; 7] = [ + "decrypt", + "gross.pqkf", + "--key", + "k.key.json", + "-o", + "gross.bin", + "--passphrase-stdin", +]; + +/// DE: Schlüssel und großer Strom in `d`; liefert die Passphrase-Zeile für stdin. +/// EN: Key and large stream in `d`; returns the passphrase line for stdin. +fn fixture(d: &Path) -> String { + let (file, pass) = common::key_file(KeyAlgorithm::Kem(KemAlgorithm::MlKem768)); + envelope::save(&file, &d.join("k.key.json"), Overwrite::No).unwrap(); + let public = file.public_part().unwrap(); + let p = Protection::Recipient(&public); + let mut source = std::io::repeat(0x42).take(SIZE); + let enc = d.join("gross.pqkf"); + files::encrypt_stream_to(&mut source, &enc, &p, None, EncryptOptions::default()).unwrap(); + format!("{}\n", pass.as_ref().expose_str()) +} + +/// DE: Startet `decrypt`, wartet, bis die Temporärdatei wächst, und beendet per SIGKILL; liefert +/// den Namen der Temporärdatei. EN: Starts `decrypt`, waits until the temporary file grows and +/// kills with SIGKILL; returns the temporary file's name. +fn start_and_kill(d: &Path, line: &str) -> String { + let mut child = Command::new(env!("CARGO_BIN_EXE_pqkeep")) + .args(ARGS) + .current_dir(d) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(line.as_bytes()).unwrap(); + drop(stdin); + let start = Instant::now(); + let seen = loop { + let grown = temps(d) + .into_iter() + .find(|t| std::fs::metadata(d.join(t)).is_ok_and(|m| m.len() > 0)); + if let Some(t) = grown { + break t; + } + let running = child.try_wait().unwrap().is_none(); + assert!(running, "zu schnell fertig / finished too fast"); + let waited = start.elapsed() < Duration::from_secs(120); + assert!(waited, "keine Temporärdatei / no temp"); + std::thread::sleep(Duration::from_millis(2)); + }; + child.kill().unwrap(); + child.wait().unwrap(); + seen +} + +#[test] +fn killed_decrypt_never_publishes_the_target() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + let line = fixture(d); + let seen = start_and_kill(d, &line); + assert!( + !d.join("gross.bin").exists(), + "Ziel nach Kill / target after kill" + ); + // DE: Grenze L1: Rest kann bleiben – nur für den Eigentümer lesbar. + // EN: Limit L1: a leftover may remain – readable by the owner only. + if let Ok(meta) = std::fs::metadata(d.join(&seen)) { + assert_eq!(meta.permissions().mode() & 0o077, 0, "Rechte / mode"); + } + let (code, _, err) = common::pqkeep(&ARGS, &line, d); + assert_eq!(code, 0, "{err}"); + assert_eq!(std::fs::metadata(d.join("gross.bin")).unwrap().len(), SIZE); + // DE: Der alte Rest wurde nicht übernommen. EN: The old leftover was not adopted. + assert!(temps(d).iter().all(|t| *t == seen), "{:?}", temps(d)); +} diff --git a/tests/process_capability.rs b/tests/process_capability.rs new file mode 100644 index 0000000..1c99191 --- /dev/null +++ b/tests/process_capability.rs @@ -0,0 +1,96 @@ +//! DE: Prozessbeobachtung ist lesend; Härtung ausschließlich im eigenen Kind. +//! EN: Process observation is read-only; hardening runs only in an owned child. +#![allow(clippy::unwrap_used)] + +use pqkeep::hardening::{harden_process, observe_process}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +#[test] +fn actual_readback_and_child_hardening_preserve_parent_policy() { + let before = observe_process(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "process_readback_child", + "--ignored", + "--test-threads=1", + ]) + .env("PQKEEP_PROCESS_READBACK_CHILD", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(status) = child.try_wait().unwrap() { + let output = child.wait_with_output().unwrap(); + assert!( + status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); + break; + } + let timed_out = Instant::now() >= deadline; + if timed_out { + child.kill().unwrap(); + child.wait().unwrap(); + } + assert!( + !timed_out, + "DE/EN: Prozessabfrage-Timeout / process query timeout" + ); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(observe_process(), before); +} + +#[test] +#[ignore = "DE/EN: Nur vom begrenzten Elternprozess / bounded parent invocation only"] +fn process_readback_child() { + assert_eq!(std::env::var("PQKEEP_PROCESS_READBACK_CHILD").unwrap(), "1"); + #[cfg(target_os = "linux")] + { + use rustix::process::{DumpableBehavior, Resource, dumpable_behavior, getrlimit}; + let core = getrlimit(Resource::Core); + let dumpable = dumpable_behavior().unwrap(); + let observed = observe_process(); + assert_eq!( + observed.core_dumps_disabled, + core.current == Some(0) && core.maximum == Some(0) + ); + assert_eq!( + observed.not_dumpable, + dumpable == DumpableBehavior::NotDumpable + ); + assert_eq!(getrlimit(Resource::Core), core); + assert_eq!(dumpable_behavior().unwrap(), dumpable); + let applied = harden_process(); + assert!(applied.complete()); + assert_eq!(applied, observe_process()); + assert_eq!(getrlimit(Resource::Core).current, Some(0)); + assert_eq!(getrlimit(Resource::Core).maximum, Some(0)); + assert_eq!(dumpable_behavior().unwrap(), DumpableBehavior::NotDumpable); + } + #[cfg(windows)] + { + use pqkeep_platform::{WerFlags, current_wer_flags}; + let before = current_wer_flags().unwrap(); + let observed = observe_process(); + assert_eq!(current_wer_flags().unwrap(), before); + assert_eq!( + observed.wer_heap_reporting_disabled, + matches!(before, WerFlags::Present(flags) if flags & 1 != 0) + ); + let applied = harden_process(); + let after = current_wer_flags().unwrap(); + assert!(applied.wer_heap_reporting_disabled); + assert_eq!(applied, observe_process()); + assert!(!applied.complete()); + if let (WerFlags::Present(old), WerFlags::Present(new)) = (before, after) { + assert_eq!(new & old, old); + } + } +} From 386984fdedece83e87621656ac99296dd820dd37 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:17:12 +0100 Subject: [PATCH 03/26] Diagnose native process access probe failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Ausschließlich feste öffentliche Zugriffsmaske und Fehler des eigenen Inspectors protokollieren. DACL, Rechteumfang, strenge Denial-Prüfung und konkrete Freigabe unverändert. Erste native Probe bestätigt Policy-Readback, Zugriffstest scheitert; kein R7-Abschluss. EN: Report the exact public access mask and owned inspector error for the native Windows experiment. Do not weaken assertions or change the approved own-process policy scope. Native denial remains unverified; joint R7/R8 work stays Draft. Refs #147. --- .../pqkeep-platform/examples/process_access_probe.rs | 12 ++++++++++-- scripts/test_process_access_probe.ps1 | 2 ++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/platform/pqkeep-platform/examples/process_access_probe.rs b/platform/pqkeep-platform/examples/process_access_probe.rs index 4f9b950..9fee2ff 100644 --- a/platform/pqkeep-platform/examples/process_access_probe.rs +++ b/platform/pqkeep-platform/examples/process_access_probe.rs @@ -126,9 +126,17 @@ mod windows { fn inspect(pid: u32) -> io::Result<()> { for rights in [0x10, 0x20, 0x08, 0x40, 0x02, WRITE_DAC, 0x80000] { match open(pid, rights) { - Ok(_) => return Err(io::Error::other("sensitive process access allowed")), + Ok(_) => { + return Err(io::Error::other(format!( + "sensitive process access allowed: {rights:#x}" + ))); + } Err(error) if error.raw_os_error() == Some(5) => (), - Err(_) => return Err(io::Error::other("unexpected process query failure")), + Err(error) => { + return Err(io::Error::other(format!( + "unexpected process query failure: {rights:#x}: {error}" + ))); + } } } let _query = open(pid, 0x1000 | 0x0010_0000)?; diff --git a/scripts/test_process_access_probe.ps1 b/scripts/test_process_access_probe.ps1 index 06d4b11..79e60ed 100644 --- a/scripts/test_process_access_probe.ps1 +++ b/scripts/test_process_access_probe.ps1 @@ -38,6 +38,8 @@ try { if (-not $inspector.WaitForExit(10000)) { throw 'Own inspector timeout' } $result = $inspector.StandardOutput.ReadToEnd() if ($inspector.ExitCode -ne 0 -or -not $result.StartsWith('PASS:')) { + # DE/EN: Nur feste öffentliche Probenfehler, keine Geheimwerte / public probe errors only. + Write-Output ($inspector.StandardError.ReadToEnd()) throw 'Own inspector rejected process access policy' } $target.StandardInput.Close() From ac02078cebd7ff0549581e00f648feede93ce494 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:21:17 +0100 Subject: [PATCH 04/26] Read back inspector debug privilege without modifying tokens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Native Probe zeigt erlaubtes PROCESS_VM_READ trotz bestätigter eigener DACL. Nur TOKEN_QUERY am eigenen CI-Prozesstoken öffnen, GetTokenInformation lesen und ausschließlich Debug-Privilege-enabled-Bool ausgeben. Keine Token-/Thread-/Konten-/Rechteänderung; keine Aktivierung von Privilegien, kein Skip und keine schwächere Denial-Prüfung. EN: Diagnose whether ambient CI SeDebugPrivilege bypasses DACL checks, using read-only own-token observation. Strict Windows cross-Clippy passes with validated DWORD geometry. Native privilege state remains unproven until the next actual run; R7 stays open. Refs #147. --- .../examples/process_access_probe.rs | 8 ++ .../process_access_probe/privileges.rs | 87 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 platform/pqkeep-platform/examples/process_access_probe/privileges.rs diff --git a/platform/pqkeep-platform/examples/process_access_probe.rs b/platform/pqkeep-platform/examples/process_access_probe.rs index 9fee2ff..005a903 100644 --- a/platform/pqkeep-platform/examples/process_access_probe.rs +++ b/platform/pqkeep-platform/examples/process_access_probe.rs @@ -3,6 +3,10 @@ //! EN: Public explicitly invoked process-object probe, not a production gate. //! No thread protection, existing-handle revocation, dump guarantee or R7 acceptance. +#[cfg(windows)] +#[path = "process_access_probe/privileges.rs"] +mod privileges; + #[cfg(windows)] mod windows { use std::io::{self, Read, Write}; @@ -124,6 +128,10 @@ mod windows { } fn inspect(pid: u32) -> io::Result<()> { + eprintln!( + "INSPECTOR debug_privilege_enabled={}", + super::privileges::debug_enabled()? + ); for rights in [0x10, 0x20, 0x08, 0x40, 0x02, WRITE_DAC, 0x80000] { match open(pid, rights) { Ok(_) => { diff --git a/platform/pqkeep-platform/examples/process_access_probe/privileges.rs b/platform/pqkeep-platform/examples/process_access_probe/privileges.rs new file mode 100644 index 0000000..d7c6b19 --- /dev/null +++ b/platform/pqkeep-platform/examples/process_access_probe/privileges.rs @@ -0,0 +1,87 @@ +//! DE: Ausschließlich lesende Diagnose des eigenen öffentlichen CI-Testtokens. +//! EN: Read-only diagnosis of the own public CI test token. + +use std::{ + io, + mem::{offset_of, size_of}, + os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, +}; +use windows_sys::Win32::{ + Foundation::LUID, + Security::{ + GetTokenInformation, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, SE_DEBUG_NAME, + SE_PRIVILEGE_ENABLED, TOKEN_PRIVILEGES, TOKEN_QUERY, TokenPrivileges, + }, + System::Threading::{GetCurrentProcess, OpenProcessToken}, +}; + +fn own_token() -> io::Result { + let mut handle = std::ptr::null_mut(); + // SAFETY: Current-process pseudo handle is borrowed only. The initialized + // output gets one new real TOKEN_QUERY handle; no adjustment right requested. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut handle) } == 0 { + return Err(io::Error::last_os_error()); + } + if handle.is_null() { + return Err(io::Error::other("missing own query token")); + } + // SAFETY: Successful API returned a uniquely owned real handle, closed once. + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) +} + +pub(super) fn debug_enabled() -> io::Result { + let token = own_token()?; + let (mut buffer, mut needed) = ([0u32; 512], 0); + // SAFETY: Live own TOKEN_QUERY handle; initialized aligned2048byte buffer; + // exact capacity passed and exclusive output count. No token writes. + if unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenPrivileges, + buffer.as_mut_ptr().cast(), + 2048, + &raw mut needed, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let needed = usize::try_from(needed).map_err(|_| io::Error::other("invalid token length"))?; + let offset = offset_of!(TOKEN_PRIVILEGES, Privileges); + if offset % size_of::() != 0 || !(offset..=size_of_val(&buffer)).contains(&needed) { + return Err(io::Error::other("invalid token result length")); + } + let count = usize::try_from(buffer[0]).map_err(|_| io::Error::other("invalid token count"))?; + if count > (needed - offset) / size_of::() { + return Err(io::Error::other("invalid token records")); + } + // SAFETY: DWORD-aligned record offset in a DWORD-aligned initialized buffer; + // complete count validated against actual returned bytes. All fields integer. + let values = unsafe { + std::slice::from_raw_parts( + buffer + .as_ptr() + .add(offset / size_of::()) + .cast::(), + count, + ) + }; + enabled(values) +} + +fn enabled(values: &[LUID_AND_ATTRIBUTES]) -> io::Result { + let mut debug = LUID { + LowPart: 0, + HighPart: 0, + }; + // SAFETY: Null means local system lookup; static NUL-terminated privilege + // name, exclusive initialized scalar output; no token or account mutation. + if unsafe { LookupPrivilegeValueW(std::ptr::null(), SE_DEBUG_NAME, &raw mut debug) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(values.iter().any(|value| { + value.Luid.LowPart == debug.LowPart + && value.Luid.HighPart == debug.HighPart + && value.Attributes & SE_PRIVILEGE_ENABLED != 0 + })) +} From 504abcba7fc3417dfdbaecd209aeef6f35de039e Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:12:44 +0100 Subject: [PATCH 05/26] Protect hidden sender construction and signature workspaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Verborgenen Signierschlüssel einschließlich Identitätsmatrix vor Seed-Verarbeitung sperren; keine gewöhnlichen Verifikations-Cache-Kopien. Signatur direkt in gesperrte Ausgabe kodieren; vollständige verborgene Dekodier-/SHAKE128-/Matrix-/NTT-/Hint-/Hashpfade vorab sperren. Originale Formeln, Nonces und Wire-Bytes erhalten. Identitätsvergleich mit vorhandener subtle2.6.1 in beiden Featurekonfigurationen; Versionen und Lockfile unverändert. EN: Direct protected-feature provider lint, strict root lint with/without API, ten DSA groups including actual denial/unwind children and all13 sender integration tests pass. Final local recheck: all721 source hashes unchanged, API all-target Clippy, ten DSA and61 file-module groups pass. No private payload/address assertion output. Current native/fuzz/audit acceptance and remaining metadata/process/helper gaps stay open; one joint Draft355, no partial merge. The reduced own CI-thread proposal is documentation only; unapproved token-changing executable sources remain unpublished locally. Refs #147. --- Cargo.toml | 4 +- docs/ROADMAP.md | 23 +- docs/SPEC.en.md | 6 + docs/SPEC.md | 6 + docs/security/CONFIDENTIAL_SENDER_IDENTITY.md | 6 + docs/security/HIDDEN_SIGNATURE_VALIDATION.md | 88 ++++++++ .../WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md | 69 ++++++ src/crypto/dsa.rs | 9 + src/crypto/dsa_confidential_denial_tests.rs | 68 ++++++ src/crypto/dsa_confidential_key.rs | 60 ++++++ src/crypto/dsa_confidential_sign.rs | 51 +++++ src/crypto/dsa_confidential_sign_tests.rs | 204 ++++++++++++++++++ src/crypto/dsa_confidential_verify.rs | 94 ++++++++ src/crypto/dsa_confidential_verify_tests.rs | 177 +++++++++++++++ src/files/hidden_result_tests.rs | 2 +- src/files/signed_by.rs | 8 +- src/files/signed_by_tests.rs | 30 ++- src/files/tail_v4.rs | 12 +- vendor/ml-dsa-0.1.2/src/algebra.rs | 32 +++ vendor/ml-dsa-0.1.2/src/hint.rs | 2 +- vendor/ml-dsa-0.1.2/src/lib.rs | 4 + vendor/ml-dsa-0.1.2/src/param.rs | 70 ++++++ vendor/ml-dsa-0.1.2/src/sampling.rs | 6 + .../src/sampling/matrix_workspace.rs | 87 ++++++++ vendor/ml-dsa-0.1.2/src/signing.rs | 4 + vendor/ml-dsa-0.1.2/src/signing/borrowed.rs | 19 +- .../src/signing/confidential_encoding.rs | 59 +++++ .../src/signing/confidential_key.rs | 43 ++++ vendor/ml-dsa-0.1.2/src/signing/in_place.rs | 75 +++++++ vendor/ml-dsa-0.1.2/src/verifying.rs | 6 + .../src/verifying/confidential.rs | 75 +++++++ .../src/verifying/confidential_decode.rs | 35 +++ .../src/verifying/confidential_operations.rs | 92 ++++++++ 33 files changed, 1500 insertions(+), 26 deletions(-) create mode 100644 docs/security/HIDDEN_SIGNATURE_VALIDATION.md create mode 100644 docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md create mode 100644 src/crypto/dsa_confidential_denial_tests.rs create mode 100644 src/crypto/dsa_confidential_key.rs create mode 100644 src/crypto/dsa_confidential_sign.rs create mode 100644 src/crypto/dsa_confidential_sign_tests.rs create mode 100644 src/crypto/dsa_confidential_verify.rs create mode 100644 src/crypto/dsa_confidential_verify_tests.rs create mode 100644 vendor/ml-dsa-0.1.2/src/sampling/matrix_workspace.rs create mode 100644 vendor/ml-dsa-0.1.2/src/signing/confidential_encoding.rs create mode 100644 vendor/ml-dsa-0.1.2/src/signing/confidential_key.rs create mode 100644 vendor/ml-dsa-0.1.2/src/verifying/confidential.rs create mode 100644 vendor/ml-dsa-0.1.2/src/verifying/confidential_decode.rs create mode 100644 vendor/ml-dsa-0.1.2/src/verifying/confidential_operations.rs diff --git a/Cargo.toml b/Cargo.toml index eb342fa..1b6e527 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -81,7 +81,7 @@ region = { version = "4.0.1", path = "vendor/region-4.0.1" } serde = { version = "1.0.229", features = ["derive"] } serde_json = { version = "1.0.154", path = "vendor/serde_json-1.0.154" } sha3 = { version = "0.12.0", path = "vendor/sha3-0.12.0", features = ["zeroize", "protected-workspace"] } -subtle = { version = "2.6.1", optional = true } +subtle = "2.6.1" sys-locale = "0.3.2" thiserror = "2.0.21" tokio = { version = "1.54.1", default-features = false, features = ["rt-multi-thread", "net", "time", "signal", "sync"], optional = true } @@ -150,7 +150,7 @@ pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform", featur # (`--no-default-features`) a pure CLI without network code is built. [features] default = ["api"] -api = ["dep:axum", "dep:hyper", "dep:hyper-util", "dep:tokio", "dep:tower", "dep:subtle", "dep:mime"] +api = ["dep:axum", "dep:hyper", "dep:hyper-util", "dep:tokio", "dep:tower", "dep:mime"] # DE: Abhängigkeiten auch im Debug/Test-Build optimieren (Argon2 sonst extrem langsam). # Betrifft nur die Laufzeit, nicht die Semantik; eigener Code bleibt unoptimiert. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index fb843a4..bb5c4c2 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -150,9 +150,20 @@ EN: Prelock parser/source/index/depth/scratch descriptor; native/security/fuzz acceptance required. Other R6/R7/R8 boundaries remain OPEN. See [parser state plan](security/PARSER_STATE_OWNER_PLAN.md). -DE: #147 R6 In Bearbeitung: vollständige Provider-Lebensdauer in Draft334 umgesetzt; -alle neun Zeilen der [Abnahmematrix](security/PROVIDER_LIFETIME_VALIDATION.md) abgleichen. -Finaler signierter Head, native Linux-/Windows-/ARM64-CI, Security/Fuzz und exakter -Rückweg vor Merge erforderlich; kein Teilmerge. R7/R8 separat offen. -EN: Complete R6 implementation; final source-bound acceptance remains required. -Issue147 and roadmap stay In progress; no whole-issue closure. +DE: #147 R6 abgeschlossen: PR334 auf Mainb813bc6 mit allen neun Zeilen der +[Abnahmematrix](security/PROVIDER_LIFETIME_VALIDATION.md), nativer Linux-/Windows-/ +ARM64-Abnahme, Security/Fuzz und geprüftem Rückweg übernommen. R7/R8 separat offen. +EN: R6 completed on Main; current shared-provider changes retain its regression +checks. Issue147 and roadmap stay In progress; no whole-issue closure. + +DE: #147 R7/R8 gemeinsam in Bearbeitung in [Draft355](https://github.com/SpecterAoD/pqkeep/pull/355): +[vollständig freigegebener Plan](security/PROCESS_METADATA_COMPLETION_PLAN.md). +Geschützte Pfadindex-Knoten und Absenderidentität veröffentlicht; geschützter +verborgener Signierschlüssel-/Kodier-/Verifikationspfad im selben Draft umgesetzt, +Gesamtabnahme noch offen. Windows-DACL nativ zurückgelesen, privilegierter +SeDebugPrivilege-Bypass tatsächlich nachgewiesen; neuer eigener reduzierter +CI-Threadversuch benötigt separate konkrete Freigabe. Kein Teilmerge. +EN: One joint PR; platform/helper, remaining metadata, native/security/fuzz and +full rollback acceptance remain open. See +[hidden signature scope](security/HIDDEN_SIGNATURE_VALIDATION.md) and +[restricted inspector proposal](security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md). diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 2810bbf..917b466 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -7,6 +7,12 @@ > scratch, process/helper and other metadata paths remain open. See > [confidential sender identity](security/CONFIDENTIAL_SENDER_IDENTITY.md). +> R8 follow-up in PR355: hidden signing-key construction, encoding and verification +> use prelocked workspaces including identity-derived matrices and SHAKE128 scratch, +> without ordinary Signature/cache copies in these paths. Implemented in the joint draft; +> final joint native acceptance remains pending. See +> [validation scope and limits](security/HIDDEN_SIGNATURE_VALIDATION.md). + > **Translation note:** This is the English translation of [`SPEC.md`](SPEC.md) (German), version > 2.22. Both versions are maintained together; every change to one is made to the other in the > same pull request. If they ever contradict each other, the German version applies until the diff --git a/docs/SPEC.md b/docs/SPEC.md index 142d38f..ee5dc53 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -7,6 +7,12 @@ > Signatur-Scratch, Prozess-/Helper- und übrige Metadatenpfade weiter offen. > Details: [vertrauliche Absenderidentität](security/CONFIDENTIAL_SENDER_IDENTITY.md). +> R8-Folgebaustein in PR355: Verborgener Signierschlüssel-Aufbau, Kodierung und +> Verifikation verwenden vorab gesperrte Arbeitsflächen einschließlich Identitäts- +> matrix und SHAKE128-Scratch; keine gewöhnlichen Signature-/Cache-Kopien in +> diesen Pfaden. Umsetzung im gemeinsamen Draft, finale native Abnahme noch offen. +> [Prüfumfang und Grenzen](security/HIDDEN_SIGNATURE_VALIDATION.md). + > **English translation:** [`SPEC.en.md`](SPEC.en.md) – beide Fassungen werden im selben Pull Request gemeinsam geändert; bei Widersprüchen gilt bis zur Korrektur die deutsche. / Both versions are changed together in the same pull request; in case of contradiction the German one applies until fixed. > Änderung v2.19 (22.11.2026, Eigentümerauftrag zur autonomen Sicherheitsbehebung bis main): Secret-Speicher einschließlich KDF-/HKDF-Arbeitspuffern zwingend sperren; Fehler statt ungesperrtem Fallback, begrenzte Eingaben und sichere Freigabe. Keine Änderung von Format-/Ableitungsbytes. Details: [LOCKED_SECRETS.md](security/LOCKED_SECRETS.md). diff --git a/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md b/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md index edea4e6..e617213 100644 --- a/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md +++ b/docs/security/CONFIDENTIAL_SENDER_IDENTITY.md @@ -6,6 +6,12 @@ haben weiterhin gesondert zu bearbeitende Provider-/Scratchpfade. M5-Ausgaben und Reportzähler sind ebenfalls noch nicht vollständig geschützt. EN: Local implementation in progress, not a complete R8 or issue147 closure. +DE: Aktueller Folgebaustein: Signaturkodierung, Schlüsselaufbau und vollständige +Verifikations-Scratchpfade sind jetzt zusätzlich lokal implementiert; ihre native +Gesamtabnahme ist noch offen. Siehe [HIDDEN_SIGNATURE_VALIDATION.md](HIDDEN_SIGNATURE_VALIDATION.md). +EN: Fixed-length identity equality reuses subtle2.6.1 in both feature configurations; +noncanonical identity lengths are refused before allocation. No version change. + ## Data flow / Datenfluss DE: Vorher kopierte hidden_sender den verborgenen öffentlichen Schlüssel aus diff --git a/docs/security/HIDDEN_SIGNATURE_VALIDATION.md b/docs/security/HIDDEN_SIGNATURE_VALIDATION.md new file mode 100644 index 0000000..91c9127 --- /dev/null +++ b/docs/security/HIDDEN_SIGNATURE_VALIDATION.md @@ -0,0 +1,88 @@ +# Hidden signature protection / Schutz verborgener Signaturen + +DE: M4-Implementierungsstand im gemeinsamen R7/R8-Draft355. +Noch kein vollständiger R8-/Prozess-/Helper-Abschluss und kein Teilmerge. +EN: Current joint draft implementation, not final native/platform acceptance. + +## Concrete source paths / Konkrete Quellpfade + +| Path / Pfad | Protected ownership / Geschützte Ownership | +|---|---| +| Hidden signing key construction | Dedicated ExpandedSigningKey public-empty state; lock full inline key and each existing matrix row before seed input. No ordinary verifying-key/cache construction or cloned public matrix on this path. | +| Key-generation scratch | ConfidentialKeyGenerationWorkspace prelocked: original key-generation workspace, SHAKE128 matrix sampler and encoded verifying key used only for tr. No returned ordinary public-key encoding. | +| Signing candidate | Reuse the original nonce/rejection checks through accept_candidate; every candidate remains in existing protected SigningWorkspace. Same canonicalization for original public and new confidential output. | +| Signature encoding | Prelocked SecretBytes output; map z in protected candidate, original vector codec into borrowed output, hints directly into protected output. No returned Signature/MaybeBox/challenge/z/hint/encoded arrays. | +| Verification input | Borrow typed encoded key/signature views directly from caller bytes; no copied encoded owner. Trailer bytes are already locked; intentionally public caller-provided key inputs remain caller-owned. | +| Verification decoding | Prelocked t1/z and complete hints; read encoded cuts/indices by borrow, never create ordinary intermediate arrays or Hint allocation. Same norm/order/range/zero-tail checks. | +| Matrix and verification arithmetic | Prelock complete workspace and all nested matrix-row allocations; SHAKE128/reader/840-byte sampler/extra three bytes, NTT, product, difference, inverse, UseHint, w1 packing and challenge hashing all use those destinations. | +| Identity retention | Existing new SignedBy/HiddenResult protected owners; explicit borrowed key_id, fallible duplication, redacted Debug. Compare fixed-length IDs with existing subtle2.6.1 in both feature configurations. | + +DE: Unveränderte Versionen ML-DSA0.1.2, module-lattice0.2.4 und SHAKE0.1.0. +Kein neuer Kryptoalgorithmus, keine geänderten Parameter oder Rejection-Grenzen, +kein deterministischer Fallback. Gemeinsame vorhandene Sampling-/NTT-/Multiply-/ +Power2Round-/UseHint-/Codec-Schritte verwenden. Der ursprünglich öffentliche +Signatur-/Verifikationspfad bleibt für ausdrücklich öffentliche API-Operationen +erhalten; verborgene Dateioperationen rufen ausschließlich die neuen Pfade auf. +EN: Hidden verification propagates MemoryLock distinctly from an invalid signature; +never collapse resource refusal into an unchecked successful signature. + +## Destruction and boundaries / Freigabe und Grenzen + +DE: Root hält stabile SecretState-Owner und gesperrte LockedRange-Records. Alle +Matrixzeilen bleiben über die Operation hinweg adressstabil. Beim Drop zuerst +sämtliche privaten Felder einschließlich Identitätsmatrix löschen, dann die +Zeilensperren freigeben. Bestehende SecretState-/SecretBytes-Destruktoren löschen +vollständige frühere Record-/Pufferkapazität und Padding vor Unlock/Free. +EN: Public-zero preparation precedes locking; no private matrix-row replacement +after guards are acquired. Partial initialization/lock refusal admits no seed +or hidden key/signature input. Exact cleanup is checked in an isolated child. + +DE: Die neue Matrix-Samplerfläche hat exakt280 Dreiergruppen (840 Bytes) und +drei Extrabytes. Safe as_flattened_mut liefert eine geliehene Byteansicht ohne +neues Array oder Alignment-Cast; kein as_chunks-Aufruf mit erhöhtem MSRV. +EN: Root forbid(unsafe_code) stays intact. Necessary register/scalar/compiler/OS +limits from R6 remain explicit; this is not a formal or external soundness proof. + +DE: Öffentlich bekannte oder ausdrücklich exportierte Caller-Eingaben werden +nicht rückwirkend gesperrt. Quelleingänge, temporäre/native Pfade, Report-/Stream- +Zähler, Trailer-/Nachrichten-Framing, Ausgabeformatierung und der gemeinsame Sperrregistry bleiben eigene +offene R8-Zeilen. Auch die Prozess-/GUI-Verträge aus R7 sind nicht hier erledigt. +EN: Do not count this provider component as whole M4/R8 completion while dependent +retained metadata or platform acceptance is still open. + +## Tests and compatibility / Tests und Kompatibilität + +DE: Frische OS-Seeds/-Coins in gesperrten Testownern; identische Coins an neuen +und ursprünglichen Referenzpfad: für alle drei ML-DSA-Parametersätze bytegleiche +Signaturkodierung bei leerer/großer Nachricht, leerem/255-Byte-Kontext und mehrfach +verwendeter Arbeitsfläche. Partielle RNG-Fehler verändern die Ausgabe nicht; +256-Byte-Kontext ruft den RNG nicht auf. Kein Secret-Festwert und keine Ausgabe +privater Inhalte oder Adressen in Logs. +EN: Protected verification is compared with original public verification for all +three parameter sets, valid signatures, changed bytes and invalid geometry/hints. +Actual complete workspace/matrix first/last addresses are checked under lock. +An owned bounded Linux child checks real unwind/lock-count restoration and actual +RLIMIT_MEMLOCK=0 refusal in both reached confidential signing/verification APIs; +parent policy remains unchanged. Original public R6 operation tests are retained. + +DE: Vorläufige lokale Prüfgruppen grün; vollständige aktuelle Ergebnisse liegen +separat mit Quellhashes unter analysis/issue-147-r7-r8-20261127T182246Z. +Strenges direktes Provider-Clippy und Root-Clippy, beide Feature-Sätze, vorhandene +öffentliche/verborgene Roundtrips, MSRV, native Linux/Windows/ARM64, acht Fuzz- +Ziele und gemeinsame finale Audit-/Rückwegabnahme müssen auf dem finalen Head +bestanden sein. Frühere Checkpoints sind kein Nachweis später geänderter Quellen. +EN: CLI/JSON/file bytes stay unchanged. Existing subtle2.6.1 becomes a core dependency +for confidential identity equality, with unchanged version and lockfile; no new +package or system installation. The api feature keeps its external meaning. + +DE: Lokaler Quellenstand nach Konstruktor-/Testlog-Korrektur: vollständiger +Hashvergleich von721 Rust-/Manifest-/Buildquellen vor/nach allen drei v5-Kommandos +identisch. Strenges API-All-targets-Clippy, zehn DSA-Prüfgruppen (drei explizit +aufgerufene Kindeinstiege) und61 Dateimodul-Prüfgruppen grün. Davor v3: alle sechs +Kommandos grün einschließlich strengem direkt erfasstem Provider-Clippy mit +tatsächlich aktivierten alloc/protected-workspace/rand_core/zeroize, beiden +Root-Featurekonfigurationen und sämtlichen13 bestehenden Absender-Integrationstests. +EN: Logs retain all failed compile/lint checkpoints. No production lint suppression, +parameter reduction, fake skip or changed expected result. Boolean witnesses keep +private signatures and addresses out of assertion failure messages. Native final +acceptance and the dependent framing/report/registry rows remain open. diff --git a/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md new file mode 100644 index 0000000..44e211a --- /dev/null +++ b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md @@ -0,0 +1,69 @@ +# Restricted CI inspector / Reduzierter CI-Inspector + +DE: Konkreter Folgeversuch zu P2 des freigegebenen gemeinsamen R7/R8-Plans. +Noch nicht zur Ausführung freigegeben. Bisherige Freigabe galt nur der eigenen +Prozess-DACL und Zugriffsprobe, ausdrücklich ohne Token-/Threadänderungen. +EN: Locally developed and cross-checked only until additional concrete approval. + +## Observed failure / Beobachteter Fehler + +DE: Native Windows-2025-Probe bestätigt die zurückgelesene Ziel-DACL. Inspector +erhält trotzdem PROCESS_VM_READ (0x10). Gesonderte ausschließlich lesende Abfrage +des eigenen Tokens bestätigt debug_privilege_enabled=true am Headac02078. +Das ist die dokumentierte SeDebugPrivilege-Ausnahme; keine fehlgeschlagene +Verweigerungsprüfung als erfolgreich umbewerten. R7 bleibt offen. +EN: Microsoft explicitly documents that enabled SeDebugPrivilege bypasses the +process security descriptor. Administrative access is outside this DACL guarantee. + +## Exact additional action / Zusätzliche konkrete Aktion + +DE: Nur im bereits eigenen kurzlebigen Inspector-Hauptthread: + +1. Vorhandene Thread-Impersonation ausschließen (OpenThreadToken, nur QUERY). +2. Eigenes Primärtoken ausschließlich mit QUERY|DUPLICATE öffnen. DuplicateTokenEx + erstellt ein getrenntes nicht vererbbares Token, Typ TokenImpersonation, + Level SecurityImpersonation, Rechte QUERY|ADJUST_PRIVILEGES|IMPERSONATE. +3. AdjustTokenPrivileges(DISABLE_ALL=TRUE) ausschließlich auf dem neuen Duplikat. + Readback muss bestätigen: kein Privileg aktiviert. Kein Privileg hinzufügen. +4. SetThreadToken(NULL, Duplikat) betrifft ausschließlich den aktuellen eigenen + Testthread. Tatsächliches Threadtoken erneut öffnen/auslesen; keine aktivierten + Privilegien zulassen. Keine Veränderung des ursprünglichen Primärtokens. +5. Dieselben sieben sensiblen OpenProcess-Rechte müssen AccessDenied liefern; + QueryLimited/Synchronize müssen weiterhin funktionieren. Zustand des ursprünglichen + Primärtokens vor/nachher muss gleich sein. Kein Skip/abgeschwächter Rechteumfang. + +EN: Before reduction, if actual debug privilege is enabled, open and immediately +close one VM_READ control handle to the same owned target without reading memory. +No privileged control handle survives into the restricted access checks. The +original privileged bypass remains explicit evidence, never a DACL success claim. + +DE: Der Inspector stellt keine Privilegien wieder her: Der reduzierte Thread +beendet sich danach. Tokenhandles schließen; OS-Thread-/Prozessende beseitigt +die Impersonation. Parent, Target-Primärtoken und sämtliche übrigen Prozesse, +Konten, Registry-/Datei-/Dienst-/Hostrechte bleiben unangetastet. Kein sudo, +keine Installation, keine Aktivierung zusätzlicher Rechte oder neue Benutzer. +EN: A controlled test subject, not an irreversible sandbox or protection against +administrators. No production helper/CLI policy is installed by this experiment. + +## Files, bounded lifecycle and return / Dateien, Grenzen und Rückweg + +DE: Beispiele process_access_probe.rs und process_access_probe/{privileges, +restricted}.rs sowie eine konkrete Änderung des vorhandenen PowerShell-Harness: +Argument inspect-restricted statt inspect; feste öffentliche Kontroll-/Readback- +Diagnose auch bei Erfolg festhalten. Geplanter Harness liegt vor Freigabe nur +in der geschützten Analyseablage; bestehender Workflow führt ihn noch nicht aus. +EN: Same two owned children, same own Process/PID tracking, same bounded10-second +startup/inspection/exit and kill/wait cleanup; no unknown processes or shared endpoint. + +DE: Risiko ausschließlich falscher Testkontext oder Testfehler im eigenen Kind; +beide führen zu Fehler statt Erfolg. Prüffehler beenden ausschließlich eigene +Kinder. Prozessende ist der technische Rückweg, keine Host-Policy zurückzusetzen. +Vollständiges aktuelles Bundle und kompletter lokaler Quellenstand einschließlich +geplantem Harness werden mit Bytes/Modi und Lesbarkeit geprüft gesichert. +EN: Local branches, worktrees, source/evidence backups remain retained. No deletion. + +Sources / Quellen: +- https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess +- https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-duplicatetokenex +- https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges +- https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadtoken diff --git a/src/crypto/dsa.rs b/src/crypto/dsa.rs index b781790..ad2ed66 100644 --- a/src/crypto/dsa.rs +++ b/src/crypto/dsa.rs @@ -19,6 +19,15 @@ use crate::{Error, Result}; #[path = "dsa_key_state.rs"] mod key_state; +#[path = "dsa_confidential_key.rs"] +mod confidential_key; +#[path = "dsa_confidential_sign.rs"] +mod confidential_sign; +pub(crate) use confidential_sign::sign as sign_confidential; +#[path = "dsa_confidential_verify.rs"] +mod confidential_verify; +pub(crate) use confidential_verify::verify as verify_confidential; + /// DE: Länge des Seeds ξ in Bytes. EN: Length of the seed ξ in bytes. pub const SEED_LEN: usize = 32; diff --git a/src/crypto/dsa_confidential_denial_tests.rs b/src/crypto/dsa_confidential_denial_tests.rs new file mode 100644 index 0000000..17f3459 --- /dev/null +++ b/src/crypto/dsa_confidential_denial_tests.rs @@ -0,0 +1,68 @@ +//! DE: Verborgene Signaturpfade mit echtem Unwind und Sperrverweigerung. +//! EN: Hidden signature paths under actual unwind and memory-lock denial. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::{crypto::SecretBytes, hardening::memlock}; +use rustix::process::{Resource, getrlimit, setrlimit}; + +#[test] +fn confidential_workspace_denial_and_unwind_run_in_an_owned_child() { + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "crypto::dsa::confidential_verify::denial_tests::confidential_workspace_child", + "PQKEEP_CONFIDENTIAL_DSA_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn confidential_workspace_child() { + assert_eq!(std::env::var("PQKEEP_CONFIDENTIAL_DSA_CHILD").unwrap(), "1"); + let algorithm = DsaAlgorithm::MlDsa44; + let key = super::super::generate(algorithm).unwrap(); + let public = SecretBytes::from_slice(&key.public_key).unwrap(); + let signature = + super::super::sign_confidential(algorithm, key.seed().expose(), b"message", b"ctx") + .unwrap(); + let baseline = memlock::stats().locked_pages; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut state = State::::new().unwrap(); + let pk: &EncodedVerifyingKey = public.expose().try_into().unwrap(); + let sig: &EncodedSignature = signature.expose().try_into().unwrap(); + assert!( + state + .work + .get_mut() + .verify_encoded(pk, b"message", b"ctx", sig) + ); + assert!(state.work.get().visit_private_storage(|addr, len| { + memlock::is_locked(addr) && memlock::is_locked(addr + len - 1) + })); + std::panic::resume_unwind(Box::new(())); + })); + assert!(result.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + let failure_count = memlock::stats().failed_attempts; + assert!(matches!( + verify( + algorithm, + public.expose(), + b"message", + b"ctx", + signature.expose() + ), + Err(Error::MemoryLock) + )); + assert!(matches!( + super::super::sign_confidential(algorithm, key.seed().expose(), b"message", b"ctx"), + Err(Error::MemoryLock) + )); + assert!(memlock::stats().failed_attempts >= failure_count + 2); + assert_eq!(memlock::stats().locked_pages, baseline); +} diff --git a/src/crypto/dsa_confidential_key.rs b/src/crypto/dsa_confidential_key.rs new file mode 100644 index 0000000..dc88eba --- /dev/null +++ b/src/crypto/dsa_confidential_key.rs @@ -0,0 +1,60 @@ +//! DE: Verborgenen Signierschlüssel samt Identitätsmatrix vor Befüllung sperren. +//! EN: Prelock hidden signing key including its identity-derived matrix. + +use crate::{ + Error, Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, + hardening::memlock::LockedRange, +}; +use ml_dsa::{ConfidentialKeyGenerationWorkspace, ExpandedSigningKey, MlDsaParams, Seed}; +use zeroize::Zeroize; + +pub(super) struct KeyState { + key: SecretState>, + rows: SecretWorkspace, +} + +impl KeyState

{ + pub(super) fn new(seed: &Seed) -> Result { + let mut out = Self::prepare()?; + let mut work = SecretState::new(ConfidentialKeyGenerationWorkspace::

::default())?; + out.key + .get_mut() + .initialize_confidential_seed(seed, work.get_mut()) + .map_err(|_| Error::Crypto)?; + Ok(out) + } + + pub(super) fn prepare() -> Result { + let key = SecretState::new(ExpandedSigningKey::

::public_confidential_state())?; + let expected = key.get().confidential_storage_count(); + let mut out = Self { + key, + rows: SecretWorkspace::zeroed(expected)?, + }; + let mut count = 0; + let complete = out.key.get().visit_confidential_storage(|addr, len| { + let Some(slot) = out.rows.expose_mut().get_mut(count) else { + return false; + }; + count += 1; + len > 0 && slot.acquire(addr, len) + }); + if !complete || count != expected { + return Err(Error::MemoryLock); + } + Ok(out) + } + + pub(super) fn get(&self) -> &ExpandedSigningKey

{ + self.key.get() + } +} + +impl Drop for KeyState

{ + fn drop(&mut self) { + // DE/EN: Auch Identitätsmatrix vor Guardfreigabe löschen / wipe identity matrix before unlocking. + self.key.get_mut().zeroize_confidential(); + self.rows.zeroize(); + } +} diff --git a/src/crypto/dsa_confidential_sign.rs b/src/crypto/dsa_confidential_sign.rs new file mode 100644 index 0000000..f066a82 --- /dev/null +++ b/src/crypto/dsa_confidential_sign.rs @@ -0,0 +1,51 @@ +//! DE: Verborgene Signaturen ohne gewöhnlichen Signature-/Ausgabe-Owner. +//! EN: Hidden signatures without ordinary Signature/output ownership. + +use super::{MAX_CONTEXT_LEN, confidential_key::KeyState}; +use crate::{ + Error, Result, + crypto::{DsaAlgorithm, SecretBytes, secret_state::SecretState}, +}; +use getrandom::SysRng; +use ml_dsa::{EncodedSignature, MlDsa44, MlDsa65, MlDsa87, MlDsaParams, SigningWorkspace}; +use zeroize::Zeroize; + +pub(crate) fn sign( + algorithm: DsaAlgorithm, + seed: &[u8], + message: &[u8], + context: &[u8], +) -> Result { + if context.len() > MAX_CONTEXT_LEN { + return Err(Error::InvalidInput { field: "context" }); + } + match algorithm { + DsaAlgorithm::MlDsa44 => sign_with::(seed, message, context), + DsaAlgorithm::MlDsa65 => sign_with::(seed, message, context), + DsaAlgorithm::MlDsa87 => sign_with::(seed, message, context), + } +} + +fn sign_with(seed: &[u8], message: &[u8], context: &[u8]) -> Result { + let mut out = SecretBytes::zeroed(size_of::>())?; + let mut work = SecretState::new(SigningWorkspace::

::default())?; + let mut seed = crate::crypto::seed_state::parse(seed, super::SEED_LEN)?; + let key = KeyState::

::new(crate::crypto::seed_state::view(&seed)?)?; + seed.zeroize(); + let encoded: &mut EncodedSignature

= + out.expose_mut().try_into().map_err(|_| Error::Crypto)?; + key.get() + .sign_randomized_encoded_with_workspace( + message, + context, + &mut SysRng, + work.get_mut(), + encoded, + ) + .map_err(|_| Error::Crypto)?; + Ok(out) +} + +#[cfg(test)] +#[path = "dsa_confidential_sign_tests.rs"] +mod tests; diff --git a/src/crypto/dsa_confidential_sign_tests.rs b/src/crypto/dsa_confidential_sign_tests.rs new file mode 100644 index 0000000..645b76a --- /dev/null +++ b/src/crypto/dsa_confidential_sign_tests.rs @@ -0,0 +1,204 @@ +//! DE: Vertrauliche Kodierung gegen ursprüngliches Signieren und echte Fehler prüfen. +//! EN: Compare confidential encoding with original signing and actual failures. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::{ + crypto::{rng, seed_state}, + hardening::memlock, + locked_owner_test_support::locked, +}; +use ml_dsa::signature::Keypair; +use ml_dsa::signature::rand_core::{TryCryptoRng, TryRng}; +use std::{cell::Cell, io}; + +struct Replay<'a> { + bytes: &'a SecretBytes, + require_locked: bool, + fail: bool, + calls: &'a Cell, +} + +impl TryRng for Replay<'_> { + type Error = io::Error; + fn try_next_u32(&mut self) -> io::Result { + Err(io::Error::other("unused")) + } + fn try_next_u64(&mut self) -> io::Result { + Err(io::Error::other("unused")) + } + fn try_fill_bytes(&mut self, out: &mut [u8]) -> io::Result<()> { + self.calls.set(self.calls.get() + 1); + if self.require_locked { + assert!(memlock::is_locked(out.as_ptr().addr())); + assert!(memlock::is_locked(out.as_ptr().addr() + out.len() - 1)); + } + if self.fail { + let half = out.len() / 2; + out[..half].copy_from_slice(&self.bytes.expose()[..half]); + return Err(io::Error::other("partial RNG failure")); + } + out.copy_from_slice(self.bytes.expose()); + Ok(()) + } +} +impl TryCryptoRng for Replay<'_> {} + +fn compare() { + let empty = KeyState::

::prepare().unwrap(); + assert_hidden_key_locked(empty.get()); + drop(empty); + let seed = rng::secret(super::super::SEED_LEN).unwrap(); + let key = KeyState::

::new(seed_state::view(&seed).unwrap()).unwrap(); + let key_rows = assert_hidden_key_locked(key.get()); + let legacy = ml_dsa::SigningKey::

::from_seed(seed_state::view(&seed).unwrap()); + let mut work = SecretState::new(SigningWorkspace::

::default()).unwrap(); + let mut out = SecretBytes::zeroed(size_of::>()).unwrap(); + out.assert_metadata_locked(); + locked(out.expose()); + let address = out.expose().as_ptr(); + for (length, context_len) in [(0, 0), (193, 255), (65_537, 17)] { + let message = rng::secret(length).unwrap(); + let context = rng::secret(context_len).unwrap(); + let random = rng::secret(32).unwrap(); + let calls = Cell::new(0); + let mut replay = Replay { + bytes: &random, + require_locked: true, + fail: false, + calls: &calls, + }; + let encoded: &mut EncodedSignature

= out.expose_mut().try_into().unwrap(); + key.get() + .sign_randomized_encoded_with_workspace( + message.expose(), + context.expose(), + &mut replay, + work.get_mut(), + encoded, + ) + .unwrap(); + assert_eq!(calls.get(), 1); + locked(work.get()); + out.assert_metadata_locked(); + assert!(std::ptr::eq(address, out.expose().as_ptr())); + compare_original(&legacy, &message, &context, &random, &out); + let owners_unchanged = assert_hidden_key_locked(key.get()) == key_rows; + assert!(owners_unchanged); + } +} + +fn assert_hidden_key_locked( + key: &ml_dsa::ExpandedSigningKey

, +) -> Vec<(usize, usize)> { + locked(key); + let mut rows = Vec::new(); + assert!(key.visit_confidential_storage(|address, len| { + assert!(memlock::is_locked(address)); + assert!(memlock::is_locked(address + len - 1)); + #[cfg(target_os = "linux")] + assert!(crate::locked_owner_test_support::own_mapping_locked( + address + )); + rows.push((address, len)); + true + })); + assert_eq!(rows.len(), key.confidential_storage_count()); + rows +} + +fn compare_original( + legacy: &ml_dsa::SigningKey

, + message: &SecretBytes, + context: &SecretBytes, + random: &SecretBytes, + out: &SecretBytes, +) { + // DE: Bewusster öffentlicher Referenzpfad ausschließlich im Test. + // EN: Intentional public reference path in the test only. + let calls = Cell::new(0); + let expected = legacy + .expanded_key() + .sign_randomized( + message.expose(), + context.expose(), + &mut Replay { + bytes: random, + require_locked: false, + fail: false, + calls: &calls, + }, + ) + .unwrap(); + let equal = out.expose() == expected.encode().as_slice(); + assert!(equal); + assert!(legacy.verifying_key().verify_with_context( + message.expose(), + context.expose(), + &expected + )); +} + +#[test] +fn confidential_encoding_matches_original_for_every_parameter_set_and_reused_workspace() { + compare::(); + compare::(); + compare::(); +} + +#[test] +fn randomized_dispatch_returns_locked_signatures_accepted_by_existing_verifier() { + for algorithm in [ + DsaAlgorithm::MlDsa44, + DsaAlgorithm::MlDsa65, + DsaAlgorithm::MlDsa87, + ] { + let key = super::super::generate(algorithm).unwrap(); + let signature = sign(algorithm, key.seed().expose(), b"test message", b"context").unwrap(); + signature.assert_metadata_locked(); + assert!(super::super::verify( + algorithm, + &key.public_key, + b"test message", + b"context", + signature.expose() + )); + assert!(!super::super::verify( + algorithm, + &key.public_key, + b"changed", + b"context", + signature.expose() + )); + } +} + +#[test] +fn partial_rng_failure_keeps_output_unchanged_and_long_context_never_calls_rng() { + let seed = rng::secret(super::super::SEED_LEN).unwrap(); + let key = KeyState::::new(seed_state::view(&seed).unwrap()).unwrap(); + let mut work = SecretState::new(SigningWorkspace::::default()).unwrap(); + let mut out = SecretBytes::zeroed(size_of::>()).unwrap(); + out.expose_mut().fill(0x5a); + let random = rng::secret(32).unwrap(); + for (context, expected_calls) in [(b"context".as_slice(), 1), (&[0; 256][..], 0)] { + let calls = Cell::new(0); + let encoded: &mut EncodedSignature = out.expose_mut().try_into().unwrap(); + let result = key.get().sign_randomized_encoded_with_workspace( + b"message", + context, + &mut Replay { + bytes: &random, + require_locked: true, + fail: true, + calls: &calls, + }, + work.get_mut(), + encoded, + ); + assert!(result.is_err()); + assert_eq!(calls.get(), expected_calls); + assert!(out.expose().iter().all(|byte| *byte == 0x5a)); + locked(work.get()); + } +} diff --git a/src/crypto/dsa_confidential_verify.rs b/src/crypto/dsa_confidential_verify.rs new file mode 100644 index 0000000..6e194a1 --- /dev/null +++ b/src/crypto/dsa_confidential_verify.rs @@ -0,0 +1,94 @@ +//! DE: Auch verborgene Verifikationsschlüssel/-signaturen vor Dekodierung schützen. +//! EN: Protect hidden verification keys/signatures before decoding as well. + +use crate::{ + Error, Result, + crypto::{DsaAlgorithm, secret_state::SecretState, secret_workspace::SecretWorkspace}, + hardening::memlock::LockedRange, +}; +use ml_dsa::{ + ConfidentialVerificationWorkspace, EncodedSignature, EncodedVerifyingKey, MlDsa44, MlDsa65, + MlDsa87, MlDsaParams, +}; +use zeroize::Zeroize; + +struct State { + work: SecretState>, + rows: SecretWorkspace, +} + +impl State

{ + fn new() -> Result { + let work = SecretState::new(ConfidentialVerificationWorkspace::

::default())?; + let expected = work.get().private_storage_count(); + let mut out = Self { + work, + rows: SecretWorkspace::zeroed(expected)?, + }; + let mut count = 0; + let complete = out.work.get().visit_private_storage(|addr, len| { + let Some(slot) = out.rows.expose_mut().get_mut(count) else { + return false; + }; + count += 1; + len > 0 && slot.acquire(addr, len) + }); + if !complete || count != expected { + return Err(Error::MemoryLock); + } + Ok(out) + } +} + +impl Drop for State

{ + fn drop(&mut self) { + // DE: Alle verschachtelten Zeilen unter ihrer Sperre löschen. + // EN: Wipe every nested row while its lock is still held. + self.work.get_mut().zeroize(); + self.rows.zeroize(); + } +} + +pub(crate) fn verify( + algorithm: DsaAlgorithm, + key: &[u8], + message: &[u8], + context: &[u8], + signature: &[u8], +) -> Result { + if context.len() > super::MAX_CONTEXT_LEN { + return Ok(false); + } + match algorithm { + DsaAlgorithm::MlDsa44 => verify_with::(key, message, context, signature), + DsaAlgorithm::MlDsa65 => verify_with::(key, message, context, signature), + DsaAlgorithm::MlDsa87 => verify_with::(key, message, context, signature), + } +} + +fn verify_with( + key: &[u8], + message: &[u8], + context: &[u8], + signature: &[u8], +) -> Result { + let (Ok(key), Ok(signature)) = ( + <&EncodedVerifyingKey

>::try_from(key), + <&EncodedSignature

>::try_from(signature), + ) else { + return Ok(false); + }; + let mut state = State::

::new()?; + Ok(state + .work + .get_mut() + .verify_encoded(key, message, context, signature)) +} + +#[cfg(test)] +#[path = "dsa_confidential_verify_tests.rs"] +mod tests; + +#[cfg(all(test, target_os = "linux"))] +#[path = "dsa_confidential_denial_tests.rs"] +mod denial_tests; diff --git a/src/crypto/dsa_confidential_verify_tests.rs b/src/crypto/dsa_confidential_verify_tests.rs new file mode 100644 index 0000000..5c49322 --- /dev/null +++ b/src/crypto/dsa_confidential_verify_tests.rs @@ -0,0 +1,177 @@ +//! DE: Echte verborgene Verifikationspfade gegen ursprüngliche öffentliche Arithmetik. +//! EN: Compare actual hidden verification paths with original public arithmetic. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::{ + crypto::{SecretBytes, rng}, + locked_owner_test_support::locked, +}; + +fn check_storage(state: &State

) -> Vec<(usize, usize)> { + locked(state.work.get()); + let mut rows = Vec::new(); + assert!(state.work.get().visit_private_storage(|address, len| { + assert!(crate::hardening::memlock::is_locked(address)); + assert!(crate::hardening::memlock::is_locked(address + len - 1)); + #[cfg(target_os = "linux")] + assert!(crate::locked_owner_test_support::own_mapping_locked( + address + )); + rows.push((address, len)); + true + })); + assert_eq!(rows.len(), state.work.get().private_storage_count()); + rows +} + +fn compare(algorithm: DsaAlgorithm) { + let key = super::super::generate(algorithm).unwrap(); + let public = SecretBytes::from_slice(&key.public_key).unwrap(); + let mut state = State::

::new().unwrap(); + let rows = check_storage(&state); + for (message_len, context_len) in [(0, 0), (193, 255), (65_537, 17)] { + let message = rng::secret(message_len).unwrap(); + let context = rng::secret(context_len).unwrap(); + let signature = super::super::sign_confidential( + algorithm, + key.seed().expose(), + message.expose(), + context.expose(), + ) + .unwrap(); + let pk: &EncodedVerifyingKey

= public.expose().try_into().unwrap(); + let sig: &EncodedSignature

= signature.expose().try_into().unwrap(); + let valid = + state + .work + .get_mut() + .verify_encoded(pk, message.expose(), context.expose(), sig); + assert!(valid); + let actual = verify( + algorithm, + public.expose(), + message.expose(), + context.expose(), + signature.expose(), + ) + .unwrap(); + assert!(actual); + let owners_unchanged = check_storage(&state) == rows; + assert!(owners_unchanged); + compare_tampering(algorithm, &public, &message, &context, &signature); + state.work.get_mut().zeroize(); + let owners_unchanged = check_storage(&state) == rows; + assert!(owners_unchanged); + let valid = + state + .work + .get_mut() + .verify_encoded(pk, message.expose(), context.expose(), sig); + assert!(valid); + } + assert_eq!( + format!("{:?}", state.work.get()), + "ConfidentialVerificationWorkspace { .. }" + ); +} + +fn compare_tampering( + algorithm: DsaAlgorithm, + key: &SecretBytes, + message: &SecretBytes, + context: &SecretBytes, + signature: &SecretBytes, +) { + // DE: Öffentliche Referenz ausschließlich für diese Test-Gegenprobe. + // EN: Public reference used only for this test comparison. + assert!(super::super::verify( + algorithm, + key.expose(), + message.expose(), + context.expose(), + signature.expose() + )); + let mut changed = SecretBytes::from_slice(signature.expose()).unwrap(); + for index in [0, 1, 32, changed.len() / 2, changed.len() - 1] { + changed.expose_mut()[index] ^= 1; + let expected = super::super::verify( + algorithm, + key.expose(), + message.expose(), + context.expose(), + changed.expose(), + ); + let actual = verify( + algorithm, + key.expose(), + message.expose(), + context.expose(), + changed.expose(), + ) + .unwrap(); + assert!(!expected); + assert_eq!(actual, expected); + changed.expose_mut()[index] ^= 1; + } + malformed_inputs(algorithm, key, message, context, signature, &mut changed); +} + +fn malformed_inputs( + algorithm: DsaAlgorithm, + key: &SecretBytes, + message: &SecretBytes, + context: &SecretBytes, + signature: &SecretBytes, + changed: &mut SecretBytes, +) { + let last = changed.len() - 1; + changed.expose_mut()[last] = 255; + assert!( + !verify( + algorithm, + key.expose(), + message.expose(), + context.expose(), + changed.expose() + ) + .unwrap() + ); + assert!( + !verify( + algorithm, + &key.expose()[..key.len() - 1], + message.expose(), + context.expose(), + signature.expose() + ) + .unwrap() + ); + assert!( + !verify( + algorithm, + key.expose(), + message.expose(), + context.expose(), + &signature.expose()[..signature.len() - 1] + ) + .unwrap() + ); + assert!( + !verify( + algorithm, + key.expose(), + message.expose(), + &[0; 256], + signature.expose() + ) + .unwrap() + ); +} + +#[test] +fn hidden_verification_matches_original_for_all_parameter_sets_and_tampering() { + compare::(DsaAlgorithm::MlDsa44); + compare::(DsaAlgorithm::MlDsa65); + compare::(DsaAlgorithm::MlDsa87); +} diff --git a/src/files/hidden_result_tests.rs b/src/files/hidden_result_tests.rs index b6eefa8..572d55e 100644 --- a/src/files/hidden_result_tests.rs +++ b/src/files/hidden_result_tests.rs @@ -14,7 +14,7 @@ fn shared_slot_stays_locked_before_and_after_identity_population() { assert!(result.take().is_none()); result.store(SignedBy::from_public_key(b"public first identity").unwrap()); locked(other.0.get()); - assert_eq!(std::ptr::from_ref(other.0.get()), address); + assert!(std::ptr::eq(std::ptr::from_ref(other.0.get()), address)); other.store(SignedBy::from_public_key(b"public replacement identity").unwrap()); drop(result); let signed = other.take().unwrap(); diff --git a/src/files/signed_by.rs b/src/files/signed_by.rs index 9f18d95..9ac155f 100644 --- a/src/files/signed_by.rs +++ b/src/files/signed_by.rs @@ -1,10 +1,11 @@ //! DE: Geprüfte Identität ohne ungesperrte Hash-/Descriptor-Kopie. //! EN: Verified identity without an unlocked hash or descriptor copy. -use crate::Result; use crate::crypto::{SecretBytes, locked_hash::LockedHash, secret_state::SecretState}; +use crate::{Error, Result}; use sha3::Sha3_256; use std::fmt; +use subtle::ConstantTimeEq; /// DE: Geprüfter Absender; Identität nur ausdrücklich ausleihen. /// EN: Verified sender; borrow identity only by explicit disclosure. @@ -20,6 +21,9 @@ impl SignedBy { } pub(super) fn from_key_id(id: &[u8]) -> Result { + if id.len() != 32 { + return Err(Error::InvalidInput { field: "key_id" }); + } let mut out = Self::prepare()?; *out.0.get_mut() = SecretBytes::from_slice(id)?; Ok(out) @@ -47,7 +51,7 @@ impl SignedBy { impl PartialEq for SignedBy { fn eq(&self, other: &Self) -> bool { - self.key_id() == other.key_id() + bool::from(self.key_id().ct_eq(other.key_id())) } } impl Eq for SignedBy {} diff --git a/src/files/signed_by_tests.rs b/src/files/signed_by_tests.rs index e39827d..ead1cef 100644 --- a/src/files/signed_by_tests.rs +++ b/src/files/signed_by_tests.rs @@ -11,7 +11,8 @@ fn identity_hash_matches_public_reference_and_all_owners_are_locked() { let key = b"public synthetic sender identity"; let signed = SignedBy::from_public_key(key).unwrap(); let expected = Sha3_256::digest(key); - assert_eq!(signed.key_id(), expected.as_slice()); + let matches_reference = signed.key_id() == expected.as_slice(); + assert!(matches_reference); locked(signed.0.get()); signed.0.get().assert_metadata_locked(); assert!(crate::hardening::memlock::is_locked( @@ -28,12 +29,29 @@ fn duplication_keeps_source_and_locks_an_independent_destination() { let signed = SignedBy::from_public_key(b"public reference").unwrap(); let duplicate = signed.try_duplicate().unwrap(); assert_eq!(signed, duplicate); - assert_ne!(signed.key_id().as_ptr(), duplicate.key_id().as_ptr()); + assert!(!std::ptr::eq( + signed.key_id().as_ptr(), + duplicate.key_id().as_ptr() + )); locked(duplicate.0.get()); duplicate.0.get().assert_metadata_locked(); drop(signed); - assert_eq!( - duplicate.key_id(), - Sha3_256::digest(b"public reference").as_slice() - ); + let matches_reference = duplicate.key_id() == Sha3_256::digest(b"public reference").as_slice(); + assert!(matches_reference); +} + +#[test] +fn identity_comparison_checks_every_byte_and_refuses_noncanonical_lengths() { + let signed = SignedBy::from_key_id(&[0x5a; 32]).unwrap(); + for index in 0..32 { + let mut changed = [0x5a; 32]; + changed[index] ^= 1; + assert_ne!(signed, SignedBy::from_key_id(&changed).unwrap()); + } + for len in [0, 1, 31, 33, 64] { + assert!(matches!( + SignedBy::from_key_id(&vec![0; len]), + Err(Error::InvalidInput { field: "key_id" }) + )); + } } diff --git a/src/files/tail_v4.rs b/src/files/tail_v4.rs index 779bbfc..7d3249c 100644 --- a/src/files/tail_v4.rs +++ b/src/files/tail_v4.rs @@ -56,25 +56,25 @@ pub(crate) fn push_tail(enc: &mut EncryptWriter, tail: &TailWrite<' if let Some((key, header)) = tail.hidden { let hash = enc.take_hash().ok_or(Error::Crypto)?.finalize()?; let msg = hidden_message(header, hash.expose(), payload, pad)?; - let sig = dsa::sign( + let sig = dsa::sign_confidential( SIGNER_DSA, key.secret().expose(), msg.expose(), FILE_SIG_CONTEXT, )?; // DE: Gegenprobe wie bei v3. EN: Cross-check as in v3. - if !dsa::verify( + if !dsa::verify_confidential( SIGNER_DSA, &key.public_key, msg.expose(), FILE_SIG_CONTEXT, - &sig, - ) { + sig.expose(), + )? { return Err(Error::Crypto); } enc.push(&[SIGNER_ML_DSA_87])?; enc.push(&key.public_key)?; - enc.push(&sig)?; + enc.push(sig.expose())?; } enc.push(&trailer(payload, pad)) } @@ -166,7 +166,7 @@ fn hidden_sender( } let (key, sig) = block[1..].split_at(SIGNER_KEY_LEN); let msg = hidden_message(header, hash, payload, pad)?; - if !dsa::verify(SIGNER_DSA, key, msg.expose(), FILE_SIG_CONTEXT, sig) { + if !dsa::verify_confidential(SIGNER_DSA, key, msg.expose(), FILE_SIG_CONTEXT, sig)? { return Err(Error::InvalidSignature); } SignedBy::from_public_key(key) diff --git a/vendor/ml-dsa-0.1.2/src/algebra.rs b/vendor/ml-dsa-0.1.2/src/algebra.rs index 75dd053..25c1c85 100644 --- a/vendor/ml-dsa-0.1.2/src/algebra.rs +++ b/vendor/ml-dsa-0.1.2/src/algebra.rs @@ -22,6 +22,22 @@ pub(crate) type NttVector = module_lattice::NttVector; pub(crate) struct NttMatrix(Array>, K>); impl NttMatrix { + #[cfg(feature = "protected-workspace")] + pub(crate) fn row_count(&self) -> usize { + self.0.len() + } + #[cfg(feature = "protected-workspace")] + pub(crate) fn rows_mut(&mut self) -> impl Iterator> { + self.0.iter_mut().map(|row| &mut **row) + } + + #[cfg(feature = "protected-workspace")] + pub(crate) fn visit_rows(&self, mut visitor: impl FnMut(usize, usize) -> bool) -> bool { + self.0 + .iter() + .all(|row| visitor(core::ptr::from_ref(&**row).addr(), size_of_val(&**row))) + } + pub(crate) fn from_fn(mut f: impl FnMut(usize) -> NttVector) -> Self { Self(Array::from_fn(|i| MaybeBox::new(f(i)))) } @@ -45,6 +61,22 @@ impl NttMatrix { } } +#[cfg(feature = "protected-workspace")] +impl Default for NttMatrix { + fn default() -> Self { + Self::from_fn(|_| NttVector::default()) + } +} + +#[cfg(feature = "protected-workspace")] +impl zeroize::Zeroize for NttMatrix { + fn zeroize(&mut self) { + for row in &mut self.0 { + zeroize::Zeroize::zeroize(&mut **row); + } + } +} + impl Mul<&NttVector> for &NttMatrix { type Output = NttVector; diff --git a/vendor/ml-dsa-0.1.2/src/hint.rs b/vendor/ml-dsa-0.1.2/src/hint.rs index 45cbae6..53d18e1 100644 --- a/vendor/ml-dsa-0.1.2/src/hint.rs +++ b/vendor/ml-dsa-0.1.2/src/hint.rs @@ -22,7 +22,7 @@ pub(crate) fn make_hint(z: Elem, r: Elem) -> bool { /// All branches are replaced with constant-time selection to avoid /// leaking information about `r0` through branch timing. #[allow(clippy::integer_division_remainder_used, reason = "params are public")] -fn use_hint(h: bool, r: Elem) -> Elem { +pub(crate) fn use_hint(h: bool, r: Elem) -> Elem { let m: u32 = (BaseField::Q - 1) / TwoGamma2::U32; let (r1, r0) = r.decompose::(); let gamma2 = TwoGamma2::U32 / 2; diff --git a/vendor/ml-dsa-0.1.2/src/lib.rs b/vendor/ml-dsa-0.1.2/src/lib.rs index 8a01314..ac1b64a 100644 --- a/vendor/ml-dsa-0.1.2/src/lib.rs +++ b/vendor/ml-dsa-0.1.2/src/lib.rs @@ -58,11 +58,15 @@ mod sampling; mod signing; mod verifying; +#[cfg(all(feature = "protected-workspace", feature = "alloc"))] +pub use signing::confidential_key::ConfidentialKeyGenerationWorkspace; #[cfg(all(feature = "protected-workspace", feature = "alloc"))] pub use signing::in_place::{KeyGenerationWorkspace, SeedKeyInPlace}; #[cfg(all(feature = "protected-workspace", feature = "rand_core"))] pub use signing::workspace::SigningWorkspace; #[cfg(feature = "protected-workspace")] +pub use verifying::confidential::ConfidentialVerificationWorkspace; +#[cfg(feature = "protected-workspace")] pub use verifying::in_place::VerificationWorkspace; pub use crate::{ diff --git a/vendor/ml-dsa-0.1.2/src/param.rs b/vendor/ml-dsa-0.1.2/src/param.rs index 9375398..ba54162 100644 --- a/vendor/ml-dsa-0.1.2/src/param.rs +++ b/vendor/ml-dsa-0.1.2/src/param.rs @@ -285,7 +285,11 @@ pub trait VerifyingKeyParams: ParameterSet { type VerifyingKeySize: ArraySize; fn encode_t1(t1: &Vector) -> EncodedT1; + #[cfg(feature = "protected-workspace")] + fn encode_t1_into(t1: &Vector, out: &mut EncodedT1); fn decode_t1(enc: &EncodedT1) -> Vector; + #[cfg(feature = "protected-workspace")] + fn decode_t1_into(enc: &EncodedT1, out: &mut Vector); fn concat_vk(rho: B32, t1: EncodedT1) -> EncodedVerifyingKey; fn split_vk(enc: &EncodedVerifyingKey) -> (&B32, &EncodedT1); @@ -316,10 +320,36 @@ where Encode::::encode(t1) } + #[cfg(feature = "protected-workspace")] + fn encode_t1_into(t1: &Vector, out: &mut EncodedT1) { + let (parts, tail) = module_lattice::EncodedPolynomial::::slice_as_chunks_mut( + out.as_mut_slice(), + ); + assert!(tail.is_empty() && parts.len() == t1.0.len()); + for (part, poly) in parts.iter_mut().zip(t1.0.iter()) { + module_lattice::byte_encode_into::( + &poly.0, part, + ); + } + } + fn decode_t1(enc: &EncodedT1) -> Vector { Encode::::decode(enc) } + #[cfg(feature = "protected-workspace")] + fn decode_t1_into(enc: &EncodedT1, out: &mut Vector) { + let (parts, tail) = + module_lattice::EncodedPolynomial::::slice_as_chunks(enc.as_slice()); + assert!(tail.is_empty() && parts.len() == out.0.len()); + for (part, poly) in parts.iter().zip(out.0.iter_mut()) { + module_lattice::byte_decode_into::( + part, + &mut poly.0, + ); + } + } + fn concat_vk(rho: B32, t1: EncodedT1) -> EncodedVerifyingKey { rho.concat(t1) } @@ -349,7 +379,14 @@ pub trait SignatureParams: ParameterSet { fn decode_w1(enc: &EncodedW1) -> Vector; fn encode_z(z: &Vector) -> EncodedZ; + #[cfg(feature = "protected-workspace")] + fn encode_z_into( + z: &mut Vector, + out: &mut EncodedZ, + ) -> Result<(), module_lattice::InvalidEncodingGeometry>; fn decode_z(enc: &EncodedZ) -> Vector; + #[cfg(feature = "protected-workspace")] + fn decode_z_into(enc: &EncodedZ, out: &mut Vector); fn concat_sig( c_tilde: EncodedCTilde, @@ -443,10 +480,43 @@ where BitPack::, P::Gamma1>::pack(z) } + // DE: Dieselbe BitPack-Abbildung im bereits gesperrten Kandidaten ausführen. + // EN: Apply the same BitPack mapping in the already protected candidate. + #[cfg(feature = "protected-workspace")] + fn encode_z_into( + z: &mut Vector, + out: &mut EncodedZ, + ) -> Result<(), module_lattice::InvalidEncodingGeometry> { + let a = crate::algebra::Elem::new(P::Gamma1::U32 - 1); + let b = crate::algebra::Elem::new(P::Gamma1::U32); + for poly in &mut z.0 { + for value in &mut poly.0 { + if !(value.0 <= b.0 || value.0 >= (-a).0) { + return Err(module_lattice::InvalidEncodingGeometry); + } + *value = b - *value; + } + } + module_lattice::byte_encode_vector_into::< + crate::algebra::BaseField, + crate::encode::RangeEncodingBits, P::Gamma1>, + P::L, + >(z, out) + } + fn decode_z(enc: &EncodedZ) -> Vector { BitPack::, P::Gamma1>::unpack(enc) } + #[cfg(feature = "protected-workspace")] + fn decode_z_into(enc: &EncodedZ, out: &mut Vector) { + let (parts, tail) = crate::encode::RangeEncodedPolynomial::, P::Gamma1>::slice_as_chunks(enc.as_slice()); + assert!(tail.is_empty() && parts.len() == out.0.len()); + for (part, poly) in parts.iter().zip(out.0.iter_mut()) { + crate::encode::unpack_into::, P::Gamma1>(part, poly); + } + } + fn concat_sig( c_tilde: EncodedCTilde

, z: EncodedZ

, diff --git a/vendor/ml-dsa-0.1.2/src/sampling.rs b/vendor/ml-dsa-0.1.2/src/sampling.rs index 0c51997..c6b45b4 100644 --- a/vendor/ml-dsa-0.1.2/src/sampling.rs +++ b/vendor/ml-dsa-0.1.2/src/sampling.rs @@ -11,6 +11,8 @@ use zeroize::Zeroize; #[cfg(feature = "protected-workspace")] pub(crate) mod in_place; +#[cfg(feature = "protected-workspace")] +pub(crate) mod matrix_workspace; // Algorithm 13 BytesToBits fn bit_set(z: &[u8], i: usize) -> bool { @@ -21,6 +23,10 @@ fn bit_set(z: &[u8], i: usize) -> bool { // Algorithm 14 CoeffFromThreeBytes fn coeff_from_three_bytes(b: [u8; 3]) -> Option { + coeff_from_three_bytes_ref(&b) +} + +fn coeff_from_three_bytes_ref(b: &[u8; 3]) -> Option { let b0: Int = b[0].into(); let b1: Int = b[1].into(); let b2: Int = b[2].into(); diff --git a/vendor/ml-dsa-0.1.2/src/sampling/matrix_workspace.rs b/vendor/ml-dsa-0.1.2/src/sampling/matrix_workspace.rs new file mode 100644 index 0000000..c6ff515 --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/sampling/matrix_workspace.rs @@ -0,0 +1,87 @@ +//! DE: Ursprüngliches ExpandA mit vorab gesperrtem SHAKE128-/Sampler-Scratch. +//! EN: Original ExpandA with prelocked SHAKE128/sampling scratch. + +use super::coeff_from_three_bytes_ref; +use crate::algebra::{NttMatrix, NttPolynomial}; +use module_lattice::{ArraySize, Truncate}; +use shake::{ + Shake128, Shake128Reader, + digest::{Reset, Update, XofReader}, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +pub(crate) struct MatrixWorkspace { + hash: Shake128, + reader: Shake128Reader, + bytes: [[u8; 3]; 280], + extra: [u8; 3], +} + +impl Default for MatrixWorkspace { + fn default() -> Self { + Self { + hash: Default::default(), + reader: Default::default(), + bytes: [[0; 3]; 280], + extra: [0; 3], + } + } +} + +impl MatrixWorkspace { + pub(crate) fn expand( + &mut self, + rho: &[u8], + out: &mut NttMatrix, + ) { + for (r, row) in out.rows_mut().enumerate() { + for (s, poly) in row.0.iter_mut().enumerate() { + self.polynomial(rho, Truncate::truncate(r), Truncate::truncate(s), poly); + } + } + } + + fn polynomial(&mut self, rho: &[u8], r: u8, s: u8, out: &mut NttPolynomial) { + self.hash.reset(); + self.reader.zeroize(); + self.hash.update(rho); + self.hash.update(&[s]); + self.hash.update(&[r]); + self.hash.finalize_reader_into(&mut self.reader); + self.reader.read(self.bytes.as_flattened_mut()); + let mut index = 0; + for chunk in &self.bytes { + if let Some(value) = coeff_from_three_bytes_ref(chunk) { + out.0[index] = value; + index += 1; + if index == 256 { + break; + } + } + } + // DE: Originalen zusätzlichen Rejection-Pfad ohne Parameteränderung behalten. + // EN: Preserve original extra rejection path without parameter changes. + while index < 256 { + self.reader.read(&mut self.extra); + if let Some(value) = coeff_from_three_bytes_ref(&self.extra) { + out.0[index] = value; + index += 1; + } + } + } +} + +impl Zeroize for MatrixWorkspace { + fn zeroize(&mut self) { + self.hash.zeroize(); + self.reader.zeroize(); + self.bytes.zeroize(); + self.extra.zeroize(); + } +} +impl Drop for MatrixWorkspace { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for MatrixWorkspace {} diff --git a/vendor/ml-dsa-0.1.2/src/signing.rs b/vendor/ml-dsa-0.1.2/src/signing.rs index 13e8fa1..a0f6bdf 100644 --- a/vendor/ml-dsa-0.1.2/src/signing.rs +++ b/vendor/ml-dsa-0.1.2/src/signing.rs @@ -33,6 +33,10 @@ use zeroize::{Zeroize, ZeroizeOnDrop}; #[cfg(all(feature = "protected-workspace", feature = "rand_core"))] mod borrowed; +#[cfg(feature = "protected-workspace")] +mod confidential_encoding; +#[cfg(all(feature = "protected-workspace", feature = "alloc"))] +pub(crate) mod confidential_key; #[cfg(all(feature = "protected-workspace", feature = "alloc"))] pub(crate) mod in_place; mod steps; diff --git a/vendor/ml-dsa-0.1.2/src/signing/borrowed.rs b/vendor/ml-dsa-0.1.2/src/signing/borrowed.rs index 318c8eb..8c4b31d 100644 --- a/vendor/ml-dsa-0.1.2/src/signing/borrowed.rs +++ b/vendor/ml-dsa-0.1.2/src/signing/borrowed.rs @@ -46,6 +46,17 @@ impl ExpandedSigningKey

{ rng: &mut R, work: &mut SigningWorkspace

, ) -> Result, Error> { + self.accept_candidate(message, context, rng, work)?; + Ok(Self::accepted_signature(work)) + } + + pub(super) fn accept_candidate( + &self, + message: &[u8], + context: &[u8], + rng: &mut R, + work: &mut SigningWorkspace

, + ) -> Result<(), Error> { if context.len() > 255 { return Err(Error::new()); } @@ -69,19 +80,23 @@ impl ExpandedSigningKey

{ if work.ct0.infinity_norm() >= P::Gamma2::U32 || weight > P::Omega::USIZE { continue; } - return Ok(Self::accepted_signature(work)); + return Ok(()); } Err(Error::new()) } // DE: Ausschließlich nach beiden Akzeptanzprüfungen aufrufen. // EN: Call only after both acceptance checks. - fn accepted_signature(work: &mut SigningWorkspace

) -> Signature

{ + pub(super) fn canonicalize(work: &mut SigningWorkspace

) { for poly in &mut work.z.0 { for value in &mut poly.0 { *value = value.mod_plus_minus::(); } } + } + + fn accepted_signature(work: &mut SigningWorkspace

) -> Signature

{ + Self::canonicalize(work); Signature { c_tilde: work.challenge.clone(), z: MaybeBox::new(work.z.clone()), diff --git a/vendor/ml-dsa-0.1.2/src/signing/confidential_encoding.rs b/vendor/ml-dsa-0.1.2/src/signing/confidential_encoding.rs new file mode 100644 index 0000000..a12a875 --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/signing/confidential_encoding.rs @@ -0,0 +1,59 @@ +//! DE: Verborgene Signatur direkt in das vorab gesperrte Caller-Ziel kodieren. +//! EN: Encode hidden signatures directly into prelocked caller output. + +use super::{ExpandedSigningKey, workspace::SigningWorkspace}; +use crate::{EncodedSignature, MlDsaParams, param::EncodedZ}; +use hybrid_array::typenum::Unsigned; +use module_lattice::Truncate; +use signature::{Error, rand_core::TryCryptoRng}; + +impl ExpandedSigningKey

{ + /// DE: Caller muss work und out vor Aufruf vollständig sperren. + /// EN: Caller must fully lock work and out before calling. + /// # Errors + /// DE/EN: Wie sign_randomized_with_workspace; keine Ersatzkodierung. + /// Same failures as sign_randomized_with_workspace; no fallback encoding. + pub fn sign_randomized_encoded_with_workspace( + &self, + message: &[u8], + context: &[u8], + rng: &mut R, + work: &mut SigningWorkspace

, + out: &mut EncodedSignature

, + ) -> Result<(), Error> { + self.accept_candidate(message, context, rng, work)?; + // DE: Identische kanonische Koeffizienten wie accepted_signature. + // EN: Same canonical coefficients as accepted_signature. + Self::canonicalize(work); + let (challenge, rest) = out.as_mut_slice().split_at_mut(P::Lambda::USIZE); + let (z, hint) = rest.split_at_mut(P::ZSize::USIZE); + let z: &mut EncodedZ

= z.try_into().map_err(|_| Error::new())?; + challenge.copy_from_slice(&work.challenge); + P::encode_z_into(&mut work.z, z).map_err(|_| Error::new())?; + encode_hints(work, hint) + } +} + +fn encode_hints(work: &SigningWorkspace

, out: &mut [u8]) -> Result<(), Error> { + let omega = P::Omega::USIZE; + if out.len() != omega + P::K::USIZE { + return Err(Error::new()); + } + out.fill(0); + let mut index = 0; + // DE: Ursprüngliche Hint::bit_pack-Reihenfolge und Schnittkodierung beibehalten. + // EN: Preserve original Hint::bit_pack order and cut encoding. + for (i, hints) in work.hints.iter().enumerate() { + for (j, hint) in hints.iter().enumerate() { + if *hint { + if index == omega { + return Err(Error::new()); + } + out[index] = Truncate::truncate(j); + index += 1; + } + } + out[omega + i] = Truncate::truncate(index); + } + Ok(()) +} diff --git a/vendor/ml-dsa-0.1.2/src/signing/confidential_key.rs b/vendor/ml-dsa-0.1.2/src/signing/confidential_key.rs new file mode 100644 index 0000000..51b281e --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/signing/confidential_key.rs @@ -0,0 +1,43 @@ +//! DE: Auch Absender-Schlüsselaufbau ohne gewöhnliche öffentliche Cache-Kopien. +//! EN: Sender key construction without ordinary public-cache copies as well. + +use super::in_place::KeyGenerationWorkspace; +use crate::{EncodedVerifyingKey, MlDsaParams, sampling::matrix_workspace::MatrixWorkspace}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +/// DE: Gesamtes Objekt vor Seed-Eintritt sperren; kein öffentlicher Cache-Export. +/// EN: Lock the whole object before seed ingress; no public cache export. +pub struct ConfidentialKeyGenerationWorkspace { + pub(super) inner: KeyGenerationWorkspace

, + pub(super) matrix_sampling: MatrixWorkspace, + pub(super) encoded: EncodedVerifyingKey

, +} + +impl Default for ConfidentialKeyGenerationWorkspace

{ + fn default() -> Self { + Self { + inner: Default::default(), + matrix_sampling: Default::default(), + encoded: Default::default(), + } + } +} +impl Zeroize for ConfidentialKeyGenerationWorkspace

{ + fn zeroize(&mut self) { + self.inner.zeroize(); + self.matrix_sampling.zeroize(); + self.encoded.zeroize(); + } +} +impl Drop for ConfidentialKeyGenerationWorkspace

{ + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for ConfidentialKeyGenerationWorkspace

{} +impl core::fmt::Debug for ConfidentialKeyGenerationWorkspace

{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("ConfidentialKeyGenerationWorkspace") + .finish_non_exhaustive() + } +} diff --git a/vendor/ml-dsa-0.1.2/src/signing/in_place.rs b/vendor/ml-dsa-0.1.2/src/signing/in_place.rs index 57a49f8..06037de 100644 --- a/vendor/ml-dsa-0.1.2/src/signing/in_place.rs +++ b/vendor/ml-dsa-0.1.2/src/signing/in_place.rs @@ -148,6 +148,81 @@ impl SeedKeyInPlace for SigningKey

{ } } +impl ExpandedSigningKey

{ + /// DE: Nur öffentliche Defaults; Caller sperrt Objekt und alle Matrixzeilen. + /// EN: Public defaults only; caller prelocks object and every matrix row. + #[must_use] + pub fn public_confidential_state() -> Self { + Self { + rho: Default::default(), + K: Default::default(), + tr: Default::default(), + s1: Default::default(), + s2: Default::default(), + t0: Default::default(), + s1_hat: Default::default(), + s2_hat: Default::default(), + t0_hat: Default::default(), + A_hat: Default::default(), + } + } + + /// DE/EN: Öffentliche feste Zeilenanzahl / public fixed row count. + #[must_use] + pub fn confidential_storage_count(&self) -> usize { + self.A_hat.row_count() + } + + /// DE: Jede Zeile muss vor privater Konstruktion gesperrt sein. + /// EN: Every row must be locked before private construction. + pub fn visit_confidential_storage(&self, visitor: impl FnMut(usize, usize) -> bool) -> bool { + self.A_hat.visit_rows(visitor) + } + + /// DE: Einschließlich zuvor öffentlich klassifizierter Matrix vor Unlock löschen. + /// EN: Wipe the formerly public-classified matrix as well before unlocking. + pub fn zeroize_confidential(&mut self) { + self.A_hat.zeroize(); + self.zeroize(); + } + + /// DE: Objekt, Zeilen und Arbeitsfläche müssen vollständig gesperrt sein. + /// EN: Object, rows and workspace must all be fully locked. + /// # Errors + /// DE/EN: Ungültige öffentliche Zielgeometrie / invalid public output geometry. + pub fn initialize_confidential_seed( + &mut self, + seed: &Seed, + work: &mut super::confidential_key::ConfidentialKeyGenerationWorkspace

, + ) -> Result<(), signature::Error> { + work.inner.hash.start(&[seed, &[P::K::U8], &[P::L::U8]]); + work.inner.hash.read(&mut self.rho); + work.inner.hash.read(&mut work.inner.rhop); + work.inner.hash.read(&mut self.K); + work.matrix_sampling.expand(&self.rho, &mut self.A_hat); + work.inner + .sampling + .expand_s_into(&work.inner.rhop, P::Eta::ETA, 0, &mut self.s1); + work.inner + .sampling + .expand_s_into(&work.inner.rhop, P::Eta::ETA, P::L::USIZE, &mut self.s2); + self.s1.ntt_into(&mut self.s1_hat); + self.A_hat + .multiply_into(&self.s1_hat, &mut work.inner.sum, &mut work.inner.product); + work.inner.sum.ntt_inverse_into(&mut work.inner.t); + work.inner.round_into(self); + self.s2.ntt_into(&mut self.s2_hat); + self.t0.ntt_into(&mut self.t0_hat); + let (rho, t1) = work.encoded.as_mut_slice().split_at_mut(32); + rho.copy_from_slice(&self.rho); + let t1 = t1.try_into().map_err(|_| signature::Error::new())?; + P::encode_t1_into(&work.inner.t1, t1); + work.inner.hash.start(&[&work.encoded]); + work.inner.hash.read(&mut self.tr); + Ok(()) + } +} + impl KeyGenerationWorkspace

{ fn round_into(&mut self, key: &mut ExpandedSigningKey

) { for ((t, s2), (t1, t0)) in self diff --git a/vendor/ml-dsa-0.1.2/src/verifying.rs b/vendor/ml-dsa-0.1.2/src/verifying.rs index fcf28b1..35dcfff 100644 --- a/vendor/ml-dsa-0.1.2/src/verifying.rs +++ b/vendor/ml-dsa-0.1.2/src/verifying.rs @@ -14,6 +14,12 @@ use module_lattice::MaybeBox; use shake::Shake256; use signature::{DigestVerifier, Error, MultipartVerifier}; +#[cfg(feature = "protected-workspace")] +pub(crate) mod confidential; +#[cfg(feature = "protected-workspace")] +mod confidential_decode; +#[cfg(feature = "protected-workspace")] +mod confidential_operations; #[cfg(feature = "protected-workspace")] pub(crate) mod in_place; diff --git a/vendor/ml-dsa-0.1.2/src/verifying/confidential.rs b/vendor/ml-dsa-0.1.2/src/verifying/confidential.rs new file mode 100644 index 0000000..0e90760 --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/verifying/confidential.rs @@ -0,0 +1,75 @@ +//! DE: Verborgene Schlüssel, Signaturen und gesamte Verifikationsarithmetik schützen. +//! EN: Protect hidden keys, signatures and the complete verification arithmetic. + +use crate::{ + B64, MlDsaParams, + algebra::{NttMatrix, NttPolynomial, NttVector, Polynomial, Vector}, + hash_workspace::HashWorkspace, + param::EncodedW1, + sampling::{in_place::SamplingWorkspace, matrix_workspace::MatrixWorkspace}, +}; +use hybrid_array::{Array, typenum::U256}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +macro_rules! workspace { + ($($field:ident: $ty:ty),+ $(,)?) => { + /// DE: Objekt UND alle besuchten Matrixzeilen vor privater Eingabe sperren. + /// EN: Lock the object AND every visited matrix row before private ingress. + pub struct ConfidentialVerificationWorkspace { $(pub(super) $field: $ty),+ } + impl Default for ConfidentialVerificationWorkspace

{ + fn default() -> Self { Self { $($field: Default::default()),+ } } + } + impl Zeroize for ConfidentialVerificationWorkspace

{ + fn zeroize(&mut self) { $(self.$field.zeroize();)+ } + } + impl Drop for ConfidentialVerificationWorkspace

{ + fn drop(&mut self) { self.zeroize(); } + } + impl ZeroizeOnDrop for ConfidentialVerificationWorkspace

{} + impl core::fmt::Debug for ConfidentialVerificationWorkspace

{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("ConfidentialVerificationWorkspace").finish_non_exhaustive() + } + } + }; +} + +workspace! { + hash: HashWorkspace, + matrix_sampling: MatrixWorkspace, + sampling: SamplingWorkspace, + matrix: NttMatrix, + t1: Vector, + t1_scaled: Vector, + t1_hat: NttVector, + tr: B64, + mu: B64, + z: Vector, + hints: Array, P::K>, + c: Polynomial, + c_hat: NttPolynomial, + z_hat: NttVector, + az_hat: NttVector, + ct_hat: NttVector, + wp_hat: NttVector, + wp: Vector, + w1: Vector, + w1_bytes: EncodedW1

, + candidate: Array, + product: NttPolynomial, +} + +impl ConfidentialVerificationWorkspace

{ + /// DE: Öffentliche feste Geometrie; so viele Guards vor Eingang vorbereiten. + /// EN: Public fixed geometry; prepare this many guards before ingress. + #[must_use] + pub fn private_storage_count(&self) -> usize { + self.matrix.row_count() + } + + /// DE: Stabile Zeilenflächen besuchen; dürfen später nicht ersetzt werden. + /// EN: Visit stable row storage; rows must never be replaced afterward. + pub fn visit_private_storage(&self, visitor: impl FnMut(usize, usize) -> bool) -> bool { + self.matrix.visit_rows(visitor) + } +} diff --git a/vendor/ml-dsa-0.1.2/src/verifying/confidential_decode.rs b/vendor/ml-dsa-0.1.2/src/verifying/confidential_decode.rs new file mode 100644 index 0000000..1b913ec --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/verifying/confidential_decode.rs @@ -0,0 +1,35 @@ +//! DE: Signatur-Hints ohne gewöhnliche Schnitt-/Index-/Hint-Arrays dekodieren. +//! EN: Decode signature hints without ordinary cut/index/hint arrays. + +use super::confidential::ConfidentialVerificationWorkspace; +use crate::{EncodedSignature, MlDsaParams, algebra::AlgebraExt, param::EncodedHint}; +use hybrid_array::typenum::Unsigned; + +impl ConfidentialVerificationWorkspace

{ + pub(super) fn decode_signature(&mut self, signature: &EncodedSignature

) -> bool { + let (_, z, hints) = P::split_sig(signature); + P::decode_z_into(z, &mut self.z); + self.z.infinity_norm() < P::GAMMA1_MINUS_BETA && self.decode_hints(hints) + } + + fn decode_hints(&mut self, bytes: &EncodedHint

) -> bool { + let (indices, cuts) = P::split_hint(bytes); + self.hints.iter_mut().for_each(|row| row.fill(false)); + let mut start = 0; + for (row, end) in self.hints.iter_mut().zip(cuts.iter()) { + let end = usize::from(*end); + if end < start || end > P::Omega::USIZE { + return false; + } + let selected = &indices[start..end]; + if !selected.windows(2).all(|pair| pair[0] < pair[1]) { + return false; + } + for index in selected { + row[usize::from(*index)] = true; + } + start = end; + } + indices[start..].iter().all(|byte| *byte == 0) + } +} diff --git a/vendor/ml-dsa-0.1.2/src/verifying/confidential_operations.rs b/vendor/ml-dsa-0.1.2/src/verifying/confidential_operations.rs new file mode 100644 index 0000000..35702a1 --- /dev/null +++ b/vendor/ml-dsa-0.1.2/src/verifying/confidential_operations.rs @@ -0,0 +1,92 @@ +//! DE: Ursprüngliche Verifikationsgleichung ausschließlich in gesperrten Zielen. +//! EN: Original verification equation using protected destinations throughout. + +use super::confidential::ConfidentialVerificationWorkspace; +use crate::{ + EncodedSignature, EncodedVerifyingKey, MlDsaParams, + algebra::Elem, + hint::use_hint, + ntt::{Ntt, NttInverse, multiply_ntt_into}, +}; +use ctutils::CtEq; +use module_lattice::Truncate; + +impl ConfidentialVerificationWorkspace

{ + /// DE: Caller muss Objekt und besuchte Matrixzeilen vorab sperren. + /// Schlüssel/Signatur werden nur geliehen; keine Dekodier-Owner zurückgeben. + /// EN: Caller must prelock the object and every visited matrix row. + /// Borrow key/signature; never return owned decoding intermediates. + #[must_use] + pub fn verify_encoded( + &mut self, + key: &EncodedVerifyingKey

, + message: &[u8], + context: &[u8], + signature: &EncodedSignature

, + ) -> bool { + if context.len() > 255 || !self.decode_signature(signature) { + return false; + } + self.prepare_key(key); + let length: u8 = Truncate::truncate(context.len()); + self.hash + .start(&[&self.tr, &[0], &[length], context, message]); + self.hash.read(&mut self.mu); + let (challenge, _, _) = P::split_sig(signature); + self.sampling.ball_into(challenge, P::TAU, &mut self.c); + self.c.ntt_into(&mut self.c_hat); + self.z.ntt_into(&mut self.z_hat); + self.matrix + .multiply_into(&self.z_hat, &mut self.az_hat, &mut self.product); + self.reconstruct_w1(); + if P::encode_w1_into(&self.w1, &mut self.w1_bytes).is_err() { + return false; + } + self.hash.start(&[&self.mu, &self.w1_bytes]); + self.hash.read(&mut self.candidate); + challenge.ct_eq(&self.candidate).into() + } + + fn prepare_key(&mut self, key: &EncodedVerifyingKey

) { + let (rho, t1) = P::split_vk(key); + P::decode_t1_into(t1, &mut self.t1); + self.matrix_sampling.expand(rho, &mut self.matrix); + for (source, target) in self.t1.0.iter().zip(self.t1_scaled.0.iter_mut()) { + for (source, target) in source.0.iter().zip(target.0.iter_mut()) { + *target = Elem::new(1 << 13) * *source; + } + } + self.t1_scaled.ntt_into(&mut self.t1_hat); + self.hash.start(&[key.as_slice()]); + self.hash.read(&mut self.tr); + } + + fn reconstruct_w1(&mut self) { + for (source, target) in self.t1_hat.0.iter().zip(self.ct_hat.0.iter_mut()) { + multiply_ntt_into(&self.c_hat, source, target); + } + for ((a, b), out) in self + .az_hat + .0 + .iter() + .zip(self.ct_hat.0.iter()) + .zip(self.wp_hat.0.iter_mut()) + { + for ((a, b), out) in a.0.iter().zip(b.0.iter()).zip(out.0.iter_mut()) { + *out = *a - *b; + } + } + self.wp_hat.ntt_inverse_into(&mut self.wp); + for ((poly, hints), out) in self + .wp + .0 + .iter() + .zip(self.hints.iter()) + .zip(self.w1.0.iter_mut()) + { + for ((value, hint), out) in poly.0.iter().zip(hints.iter()).zip(out.0.iter_mut()) { + *out = use_hint::(*hint, *value); + } + } + } +} From 776d6540d78b644c4f419e7310871f8bc982736c Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:06:55 +0100 Subject: [PATCH 06/26] Protect private framing and retained stream counters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Private Trailer- und Signaturnachricht-Bytes direkt in vorab gesperrte Ziele kodieren; STREAM- und Rückhalte-Zähler vor Klartexteingang sperren. Fallible Trailer-API dokumentieren, ML-DSA-Patchmanifest berichtigen. R7/R8 bleiben gemeinsam in Draft PR355 offen. EN: Prelock framing bytes and retained counters without wire changes; preserve strict provenance checks and all existing signature/stream coverage. Strict API/no-API lint, 67 file and five stream groups per configuration, 29 integrations, format/limits/provenance pass with unchanged source hashes. No new unsafe; unapproved Windows token probe excluded. --- docs/ROADMAP.md | 7 + docs/SPEC.en.md | 11 +- docs/SPEC.md | 9 +- .../CONFIDENTIAL_FRAMING_VALIDATION.md | 63 +++++++ src/crypto/stream.rs | 4 +- src/crypto/stream_io.rs | 65 +++++--- src/crypto/stream_progress.rs | 48 ++++++ src/crypto/stream_progress_tests.rs | 98 +++++++++++ src/files/confidential_framing.rs | 68 ++++++++ src/files/confidential_framing_tests.rs | 101 ++++++++++++ src/files/format_v4.rs | 49 ++---- src/files/format_v4_tests.rs | 33 ++-- src/files/mod.rs | 2 + src/files/tail_v4.rs | 70 +------- src/files/tail_v4_drain.rs | 133 +++++++++++++++ src/files/tail_v4_drain_tests.rs | 155 ++++++++++++++++++ src/files/tail_v4_tests.rs | 54 ++++-- vendor/patches-sha256.json | 52 ++++-- 18 files changed, 848 insertions(+), 174 deletions(-) create mode 100644 docs/security/CONFIDENTIAL_FRAMING_VALIDATION.md create mode 100644 src/crypto/stream_progress.rs create mode 100644 src/crypto/stream_progress_tests.rs create mode 100644 src/files/confidential_framing.rs create mode 100644 src/files/confidential_framing_tests.rs create mode 100644 src/files/tail_v4_drain.rs create mode 100644 src/files/tail_v4_drain_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index bb5c4c2..5518c21 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -167,3 +167,10 @@ EN: One joint PR; platform/helper, remaining metadata, native/security/fuzz and full rollback acceptance remain open. See [hidden signature scope](security/HIDDEN_SIGNATURE_VALIDATION.md) and [restricted inspector proposal](security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md). + +DE: Derselbe Draft schützt nun auch Trailer-/Signaturnachricht-Bytes und laufende +STREAM-/Rückhalte-Zähler vor privater Befüllung. Berichte, native Pfade, +Sperrregister und Prozess-/Helper-Gesamtabnahme bleiben offen. +EN: Protected framing and retained stream/holdback counters in the same joint PR; +fallible Rust trailer API, unchanged wire bytes. No whole-row completion claim. +See [scope and migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 917b466..80679e4 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -3,8 +3,8 @@ > R7/R8 work in progress (#147, joint PR #355): verified sender identities use > fallible locked ownership. Rust API: `SignedBy::key_id()` replaces the public > Vec field, `try_duplicate()` replaces `Clone`; `Report` no longer implements `Clone`. -> CLI/JSON/format contracts remain unchanged. Partial remediation only; signature -> scratch, process/helper and other metadata paths remain open. See +> CLI/JSON/format contracts remain unchanged. Partial remediation only; final +> process/helper and other metadata acceptance remains open. See > [confidential sender identity](security/CONFIDENTIAL_SENDER_IDENTITY.md). > R8 follow-up in PR355: hidden signing-key construction, encoding and verification @@ -13,6 +13,13 @@ > final joint native acceptance remains pending. See > [validation scope and limits](security/HIDDEN_SIGNATURE_VALIDATION.md). +> R8 framing in PR355: encode private trailer/signature-message bytes directly +> into prelocked SecretBytes; lock retained STREAM/holdback counters before plaintext +> ingress and wipe before release. Rust API `format_v4::trailer` now returns +> `Result`; propagate with `?` and borrow bytes through `expose()`. +> Wire format unchanged; reports/transport and other R7/R8 paths remain open. +> [Scope and API migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). + > **Translation note:** This is the English translation of [`SPEC.md`](SPEC.md) (German), version > 2.22. Both versions are maintained together; every change to one is made to the other in the > same pull request. If they ever contradict each other, the German version applies until the diff --git a/docs/SPEC.md b/docs/SPEC.md index ee5dc53..33374b3 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -4,7 +4,7 @@ > fallibel in gesperrtem Speicher gehalten; Rust-API `SignedBy::key_id()` statt > öffentlichem Vec-Feld, `try_duplicate()` statt `Clone`; `Report` ohne `Clone`. > CLI-/JSON-/Formatverträge bleiben erhalten. Teilbehebung, kein Gesamtabschluss; -> Signatur-Scratch, Prozess-/Helper- und übrige Metadatenpfade weiter offen. +> Finale Prozess-/Helper- und übrige Metadatenabnahme weiter offen. > Details: [vertrauliche Absenderidentität](security/CONFIDENTIAL_SENDER_IDENTITY.md). > R8-Folgebaustein in PR355: Verborgener Signierschlüssel-Aufbau, Kodierung und @@ -13,6 +13,13 @@ > diesen Pfaden. Umsetzung im gemeinsamen Draft, finale native Abnahme noch offen. > [Prüfumfang und Grenzen](security/HIDDEN_SIGNATURE_VALIDATION.md). +> R8-Framing in PR355: Private Trailer-/Signaturnachricht-Bytes direkt in vorab +> gesperrte SecretBytes kodieren; laufende STREAM-/Rückhalte-Zähler vor Klartext- +> eingang sperren und vor Freigabe löschen. Rust-API `format_v4::trailer` liefert +> jetzt `Result`; mit `?` behandeln und Bytes mit `expose()` ausleihen. +> Wire-Format unverändert; Berichte/Transport und weitere R7/R8-Pfade bleiben offen. +> [Umfang und API-Migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). + > **English translation:** [`SPEC.en.md`](SPEC.en.md) – beide Fassungen werden im selben Pull Request gemeinsam geändert; bei Widersprüchen gilt bis zur Korrektur die deutsche. / Both versions are changed together in the same pull request; in case of contradiction the German one applies until fixed. > Änderung v2.19 (22.11.2026, Eigentümerauftrag zur autonomen Sicherheitsbehebung bis main): Secret-Speicher einschließlich KDF-/HKDF-Arbeitspuffern zwingend sperren; Fehler statt ungesperrtem Fallback, begrenzte Eingaben und sichere Freigabe. Keine Änderung von Format-/Ableitungsbytes. Details: [LOCKED_SECRETS.md](security/LOCKED_SECRETS.md). diff --git a/docs/security/CONFIDENTIAL_FRAMING_VALIDATION.md b/docs/security/CONFIDENTIAL_FRAMING_VALIDATION.md new file mode 100644 index 0000000..b7e89f9 --- /dev/null +++ b/docs/security/CONFIDENTIAL_FRAMING_VALIDATION.md @@ -0,0 +1,63 @@ +# Confidential framing / Vertrauliches Framing + +DE: Teilbaustein des freigegebenen gemeinsamen R7/R8-Plans in Draft #355, +kein Abschluss von M5 oder R7/R8. R6-Providerverträge bleiben erhalten. +EN: Component within the approved joint plan, not complete M5/R7/R8 acceptance. + +## Actual ownership / Tatsächliches Eigentum + +| Path / Pfad | Protection / Schutz | +|---|---| +| `confidential_framing::message` | Header SHA3-512 in LockedHash; domain, hash and length fields encoded directly into prelocked output, no private `to_le_bytes` array. | +| `confidential_framing::trailer` | Both little-endian lengths and unchanged magic written into prelocked SecretBytes; no returned ordinary array. | +| `format_v4::check_trailer` | Borrowed byte decoding into scalar words without an intermediate eight-byte array. | +| `tail_v4_drain` | Public-empty State prelocked before private population; held/written/zero counts retained in that state. Existing locked buffer truncated after EOF rather than copied into a second tail allocation. | +| `stream_io` | Writer cursor/total and reader cursor/released retained in a prelocked Progress state; checked arithmetic before hash/copy/output for the affected operation. Destructor wipes before unlock. | + +DE: Aufrufer erhalten bei ausdrücklich angeforderten `written()`, `position()`, +`finish()` und Trailer-Prüfung weiterhin skalare Längen. Kurzlebige skalare +Berechnungen und Compiler-/Registerkopien werden nicht als vollständig beseitigt +behauptet. Öffentliche Nonces, Blockzähler und Ciphertext-Geometrie bleiben vom +privaten Nutzlängenvertrag getrennt. Andere bekannte private Datensätze bleiben +konkrete offene Arbeit, keine umbenannte Compilergrenze. +EN: Scalar API disclosure is intentional; retained counters are protected. This +does not claim control over all compiler/register copies, caller-owned buffers, +OS transport buffers, remaining reports/serialization, native paths or lock-registry +records. Those joint-plan rows remain open. + +## Rust API migration / Rust-API-Migration + +DE: `format_v4::trailer(payload, pad)` liefert statt `[u8; 24]` jetzt +`Result`. Konstruktion mit `?` prüfen, Ausgabe mit `expose()` nur +ausleihen; notwendiges eigenständiges Duplikat fallibel mit +`SecretBytes::from_slice(original.expose())?` erstellen. Kein Clone-/Array-Fallback. +EN: Propagate the construction error, borrow for encryption, and use fallible +protected duplication only when independent ownership is required. Existing +internal callers and format tests migrate together. No format-version, endian, +domain, padding, trailer magic, signature-equation or CLI/JSON schema change. + +## Verification / Prüfung + +DE: Testfälle prüfen öffentliche Referenzbytes an Integergrenzen, vorhandene +Padding-/Manipulations-/Absenderregeln, reale AEAD-Chunkgrenzen und tatsächliche +Owner-/Byte-Sperren. Eigene begrenzte Linux-Kinder prüfen Verweigerung bei echtem +Nullbudget, Fehler und Unwind mit exaktem Sperrzähler-Baseline-Rücklauf; +Elternlimits bleiben unverändert. Assertions geben keine privaten Bytes/Adressen aus. +EN: Source-bound test and lint results are retained outside Git under +`analysis/issue-147-r7-r8-20261127T182246Z`. Native final joint acceptance is still +required; defining a test is not a claim that its final source version has passed. + +DE: Lokaler Quellenstand vor Veröffentlichung: neun Befehle erfolgreich, +Quellhashes vor/nach dem gesamten Lauf identisch. Strenges All-Target-Clippy +mit/ohne API, jeweils 67 Datei- und fünf STREAM-Gruppen bestanden; zusätzlich +29 Integrationsfälle für Chunk-/Fehler-/v4-/verborgene und öffentliche Signaturen. +Explizit ignorierte Kindfunktionen werden durch ihre erfolgreichen Eltern +begrenzt und tatsächlich aufgerufen. Root-/Plattform-Formatprüfung, Limits, +Diff und unveränderte Provider-Herkunftsprüfung erfolgreich. Ein erster +Lintfehler im Test wurde ohne private Fehlerausgabe korrigiert; Belege erhalten. +EN: Checkpoint `confidential-framing-v2.json` and complete command logs bind +these results to source hashes, with the separate format/provider proof. Native +final acceptance of this newer framing component remains pending. Earlier native +signature-head Rust suites passed, but their jobs correctly failed on the omitted +ML-DSA patch-manifest entries; those exact entries are corrected without changing +upstream provenance, other packages, scanner rules or the verification script. diff --git a/src/crypto/stream.rs b/src/crypto/stream.rs index 2bada97..2cb4def 100644 --- a/src/crypto/stream.rs +++ b/src/crypto/stream.rs @@ -155,13 +155,11 @@ pub fn decrypt( ) -> Result { let mut dec = DecryptReader::new(key, prefix, aad, reader)?; let mut buf = SecretBytes::zeroed(CHUNK_SIZE)?; - let mut total = 0u64; loop { let n = dec.read(buf.expose_mut())?; if n == 0 { - return Ok(total); + return Ok(dec.position()); } writer.write_all(&buf.expose()[..n])?; - total += n as u64; } } diff --git a/src/crypto/stream_io.rs b/src/crypto/stream_io.rs index d1006de..7b78d59 100644 --- a/src/crypto/stream_io.rs +++ b/src/crypto/stream_io.rs @@ -9,8 +9,8 @@ use std::io::{Read, Write}; -use super::SecretBytes; use super::locked_hash::LockedHash; +use super::{SecretBytes, secret_state::SecretState}; use sha3::Sha3_512; use zeroize::Zeroize; @@ -22,6 +22,14 @@ use crate::crypto::aead::TAG_LEN; use crate::crypto::stream::{CHUNK_SIZE, ENCRYPTED_CHUNK_SIZE, PREFIX_LEN, Stream, read_full}; use crate::{Error, Result}; +#[path = "stream_progress.rs"] +mod progress; +use progress::Progress; + +#[cfg(test)] +#[path = "stream_progress_tests.rs"] +mod progress_tests; + /// DE: Verschlüsselnder Schreiber: puffert bis zu einem Block; ein voller Block /// wird erst versiegelt, wenn weitere Daten folgen. `finish` versiegelt den Rest /// als letzten Block (auch leer). @@ -31,8 +39,7 @@ pub struct EncryptWriter { stream: Stream, inner: W, buf: SecretBytes, - used: usize, - total: u64, + progress: SecretState, hash: Option, } @@ -46,8 +53,7 @@ impl EncryptWriter { stream: Stream::new(key, prefix, aad)?, inner, buf: SecretBytes::zeroed(CHUNK_SIZE)?, - used: 0, - total: 0, + progress: Progress::prepare()?, hash: None, }) } @@ -58,19 +64,22 @@ impl EncryptWriter { /// DE/EN: [`Error::Io`], [`Error::Crypto`]. pub fn push(&mut self, mut data: &[u8]) -> Result<()> { while !data.is_empty() { - if self.used == CHUNK_SIZE { - let sealed = self.stream.seal(&self.buf.expose()[..self.used], false)?; + if self.progress.get().cursor == CHUNK_SIZE { + let sealed = self + .stream + .seal(&self.buf.expose()[..self.progress.get().cursor], false)?; self.inner.write_all(&sealed)?; self.buf.expose_mut().zeroize(); - self.used = 0; + self.progress.get_mut().cursor = 0; } - let take = (CHUNK_SIZE - self.used).min(data.len()); + let take = (CHUNK_SIZE - self.progress.get().cursor).min(data.len()); + self.progress.get().check_advance(take)?; if let Some(hash) = &mut self.hash { hash.update(&data[..take]); } - self.buf.expose_mut()[self.used..self.used + take].copy_from_slice(&data[..take]); - self.used += take; - self.total += take as u64; + self.buf.expose_mut()[self.progress.get().cursor..self.progress.get().cursor + take] + .copy_from_slice(&data[..take]); + self.progress.get_mut().advance(take)?; data = &data[take..]; } Ok(()) @@ -94,7 +103,7 @@ impl EncryptWriter { /// DE: Bisher aufgenommene Klartextbytes. EN: Plaintext bytes accepted so far. #[must_use] pub fn written(&self) -> u64 { - self.total + self.progress.get().total } /// DE: Schließt ab; liefert den inneren Schreiber und die Klartextlänge. @@ -103,10 +112,12 @@ impl EncryptWriter { /// # Errors /// DE/EN: [`Error::Io`], [`Error::Crypto`]. pub fn finish(mut self) -> Result<(W, u64)> { - let sealed = self.stream.seal(&self.buf.expose()[..self.used], true)?; + let sealed = self + .stream + .seal(&self.buf.expose()[..self.progress.get().cursor], true)?; self.inner.write_all(&sealed)?; self.inner.flush()?; - Ok((self.inner, self.total)) + Ok((self.inner, self.progress.get().total)) } } @@ -118,11 +129,10 @@ pub struct DecryptReader { stream: Stream, inner: R, plain: SecretBytes, - pos: usize, + progress: SecretState, pending: Vec, pending_len: usize, done: bool, - released: u64, hash: Option, } @@ -138,11 +148,10 @@ impl DecryptReader { stream: Stream::new(key, prefix, aad)?, inner, plain: SecretBytes::zeroed(0)?, - pos: 0, + progress: Progress::prepare()?, pending, pending_len, done: false, - released: 0, hash: None, }) } @@ -159,7 +168,7 @@ impl DecryptReader { }; let last = next_len == 0; self.plain = self.stream.open(&self.pending[..self.pending_len], last)?; - self.pos = 0; + self.progress.get_mut().cursor = 0; self.pending = next; self.pending_len = next_len; self.done = last; @@ -172,19 +181,21 @@ impl DecryptReader { /// # Errors /// DE/EN: [`Error::Decrypt`], [`Error::Io`]. pub fn read(&mut self, buf: &mut [u8]) -> Result { - while self.pos == self.plain.len() { + while self.progress.get().cursor == self.plain.len() { if self.done { return Ok(0); } self.refill()?; } - let n = buf.len().min(self.plain.len() - self.pos); - buf[..n].copy_from_slice(&self.plain.expose()[self.pos..self.pos + n]); + let n = buf.len().min(self.plain.len() - self.progress.get().cursor); + self.progress.get().check_advance(n)?; + buf[..n].copy_from_slice( + &self.plain.expose()[self.progress.get().cursor..self.progress.get().cursor + n], + ); if let Some(hash) = &mut self.hash { hash.update(&buf[..n]); } - self.pos += n; - self.released += n as u64; + self.progress.get_mut().advance(n)?; Ok(n) } @@ -205,7 +216,7 @@ impl DecryptReader { /// DE: Bisher herausgegebene Klartextbytes. EN: Plaintext bytes released so far. #[must_use] pub fn position(&self) -> u64 { - self.released + self.progress.get().total } /// DE: Liest genau `buf.len()` Bytes. EN: Reads exactly `buf.len()` bytes. @@ -231,7 +242,7 @@ impl DecryptReader { /// DE/EN: [`Error::InvalidInput`] (Restdaten / trailing data), [`Error::Decrypt`]. pub fn finish(mut self) -> Result<()> { loop { - if self.pos != self.plain.len() { + if self.progress.get().cursor != self.plain.len() { return Err(Error::InvalidInput { field: "archive" }); } if self.done { diff --git a/src/crypto/stream_progress.rs b/src/crypto/stream_progress.rs new file mode 100644 index 0000000..c91e9a0 --- /dev/null +++ b/src/crypto/stream_progress.rs @@ -0,0 +1,48 @@ +//! DE: Private STREAM-Längen vor Klartexteingang sperren und vor Freigabe löschen. +//! EN: Lock private STREAM lengths before plaintext ingress and wipe before release. + +use crate::{Error, Result, crypto::secret_state::SecretState}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +pub(super) struct Progress { + pub(super) cursor: usize, + pub(super) total: u64, +} + +impl Zeroize for Progress { + fn zeroize(&mut self) { + self.cursor.zeroize(); + self.total.zeroize(); + } +} + +impl Drop for Progress { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for Progress {} + +impl Progress { + pub(super) fn prepare() -> Result> { + SecretState::new(Self { + cursor: 0, + total: 0, + }) + } + + pub(super) fn check_advance(&self, bytes: usize) -> Result<()> { + self.cursor.checked_add(bytes).ok_or(Error::Crypto)?; + self.total + .checked_add(u64::try_from(bytes).map_err(|_| Error::Crypto)?) + .ok_or(Error::Crypto)?; + Ok(()) + } + + pub(super) fn advance(&mut self, bytes: usize) -> Result<()> { + self.check_advance(bytes)?; + self.cursor += bytes; + self.total += u64::try_from(bytes).map_err(|_| Error::Crypto)?; + Ok(()) + } +} diff --git a/src/crypto/stream_progress_tests.rs b/src/crypto/stream_progress_tests.rs new file mode 100644 index 0000000..566e939 --- /dev/null +++ b/src/crypto/stream_progress_tests.rs @@ -0,0 +1,98 @@ +//! DE: Laufende private Zähler am echten Strom und bei Verweigerung prüfen. +//! EN: Check live private counters on the real stream and under denial. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::locked_owner_test_support::locked; + +#[test] +fn stream_counters_stay_locked_across_partial_chunks_and_moves() { + let mut key = SecretBytes::zeroed(32).unwrap(); + crate::crypto::rng::fill(key.expose_mut()).unwrap(); + let plain = vec![23; CHUNK_SIZE + 17]; + let mut enc = + EncryptWriter::new(key.expose(), [0; PREFIX_LEN], b"public fixture", Vec::new()).unwrap(); + let base = std::ptr::from_ref(enc.progress.get()).addr(); + for part in plain.chunks(153) { + enc.push(part).unwrap(); + locked(enc.progress.get()); + let stable = std::ptr::from_ref(enc.progress.get()).addr() == base; + assert!(stable); + } + assert_eq!(enc.written(), plain.len() as u64); + let (cipher, written) = enc.finish().unwrap(); + assert_eq!(written, plain.len() as u64); + let mut dec = DecryptReader::new( + key.expose(), + [0; PREFIX_LEN], + b"public fixture", + cipher.as_slice(), + ) + .unwrap(); + let base = std::ptr::from_ref(dec.progress.get()).addr(); + let mut buffer = SecretBytes::zeroed(131).unwrap(); + while dec.read(buffer.expose_mut()).unwrap() != 0 { + locked(dec.progress.get()); + let stable = std::ptr::from_ref(dec.progress.get()).addr() == base; + assert!(stable); + } + assert_eq!(dec.position(), plain.len() as u64); + dec.finish().unwrap(); +} + +#[test] +fn counter_overflow_fails_before_copy_hash_or_output() { + let mut key = SecretBytes::zeroed(32).unwrap(); + crate::crypto::rng::fill(key.expose_mut()).unwrap(); + let mut enc = EncryptWriter::new(key.expose(), [0; PREFIX_LEN], b"", Vec::new()).unwrap(); + enc.progress.get_mut().total = u64::MAX; + assert!(matches!(enc.push(b"public fixture"), Err(Error::Crypto))); + assert_eq!(enc.progress.get().cursor, 0); + assert!(enc.buf.expose().iter().all(|b| *b == 0)); + let no_output = enc.inner.is_empty(); + assert!(no_output); + let mut state = Progress::prepare().unwrap(); + state.get_mut().cursor = usize::MAX; + assert!(matches!(state.get_mut().advance(1), Err(Error::Crypto))); + assert_eq!(state.get().total, 0); + state.get_mut().zeroize(); + assert_eq!((state.get().cursor, state.get().total), (0, 0)); +} + +#[cfg(target_os = "linux")] +#[test] +fn progress_denial_runs_in_own_child() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "crypto::stream_io::progress_tests::progress_denial_child", + "PQKEEP_PROGRESS_DENIAL_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn progress_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_PROGRESS_DENIAL_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let unwind = std::panic::catch_unwind(|| { + let mut progress = Progress::prepare().unwrap(); + progress.get_mut().advance(123).unwrap(); + locked(progress.get()); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + let failures = memlock::stats().failed_attempts; + assert!(matches!(Progress::prepare(), Err(Error::MemoryLock))); + assert!(memlock::stats().failed_attempts > failures); + assert_eq!(memlock::stats().locked_pages, baseline); +} diff --git a/src/files/confidential_framing.rs b/src/files/confidential_framing.rs new file mode 100644 index 0000000..972776d --- /dev/null +++ b/src/files/confidential_framing.rs @@ -0,0 +1,68 @@ +//! DE: Private Framingbytes direkt in vorab gesperrte Ziele schreiben. +//! EN: Write private framing bytes directly into prelocked destinations. + +use super::format_v4::{DOMAIN_V4, TRAILER_LEN, TRAILER_MAGIC}; +use crate::{ + Error, Result, + crypto::{SecretBytes, locked_hash::LockedHash}, +}; +use sha3::Sha3_512; + +pub(super) fn message( + header: &[u8], + plain_hash: &[u8], + payload: u64, + pad: u64, +) -> Result { + const TAG: &[u8] = b"sig/hidden\0"; + if plain_hash.len() != 64 { + return Err(Error::Crypto); + } + let mut header_hash = LockedHash::::new()?; + header_hash.update(header); + let header_hash = header_hash.finalize()?; + let prefix = DOMAIN_V4.len() + TAG.len(); + let mut out = SecretBytes::zeroed(prefix + 128 + 16)?; + let bytes = out.expose_mut(); + bytes[..DOMAIN_V4.len()].copy_from_slice(DOMAIN_V4); + bytes[DOMAIN_V4.len()..prefix].copy_from_slice(TAG); + bytes[prefix..prefix + 64].copy_from_slice(header_hash.expose()); + bytes[prefix + 64..prefix + 128].copy_from_slice(plain_hash); + write_word(&mut bytes[prefix + 128..prefix + 136], payload)?; + write_word(&mut bytes[prefix + 136..], pad)?; + Ok(out) +} + +pub(super) fn trailer(payload: u64, pad: u64) -> Result { + let mut out = SecretBytes::zeroed(TRAILER_LEN)?; + write_word(&mut out.expose_mut()[..8], payload)?; + write_word(&mut out.expose_mut()[8..16], pad)?; + out.expose_mut()[16..].copy_from_slice(TRAILER_MAGIC); + Ok(out) +} + +fn write_word(out: &mut [u8], mut value: u64) -> Result<()> { + if out.len() != 8 { + return Err(Error::Crypto); + } + // DE: Kein privates to_le_bytes-Rückgabearray; skalare Bytes direkt ins Ziel. + // EN: No private to_le_bytes return array; write scalar bytes directly to target. + for byte in out { + *byte = u8::try_from(value & 255).map_err(|_| Error::Crypto)?; + value >>= 8; + } + Ok(()) +} + +pub(super) fn read_word(bytes: &[u8]) -> Result { + if bytes.len() != 8 { + return Err(Error::Crypto); + } + Ok(bytes.iter().enumerate().fold(0, |value, (index, byte)| { + value | (u64::from(*byte) << (8 * index)) + })) +} + +#[cfg(test)] +#[path = "confidential_framing_tests.rs"] +mod tests; diff --git a/src/files/confidential_framing_tests.rs b/src/files/confidential_framing_tests.rs new file mode 100644 index 0000000..56a39b9 --- /dev/null +++ b/src/files/confidential_framing_tests.rs @@ -0,0 +1,101 @@ +//! DE: Geschütztes Framing gegen explizit öffentliche Referenzbytes prüfen. +//! EN: Compare protected framing with explicitly public reference bytes. +#![allow(clippy::unwrap_used)] + +use super::*; +use sha3::Digest; + +#[test] +fn words_and_trailers_match_public_reference_at_integer_boundaries() { + for value in [0, 1, 255, 256, u64::from(u32::MAX) + 1, u64::MAX] { + let mut bytes = SecretBytes::zeroed(8).unwrap(); + write_word(bytes.expose_mut(), value).unwrap(); + let equal = bytes.expose() == value.to_le_bytes(); + assert!(equal); + assert_eq!(read_word(bytes.expose()).unwrap(), value); + let tail = trailer(value, u64::MAX - value).unwrap(); + tail.assert_metadata_locked(); + crate::locked_owner_test_support::locked(tail.expose()); + let expected = [ + value.to_le_bytes().as_slice(), + (u64::MAX - value).to_le_bytes().as_slice(), + TRAILER_MAGIC, + ] + .concat(); + let equal = tail.expose() == expected; + assert!(equal); + } + assert!(write_word(&mut [0; 7], 1).is_err()); + assert!(read_word(&[0; 9]).is_err()); +} + +#[test] +fn hidden_message_matches_public_reference_without_changing_domain_or_lengths() { + let header = b"public header fixture"; + let plain_hash = Sha3_512::digest(b"public synthetic plaintext fixture"); + for (payload, pad) in [ + (0u64, 0u64), + (1, 255), + (u64::from(u32::MAX) + 1, u64::MAX), + (u64::MAX, 0), + ] { + let output = message(header, &plain_hash, payload, pad).unwrap(); + output.assert_metadata_locked(); + crate::locked_owner_test_support::locked(output.expose()); + let expected = [ + DOMAIN_V4, + b"sig/hidden\0", + Sha3_512::digest(header).as_slice(), + plain_hash.as_slice(), + &payload.to_le_bytes(), + &pad.to_le_bytes(), + ] + .concat(); + let equal = output.expose() == expected; + assert!(equal); + } + assert!(matches!( + message(header, &[0; 63], 0, 0), + Err(Error::Crypto) + )); +} + +#[cfg(target_os = "linux")] +#[test] +fn framing_denial_and_unwind_preserve_parent_policy() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::confidential_framing::tests::framing_denial_child", + "PQKEEP_FRAMING_DENIAL_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn framing_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_FRAMING_DENIAL_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let unwind = std::panic::catch_unwind(|| { + let _message = message(b"public header", &[0; 64], 1234, 256).unwrap(); + let _trailer = trailer(1234, 256).unwrap(); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + let failures = memlock::stats().failed_attempts; + assert!(matches!( + message(b"public header", &[0; 64], 1234, 256), + Err(Error::MemoryLock) + )); + assert!(matches!(trailer(1234, 256), Err(Error::MemoryLock))); + assert!(memlock::stats().failed_attempts >= failures + 2); + assert_eq!(memlock::stats().locked_pages, baseline); +} diff --git a/src/files/format_v4.rs b/src/files/format_v4.rs index 594a1d3..838759f 100644 --- a/src/files/format_v4.rs +++ b/src/files/format_v4.rs @@ -10,15 +10,15 @@ //! ``` //! //! Umgesetzt sind `SIGNED`, `PAD` (Füllung nach PADMÉ, nur Nullbytes, kanonische Länge) und -//! `ANON` (anonyme ML-KEM-1024-Empfänger, **experimentell**, #340); `HIDDEN_SENDER` ist reserviert -//! und „nicht unterstützt“, ebenso unbekannte Bits. v4 wird nur geschrieben, wenn eine Option es +//! `ANON` (anonyme ML-KEM-1024-Empfänger, **experimentell**, #340) sowie `HIDDEN_SENDER`. +//! Unbekannte Bits werden abgewiesen. v4 wird nur geschrieben, wenn eine Option es //! verlangt (Inhalt 3, `PAD` oder `ANON`); sonst ist v4 ungültig (D3 bleibt kanonisch). //! //! EN: Format v4 (`docs/V4_DRAFT.md`, #316/#83): v2 header with version 4, U16 option bits after //! the nonce prefix and a key commitment `commit` in every v4 file; new content type 3 "stream". A //! stream's plaintext ends with a trailer (layout above). `SIGNED`, `PAD` (PADMÉ padding, zero bytes //! only, canonical length) and `ANON` (anonymous ML-KEM-1024 recipients, **experimental**, #340) are -//! implemented; `HIDDEN_SENDER` is reserved and "unsupported", like unknown bits. v4 is only written +//! implemented together with `HIDDEN_SENDER`; unknown bits are rejected. v4 is only written //! when an option requires it (content 3, `PAD` or `ANON`); otherwise v4 is invalid (D3 stays //! canonical). @@ -36,13 +36,13 @@ pub const VERSION_V4: u16 = 4; /// DE: Domäne für Hüllen-AAD und Schlüsselbindung. EN: Domain for wrap AAD and key commitment. pub const DOMAIN_V4: &[u8] = b"PQKeep/file/v4\0"; -/// DE: Füllung (reserviert). EN: Padding (reserved). +/// DE: Füllung nach PADMÉ. EN: PADMÉ padding. pub const OPT_PAD: u16 = 0x0001; -/// DE: Anonyme Empfänger (reserviert). EN: Anonymous recipients (reserved). +/// DE: Experimentelle anonyme Empfänger. EN: Experimental anonymous recipients. pub const OPT_ANON: u16 = 0x0002; /// DE: Sichtbarer Absender wie v3. EN: Visible sender as in v3. pub const OPT_SIGNED: u16 = 0x0004; -/// DE: Verborgener Absender (reserviert). EN: Hidden sender (reserved). +/// DE: Verborgener Absender. EN: Hidden sender. pub const OPT_HIDDEN_SENDER: u16 = 0x0008; /// DE: Kennung am Ende des Trailers. EN: Marker at the end of the trailer. @@ -78,26 +78,7 @@ pub fn hidden_message( payload: u64, pad: u64, ) -> Result { - const TAG: &[u8] = b"sig/hidden\0"; - if plain_hash.len() != 64 { - return Err(Error::Crypto); - } - let header_hash = ::digest(header); - let parts: [&[u8]; 6] = [ - DOMAIN_V4, - TAG, - &header_hash, - plain_hash, - &payload.to_le_bytes(), - &pad.to_le_bytes(), - ]; - let mut out = SecretBytes::zeroed(parts.iter().map(|p| p.len()).sum())?; - let mut at = 0; - for part in parts { - out.expose_mut()[at..at + part.len()].copy_from_slice(part); - at += part.len(); - } - Ok(out) + super::confidential_framing::message(header, plain_hash, payload, pad) } /// DE: v4-Zusatzfelder des Headers. EN: v4 extra fields of the header. @@ -252,13 +233,12 @@ pub fn padding_for(payload: u64, padded: bool, trailer: usize) -> Result { /// DE: Trailer für `payload_len` Nutzbytes und `pad_len` Füllbytes. /// EN: Trailer for `payload_len` payload bytes and `pad_len` padding bytes. -#[must_use] -pub fn trailer(payload_len: u64, pad_len: u64) -> [u8; TRAILER_LEN] { - let mut out = [0u8; TRAILER_LEN]; - out[..8].copy_from_slice(&payload_len.to_le_bytes()); - out[8..16].copy_from_slice(&pad_len.to_le_bytes()); - out[16..].copy_from_slice(TRAILER_MAGIC); - out +/// DE: Vor privater Befüllung sperren; Bytes ausschließlich bewusst ausleihen. +/// EN: Lock before private population; borrow bytes only by explicit disclosure. +/// # Errors +/// DE/EN: [`Error::MemoryLock`], [`Error::Crypto`] bei ungültiger interner Geometrie / invalid internal geometry. +pub fn trailer(payload_len: u64, pad_len: u64) -> Result { + super::confidential_framing::trailer(payload_len, pad_len) } fn trailer_error() -> Error { @@ -279,8 +259,7 @@ pub fn check_trailer(bytes: &[u8], total: u64, padded: bool, trailer: usize) -> return Err(trailer_error()); } let word = |i: usize| -> Result { - let raw: [u8; 8] = bytes[i..i + 8].try_into().map_err(|_| trailer_error())?; - Ok(u64::from_le_bytes(raw)) + super::confidential_framing::read_word(&bytes[i..i + 8]).map_err(|_| trailer_error()) }; let (payload, pad) = (word(0)?, word(8)?); let canonical = padding_for(payload, padded, trailer).map_err(|_| trailer_error())?; diff --git a/src/files/format_v4_tests.rs b/src/files/format_v4_tests.rs index 5d828dc..63feb38 100644 --- a/src/files/format_v4_tests.rs +++ b/src/files/format_v4_tests.rs @@ -4,29 +4,32 @@ use super::*; #[test] fn trailer_roundtrip_and_rejections() { - let t = trailer(1234, 0); - assert_eq!(check_trailer(&t, 1234, false, TRAILER_LEN), Ok(1234)); - assert!(check_trailer(&t, 1233, false, TRAILER_LEN).is_err()); + let t = trailer(1234, 0).unwrap(); + assert_eq!( + check_trailer(t.expose(), 1234, false, TRAILER_LEN), + Ok(1234) + ); + assert!(check_trailer(t.expose(), 1233, false, TRAILER_LEN).is_err()); assert!( - check_trailer(&t, 1234, true, TRAILER_LEN).is_err(), + check_trailer(t.expose(), 1234, true, TRAILER_LEN).is_err(), "PAD verlangt Füllung / PAD needs padding" ); - let mut padded = t; - padded[8] = 1; - assert!(check_trailer(&padded, 1235, false, TRAILER_LEN).is_err()); - let mut magic = t; - magic[TRAILER_LEN - 1] = 1; - assert!(check_trailer(&magic, 1234, false, TRAILER_LEN).is_err()); - assert!(check_trailer(&t[..TRAILER_LEN - 1], 1234, false, TRAILER_LEN).is_err()); + let mut padded = SecretBytes::from_slice(t.expose()).unwrap(); + padded.expose_mut()[8] = 1; + assert!(check_trailer(padded.expose(), 1235, false, TRAILER_LEN).is_err()); + let mut magic = SecretBytes::from_slice(t.expose()).unwrap(); + magic.expose_mut()[TRAILER_LEN - 1] = 1; + assert!(check_trailer(magic.expose(), 1234, false, TRAILER_LEN).is_err()); + assert!(check_trailer(&t.expose()[..TRAILER_LEN - 1], 1234, false, TRAILER_LEN).is_err()); // DE: Kanonische PADMÉ-Füllung. EN: Canonical PADMÉ padding. let pad = padding_for(1234, true, TRAILER_LEN).unwrap(); - let good = trailer(1234, pad); + let good = trailer(1234, pad).unwrap(); assert_eq!( - check_trailer(&good, 1234 + pad, true, TRAILER_LEN), + check_trailer(good.expose(), 1234 + pad, true, TRAILER_LEN), Ok(1234) ); - let other = trailer(1234, pad + 1); - assert!(check_trailer(&other, 1235 + pad, true, TRAILER_LEN).is_err()); + let other = trailer(1234, pad + 1).unwrap(); + assert!(check_trailer(other.expose(), 1235 + pad, true, TRAILER_LEN).is_err()); } #[test] diff --git a/src/files/mod.rs b/src/files/mod.rs index 7979226..eaa45ae 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -16,6 +16,7 @@ mod anon_v4; mod archive; mod check; mod confidential_entries; +mod confidential_framing; mod confidential_path_index; mod confidential_text; mod decrypt; @@ -44,6 +45,7 @@ mod signer_v3; mod slot_v2; mod stream_v4; mod tail_v4; +mod tail_v4_drain; mod walk; use std::fs::File; diff --git a/src/files/tail_v4.rs b/src/files/tail_v4.rs index 7d3249c..af144a4 100644 --- a/src/files/tail_v4.rs +++ b/src/files/tail_v4.rs @@ -16,9 +16,10 @@ use super::format_v4::{ }; use super::signed_io::{HiddenResult, SignedBy}; use super::signer_v3::{FILE_SIG_CONTEXT, SIGNER_DSA, SIGNER_KEY_LEN, SIGNER_ML_DSA_87}; +use super::tail_v4_drain::{Drained, drain}; +use crate::crypto::dsa; use crate::crypto::stream::PlainHash; -use crate::crypto::stream::{CHUNK_SIZE, DecryptReader, EncryptWriter}; -use crate::crypto::{SecretBytes, dsa}; +use crate::crypto::stream::{DecryptReader, EncryptWriter}; use crate::envelope::UnlockedKey; use crate::{Error, Result}; @@ -76,71 +77,18 @@ pub(crate) fn push_tail(enc: &mut EncryptWriter, tail: &TailWrite<' enc.push(&key.public_key)?; enc.push(sig.expose())?; } - enc.push(&trailer(payload, pad)) -} - -/// DE: Was `drain` gelesen hat. EN: What `drain` has read. -struct Drained { - /// DE: Bytes vor dem Trailer. EN: Bytes before the trailer. - written: u64, - /// DE: Nullbytes am Ende davon. EN: Trailing zero bytes of those. - zeros: u64, - /// DE: Zurückgehaltener Trailer. EN: Held-back trailer. - tail: SecretBytes, -} - -/// DE: Liest den Rest: alles vor den letzten `hold` Bytes geht an `out` und (falls vorhanden) in -/// `hash`. EN: Reads the rest: everything before the last `hold` bytes goes to `out` and `hash`. -fn drain( - dec: &mut DecryptReader, - out: &mut impl Write, - holdback: usize, - mut hash: Option<&mut PlainHash>, -) -> Result { - let mut buf = SecretBytes::zeroed(CHUNK_SIZE + holdback)?; - let (mut held, mut written, mut zeros) = (0usize, 0u64, 0u64); - loop { - let n = dec.read(&mut buf.expose_mut()[held..])?; - if n == 0 { - break; - } - held += n; - if held > holdback { - let ready = held - holdback; - let part = &buf.expose()[..ready]; - out.write_all(part)?; - if let Some(h) = hash.as_deref_mut() { - h.update(part); - } - zeros = match part.iter().rposition(|b| *b != 0) { - Some(last) => (ready - last - 1) as u64, - None => zeros + ready as u64, - }; - written += ready as u64; - buf.expose_mut().copy_within(ready..held, 0); - held = holdback; - } - } - if held != holdback { - return Err(Error::InvalidInput { field: "trailer" }); - } - let tail = SecretBytes::from_slice(&buf.expose()[..holdback])?; - Ok(Drained { - written, - zeros, - tail, - }) + enc.push(trailer(payload, pad)?.expose()) } /// DE: Prüft Trailer, Füllung und ggf. den verborgenen Absender; liefert die Nutzlänge. /// EN: Checks trailer, padding and the optional hidden sender; returns the payload length. fn check_tail(d: &Drained, before: u64, tail: &TailRead, hash: Option) -> Result { - let bytes = d.tail.expose(); + let bytes = d.bytes()?; let (block, end) = bytes.split_at(bytes.len() - TRAILER_LEN); - let total = before.checked_add(d.written).ok_or(Error::Decrypt)?; + let total = before.checked_add(d.written()).ok_or(Error::Decrypt)?; let payload = check_trailer(end, total, tail.padded, bytes.len())?; let pad = total - payload; - if d.zeros < pad.min(d.written) || payload < before { + if d.zeros() < pad.min(d.written()) || payload < before { return Err(Error::InvalidInput { field: "padding" }); } if let Some((header, result)) = &tail.hidden { @@ -186,7 +134,7 @@ pub(crate) fn copy_payload( let d = drain(&mut dec, out, hold, hash.as_mut())?; dec.finish()?; let payload = check_tail(&d, 0, tail, hash)?; - Ok((payload, d.written)) + Ok((payload, d.written())) } /// DE: Archiv: nach dem Archiv-Ende nur Nullbytes, dann der Trailer mit genau der Archivlänge. @@ -200,7 +148,7 @@ pub(crate) fn finish_tail( let hold = trailer_len(tail.hidden.is_some()); let d = drain(&mut dec, &mut std::io::sink(), hold, hash.as_mut())?; dec.finish()?; - if d.zeros != d.written { + if d.zeros() != d.written() { return Err(Error::InvalidInput { field: "padding" }); } if check_tail(&d, archive_len, tail, hash)? != archive_len { diff --git a/src/files/tail_v4_drain.rs b/src/files/tail_v4_drain.rs new file mode 100644 index 0000000..8953305 --- /dev/null +++ b/src/files/tail_v4_drain.rs @@ -0,0 +1,133 @@ +//! DE: Auch Längen und Cursor des privaten Trailer-Rückhalts vor Eingang sperren. +//! EN: Prelock lengths and cursors of private trailer holdback before ingress. + +use super::format_v4::TRAILER_LEN; +use crate::{ + Error, Result, + crypto::{ + SecretBytes, + secret_state::SecretState, + stream::{CHUNK_SIZE, DecryptReader, PlainHash}, + }, +}; +use std::io::{Read, Write}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State { + buffer: Option, + held: usize, + written: u64, + zeros: u64, +} + +impl Zeroize for State { + fn zeroize(&mut self) { + self.buffer.take(); + self.held.zeroize(); + self.written.zeroize(); + self.zeros.zeroize(); + } +} +impl Drop for State { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +pub(super) struct Drained(SecretState); + +impl Drained { + fn prepare(holdback: usize) -> Result { + if holdback < TRAILER_LEN { + return Err(Error::Crypto); + } + let mut out = Self(SecretState::new(State { + buffer: None, + held: 0, + written: 0, + zeros: 0, + })?); + out.0.get_mut().buffer = Some(SecretBytes::zeroed( + CHUNK_SIZE.checked_add(holdback).ok_or(Error::Crypto)?, + )?); + Ok(out) + } + + pub(super) fn written(&self) -> u64 { + self.0.get().written + } + pub(super) fn zeros(&self) -> u64 { + self.0.get().zeros + } + pub(super) fn bytes(&self) -> Result<&[u8]> { + self.0 + .get() + .buffer + .as_ref() + .map(SecretBytes::expose) + .ok_or(Error::Crypto) + } +} + +pub(super) fn drain( + dec: &mut DecryptReader, + writer: &mut impl Write, + holdback: usize, + mut hash: Option<&mut PlainHash>, +) -> Result { + let mut out = Drained::prepare(holdback)?; + let state = out.0.get_mut(); + loop { + let buffer = state.buffer.as_mut().ok_or(Error::Crypto)?; + let n = dec.read(&mut buffer.expose_mut()[state.held..])?; + if n == 0 { + break; + } + state.held = state + .held + .checked_add(n) + .filter(|held| *held <= buffer.len()) + .ok_or(Error::Crypto)?; + if state.held > holdback { + release_ready(state, writer, holdback, hash.as_deref_mut())?; + } + } + if state.held != holdback { + return Err(Error::InvalidInput { field: "trailer" }); + } + state + .buffer + .as_mut() + .ok_or(Error::Crypto)? + .truncate(holdback); + Ok(out) +} + +fn release_ready( + state: &mut State, + writer: &mut impl Write, + holdback: usize, + hash: Option<&mut PlainHash>, +) -> Result<()> { + let ready = state.held - holdback; + let ready_u64 = u64::try_from(ready).map_err(|_| Error::Decrypt)?; + let buffer = state.buffer.as_mut().ok_or(Error::Crypto)?; + let part = &buffer.expose()[..ready]; + writer.write_all(part)?; + if let Some(hash) = hash { + hash.update(part); + } + state.zeros = match part.iter().rposition(|byte| *byte != 0) { + Some(last) => u64::try_from(ready - last - 1).map_err(|_| Error::Decrypt)?, + None => state.zeros.checked_add(ready_u64).ok_or(Error::Decrypt)?, + }; + state.written = state.written.checked_add(ready_u64).ok_or(Error::Decrypt)?; + buffer.expose_mut().copy_within(ready..state.held, 0); + state.held = holdback; + Ok(()) +} + +#[cfg(test)] +#[path = "tail_v4_drain_tests.rs"] +mod tests; diff --git a/src/files/tail_v4_drain_tests.rs b/src/files/tail_v4_drain_tests.rs new file mode 100644 index 0000000..6b2b597 --- /dev/null +++ b/src/files/tail_v4_drain_tests.rs @@ -0,0 +1,155 @@ +//! DE: Rückhalt, echte Sperren und Fehlerbereinigung über den AEAD-Strom prüfen. +//! EN: Check holdback, actual locks and failure cleanup through the AEAD stream. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::crypto::{ + rng, + stream::{EncryptWriter, PREFIX_LEN}, +}; +use crate::locked_owner_test_support::locked; + +fn key() -> SecretBytes { + let mut key = SecretBytes::zeroed(32).unwrap(); + rng::fill(key.expose_mut()).unwrap(); + key +} + +fn seal(key: &[u8], plain: &[u8]) -> Vec { + let mut enc = EncryptWriter::new(key, [0; PREFIX_LEN], b"public fixture", Vec::new()).unwrap(); + enc.push(plain).unwrap(); + enc.finish().unwrap().0 +} + +#[test] +fn streamed_holdback_matches_public_fixture_and_retains_locked_state() { + let key = key(); + for len in [ + 0, + 1, + CHUNK_SIZE - TRAILER_LEN, + CHUNK_SIZE, + 2 * CHUNK_SIZE + 3, + ] { + let mut plain = vec![19; len]; + plain.extend_from_slice(&[0; 37]); + plain.extend_from_slice(&[71; TRAILER_LEN]); + let encrypted = seal(key.expose(), &plain); + let mut dec = DecryptReader::new( + key.expose(), + [0; PREFIX_LEN], + b"public fixture", + encrypted.as_slice(), + ) + .unwrap(); + let mut output = Vec::new(); + let mut drained = drain(&mut dec, &mut output, TRAILER_LEN, None).unwrap(); + dec.finish().unwrap(); + let equal = output == plain[..plain.len() - TRAILER_LEN]; + assert!(equal); + let equal = drained.bytes().unwrap() == [71; TRAILER_LEN]; + assert!(equal); + assert_eq!(drained.written(), (len + 37) as u64); + assert_eq!(drained.zeros(), 37); + locked(drained.0.get()); + let buffer = drained.0.get().buffer.as_ref().unwrap(); + buffer.assert_metadata_locked(); + locked(buffer.expose()); + drained.0.get_mut().zeroize(); + assert!(drained.0.get().buffer.is_none()); + assert_eq!( + (drained.written(), drained.zeros(), drained.0.get().held), + (0, 0, 0) + ); + } +} + +#[test] +fn rejects_short_holdback_and_short_authenticated_stream() { + assert!(matches!( + Drained::prepare(TRAILER_LEN - 1), + Err(Error::Crypto) + )); + assert!(Drained::prepare(usize::MAX).is_err()); + let key = key(); + let encrypted = seal(key.expose(), b"public short fixture"); + let mut dec = DecryptReader::new( + key.expose(), + [0; PREFIX_LEN], + b"public fixture", + encrypted.as_slice(), + ) + .unwrap(); + assert!(matches!( + drain(&mut dec, &mut std::io::sink(), TRAILER_LEN, None), + Err(Error::InvalidInput { field: "trailer" }) + )); +} + +#[cfg(target_os = "linux")] +#[test] +fn drain_failure_cleanup_and_denial_preserve_parent_limit() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::tail_v4_drain::tests::drain_failure_child", + "PQKEEP_DRAIN_FAILURE_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn drain_failure_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_DRAIN_FAILURE_CHILD").unwrap(), "1"); + let key = key(); + let encrypted = seal(key.expose(), &vec![1; CHUNK_SIZE + TRAILER_LEN]); + let baseline = memlock::stats().locked_pages; + for panic in [false, true] { + let result = std::panic::catch_unwind(|| { + let mut dec = DecryptReader::new( + key.expose(), + [0; PREFIX_LEN], + b"public fixture", + encrypted.as_slice(), + ) + .unwrap(); + let mut writer = FailingWriter { panic }; + assert!(drain(&mut dec, &mut writer, TRAILER_LEN, None).is_err()); + }); + assert_eq!(result.is_err(), panic); + assert_eq!(memlock::stats().locked_pages, baseline); + } + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + let failures = memlock::stats().failed_attempts; + assert!(matches!( + Drained::prepare(TRAILER_LEN), + Err(Error::MemoryLock) + )); + assert!(memlock::stats().failed_attempts > failures); + assert_eq!(memlock::stats().locked_pages, baseline); +} + +#[cfg(target_os = "linux")] +struct FailingWriter { + panic: bool, +} + +#[cfg(target_os = "linux")] +impl Write for FailingWriter { + fn write(&mut self, _: &[u8]) -> std::io::Result { + if self.panic { + std::panic::resume_unwind(Box::new(())); + } + Err(std::io::Error::other("public test failure")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} diff --git a/src/files/tail_v4_tests.rs b/src/files/tail_v4_tests.rs index eeb9374..e6a2d34 100644 --- a/src/files/tail_v4_tests.rs +++ b/src/files/tail_v4_tests.rs @@ -1,6 +1,8 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use super::*; +use crate::crypto::SecretBytes; +use crate::crypto::stream::CHUNK_SIZE; use crate::crypto::stream::EncryptWriter; use crate::crypto::stream::PREFIX_LEN; use crate::files::Signer; @@ -37,7 +39,12 @@ fn payload_of(plain: &[u8], padded: bool) -> (Result<(u64, u64)>, Vec) { fn framed(data: &[u8], padded: bool) -> Vec { let pad = padding_for(data.len() as u64, padded, TRAILER_LEN).unwrap(); let zeros = vec![0u8; usize::try_from(pad).unwrap()]; - [data, &zeros, &trailer(data.len() as u64, pad)].concat() + [ + data, + &zeros, + trailer(data.len() as u64, pad).unwrap().expose(), + ] + .concat() } #[test] @@ -64,19 +71,19 @@ fn valid_trailer_releases_payload_and_padding_is_counted() { #[test] fn tampered_trailers_and_padding_are_rejected() { let data = vec![5u8; 1001]; - let good = trailer(1001, 0); - let mut wrong_len = good; - wrong_len[0] ^= 1; - let mut magic = good; - magic[TRAILER_LEN - 2] ^= 1; + let good = trailer(1001, 0).unwrap(); + let mut wrong_len = SecretBytes::from_slice(good.expose()).unwrap(); + wrong_len.expose_mut()[0] ^= 1; + let mut magic = SecretBytes::from_slice(good.expose()).unwrap(); + magic.expose_mut()[TRAILER_LEN - 2] ^= 1; let pad = padding_for(1001, true, TRAILER_LEN).unwrap(); let mut dirty = framed(&data, true); dirty[1001 + 3] = 1; - let off_by_one = [&data[..], &[0u8; 25], &trailer(1001, 25)].concat(); + let off_by_one = [&data[..], &[0u8; 25], trailer(1001, 25).unwrap().expose()].concat(); let cases: Vec<(Vec, bool)> = vec![ - ([&data[..], &wrong_len].concat(), false), - ([&data[..], &magic].concat(), false), - ([&data[..], &good, b"x"].concat(), false), + ([&data[..], wrong_len.expose()].concat(), false), + ([&data[..], magic.expose()].concat(), false), + ([&data[..], good.expose(), b"x"].concat(), false), (data[..10].to_vec(), false), (TRAILER_MAGIC.to_vec(), false), (Vec::new(), false), @@ -84,7 +91,10 @@ fn tampered_trailers_and_padding_are_rejected() { (framed(&data, true), false), (dirty, true), (off_by_one, true), - ([&data[..], &[0u8; 24], &trailer(1001, pad)].concat(), true), + ( + [&data[..], &[0u8; 24], trailer(1001, pad).unwrap().expose()].concat(), + true, + ), ]; for (i, (plain, padded)) in cases.iter().enumerate() { let (r, _) = payload_of(plain, *padded); @@ -102,7 +112,7 @@ fn archive_tail_accepts_only_zero_padding_after_the_archive() { let plain = { let pad = padding_for(500, padded, TRAILER_LEN).unwrap(); let zeros = vec![0u8; usize::try_from(pad).unwrap()]; - [&archive[..], &zeros, &trailer(500, pad)].concat() + [&archive[..], &zeros, trailer(500, pad).unwrap().expose()].concat() }; let sealed_plain = sealed(&plain); let mut dec = reader(&sealed_plain); @@ -117,12 +127,12 @@ fn archive_tail_accepts_only_zero_padding_after_the_archive() { let pad = padding_for(500, true, TRAILER_LEN).unwrap(); let mut zeros = vec![0u8; usize::try_from(pad).unwrap()]; zeros[0] = 1; - let bad = sealed(&[&archive[..], &zeros, &trailer(500, pad)].concat()); + let bad = sealed(&[&archive[..], &zeros, trailer(500, pad).unwrap().expose()].concat()); let mut dec = reader(&bad); let mut head = vec![0u8; 500]; dec.read_exact(&mut head).unwrap(); assert!(finish_tail(dec, 500, &tail(true)).is_err()); - let short = sealed(&[&archive[..], &trailer(499, 0)].concat()); + let short = sealed(&[&archive[..], trailer(499, 0).unwrap().expose()].concat()); let mut dec = reader(&short); dec.read_exact(&mut head).unwrap(); assert!(finish_tail(dec, 500, &tail(false)).is_err()); @@ -144,7 +154,13 @@ fn hidden_plain(kp: &dsa::DsaKeyPair, data: &[u8], header: &[u8], signed: (u64, ) .unwrap(); let block = [&[SIGNER_ML_DSA_87][..], &kp.public_key, &sig].concat(); - [data, &zeros, &block, &trailer(data.len() as u64, pad)].concat() + [ + data, + &zeros, + &block, + trailer(data.len() as u64, pad).unwrap().expose(), + ] + .concat() } /// DE: Wie `hidden_plain`, aber mit frei gewählter Füllung. EN: Like `hidden_plain` with chosen padding. @@ -161,7 +177,13 @@ fn hidden_plain_with_pad(kp: &dsa::DsaKeyPair, data: &[u8], pad: u64) -> Vec ) .unwrap(); let block = [&[SIGNER_ML_DSA_87][..], &kp.public_key, &sig].concat(); - [data, &zeros, &block, &trailer(data.len() as u64, pad)].concat() + [ + data, + &zeros, + &block, + trailer(data.len() as u64, pad).unwrap().expose(), + ] + .concat() } fn hidden_check(plain: &[u8], header: &[u8]) -> (Result<(u64, u64)>, Option) { diff --git a/vendor/patches-sha256.json b/vendor/patches-sha256.json index 357902a..d3cd75b 100644 --- a/vendor/patches-sha256.json +++ b/vendor/patches-sha256.json @@ -215,7 +215,7 @@ "path": "Cargo.toml" }, { - "sha256": "4f36fbfb2200aeef22323ffd5c4a346238e829d8bf51bf8d5442bcd9e9fc59fe", + "sha256": "7721b8bec4b6695b6438b2daccd30bffaeeb32a2b0db62590046f85df986f2b8", "path": "src/algebra.rs" }, { @@ -231,11 +231,11 @@ "path": "src/hash_workspace.rs" }, { - "sha256": "b2f459860cad9aee90fce36dcca3d55298c7fe925dc15ebbfbc5c3955b0c7ec2", + "sha256": "0f50c2a847adcf6ea969836afd8502d93f114d0160db60486157a8901ecccff4", "path": "src/hint.rs" }, { - "sha256": "82c8f39a0f4a2b82cf8f8c06ad3c78d9d119aaf556cc331ed119c6e048059fc9", + "sha256": "5a0940bd491609ba5ec23668abc8f5d9a3a1c1f8667a1af3c9362954e72bdefc", "path": "src/lib.rs" }, { @@ -243,23 +243,39 @@ "path": "src/ntt.rs" }, { - "sha256": "059eeb62220875479ca35d809fabf33e47e746a941dab6a2f40438f95710b262", + "sha256": "f87aecd75a14468c9022816bf49d0e03d57e099a192e986a91dec020d36fc478", "path": "src/param.rs" }, + { + "sha256": "8c55d56fdefcea76d7cc23f917b7db9b622f614759271982ac83ecec9664f003", + "path": "src/sampling.rs" + }, { "sha256": "d374e7ba9c964a22d7030b81f6829c1c2217760e6a744cfb6f963b2477f6e761", "path": "src/sampling/in_place.rs" }, { - "sha256": "27ea974a59effc0c42e499a45dfe12aee74abc1413f6fd5b62e727619987f7bb", - "path": "src/sampling.rs" + "sha256": "6f3aa1ee24ebe2747c9cfeb3342a96627ac67485bc890f6b25c599084e17e4da", + "path": "src/sampling/matrix_workspace.rs" }, { - "sha256": "3561aebac973136d3dddfb6db2f80432f07d94afb989ddde5aa381dff5bd0ac0", + "sha256": "691e9ef8ce1a0db4e55075691b141112cafa48d1acd87318578abfc509566e43", + "path": "src/signing.rs" + }, + { + "sha256": "adefe1a2b18b07ce993a97e7ed8a3a7341a1560f3b34a048e0b2b0a9595c9e44", "path": "src/signing/borrowed.rs" }, { - "sha256": "b34d6382ac006608a593a8f66a18d9af384fbde07b1b72a0d93980739e5eda7b", + "sha256": "28f139460628a9816cdb6c35dd0a9f465011edb7ea340137bb71b4c8a0f031f8", + "path": "src/signing/confidential_encoding.rs" + }, + { + "sha256": "5fb4713ed598e937b93e45bc21c4c09d97c1f4ab788e67f35f4beb9de1c4ce67", + "path": "src/signing/confidential_key.rs" + }, + { + "sha256": "656999ae93fe9b7d30538a15f622c34f39e159e059e3b909d8d7e67f770173e2", "path": "src/signing/in_place.rs" }, { @@ -267,16 +283,24 @@ "path": "src/signing/workspace.rs" }, { - "sha256": "15eacd4f4ee299bd85d100116ff84232f151565ca4df2ef28a14a346acaee5b3", - "path": "src/signing.rs" + "sha256": "1469e9f2132c04680ed2f59f90caba9e4f5fcd0c977ab268664895b41e867dd0", + "path": "src/verifying.rs" }, { - "sha256": "6722f4ed69c0e0dfb6dd80c500a1b60fa62e9d0cbb56329c37d60587e665e18b", - "path": "src/verifying/in_place.rs" + "sha256": "cb1cac683e21ca9fb0d3302832fee07250860c3f2bf07485d23f14c5a6dffdbe", + "path": "src/verifying/confidential.rs" }, { - "sha256": "fc8a4b48267279487787d09464fb9c3a9e0cd3636574bec412902b5a844f2349", - "path": "src/verifying.rs" + "sha256": "d02dde49f1e337021ca6bdb943529c9cdcf87c629f4c627b67f222afae7f9910", + "path": "src/verifying/confidential_decode.rs" + }, + { + "sha256": "deb41b31c728275489c67fbf98e879e61413683214461b6fb08061d23beb3186", + "path": "src/verifying/confidential_operations.rs" + }, + { + "sha256": "6722f4ed69c0e0dfb6dd80c500a1b60fa62e9d0cbb56329c37d60587e665e18b", + "path": "src/verifying/in_place.rs" } ], "shake-0.1.0": [ From dd5f4813b98a14529bc9d994e07ac4f0c53c1047 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:22:27 +0100 Subject: [PATCH 07/26] Integrate Main file race regressions without dropping security work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Alle neun Änderungen aus Main357 dc04d6f vollständig im gemeinsamen R7/R8-Draft erhalten; Konflikte der bereits übernommenen Integritätsdokumentation gegen den aktuellen Main-Stand abgleichen. Geschützte Framingmodule und API-Migration bleiben erhalten. EN: Preserve every Main357 race/attack regression and strict audit gate; no production logic or policy rollback. Full bundle/source backup verified, attack matrix source validator passes; unpublished registry and unapproved Windows prototype sources remain byte/mode-preserved. Native integrated acceptance pending. --- docs/FILE_FORMAT.md | 5 +- docs/security/ATTACK_TEST_MATRIX.md | 2 + docs/security/FILE_IO_RACES.md | 94 ++++++++++++++++ docs/security/attack-baseline.json | 4 +- docs/security/attack-matrix.json | 67 +++++++++--- src/fault_io_tests.rs | 25 ++++- src/fault_writer_tests.rs | 2 +- src/files/mod.rs | 3 + src/files/race_tests.rs | 164 ++++++++++++++++++++++++++++ 9 files changed, 344 insertions(+), 22 deletions(-) create mode 100644 docs/security/FILE_IO_RACES.md create mode 100644 src/files/race_tests.rs diff --git a/docs/FILE_FORMAT.md b/docs/FILE_FORMAT.md index 18d022d..81520ff 100644 --- a/docs/FILE_FORMAT.md +++ b/docs/FILE_FORMAT.md @@ -140,7 +140,8 @@ sehen nur „signiert, Absender verborgen“; wer entschlüsseln kann, prüft de - Zeitstempel, Eigentümer und Rechte werden nicht übernommen, nur Inhalt und Struktur. - Originale werden nicht gelöscht (sicheres Löschen ist auf SSDs unzuverlässig). - Zwischen Prüfen und Öffnen einer Quelldatei könnte ein lokaler Angreifer sie gegen einen Symlink - tauschen (TOCTOU); das betrifft nur Angreifer mit Schreibrechten im Quellordner. + tauschen (TOCTOU); das betrifft nur Angreifer mit Schreibrechten im Quellordner. Abhilfe geplant in #338 + ([Datei-Races](security/FILE_IO_RACES.md)). - Ordner werden per „Prüfen + Umbenennen“ veröffentlicht; ein exakt gleichzeitig angelegtes Ziel wäre ein theoretisches Rennen (unter Windows schlägt das Umbenennen dann fehl). - Wird PQKeep beim Entschlüsseln hart beendet (Kill, Absturz, Stromausfall), kann eine @@ -231,7 +232,7 @@ decrypting, but before any output. The file grows by about 7 KB. **Limitations:** approximate total size is visible; timestamps/ownership/permissions are not kept; originals are not deleted; a local attacker with write access to the source directory could swap a -file for a symlink between check and open (TOCTOU); directory publishing is check + rename; memory use +file for a symlink between check and open (TOCTOU; remedy planned in #338, [file races](security/FILE_IO_RACES.md)); directory publishing is check + rename; memory use is constant; if PQKeep is killed while decrypting (kill, crash, power loss) a **temporary plaintext file** with a hidden name (`.name.tmp-…`, Linux 0600) may remain – nothing unverified ever appears under the target name; against leftovers on the medium only **full-disk encryption** (LUKS, BitLocker) helps; diff --git a/docs/security/ATTACK_TEST_MATRIX.md b/docs/security/ATTACK_TEST_MATRIX.md index 052d5ea..95b7e8e 100644 --- a/docs/security/ATTACK_TEST_MATRIX.md +++ b/docs/security/ATTACK_TEST_MATRIX.md @@ -25,6 +25,7 @@ follows with the next baseline run. 1.5.0 adds QA1-FMT-013 (#316/#340, anonymous recipients, experimental, partial): 63 cases. 1.6.0 adds QA1-FMT-014 (#316, hidden sender): 64 cases. 1.7.0 adds QA1-FMT-015 (#335, container integrity matrix); QA1-FMT-003 covered, QA1-REC-003 partial (kill test, limit L1 → #338): 65 cases. +1.8.0: QA1-FS-008 partial (#338, deterministic race tests; gaps reproduced, fixes in PR 2–4): 65 cases. [Execution evidence](FAULT_RECOVERY_EVIDENCE.md) pins signed source/CI; broad original gaps stay open. ### Files, status and execution @@ -191,6 +192,7 @@ CI-Nachweis folgt mit dem nächsten Baseline-Lauf. 1.5.0 ergänzt QA1-FMT-013 (#316/#340, anonyme Empfänger, experimentell, teilweise): 63 Fälle. 1.6.0 ergänzt QA1-FMT-014 (#316, verborgener Absender): 64 Fälle. 1.7.0 ergänzt QA1-FMT-015 (#335, Integritätsmatrix der Container); QA1-FMT-003 abgedeckt, QA1-REC-003 teilweise (Kill-Test, Grenze L1 → #338): 65 Fälle. +1.8.0: QA1-FS-008 teilweise (#338, deterministische Race-Tests; Lücken nachgestellt, Behebung in PR 2–4): 65 Fälle. [Ausführungsnachweise](FAULT_RECOVERY_EVIDENCE.md) verknüpfen Quelle/CI; breite Altlücken bleiben offen. ### Dateien, Status und Ausführung diff --git a/docs/security/FILE_IO_RACES.md b/docs/security/FILE_IO_RACES.md new file mode 100644 index 0000000..9617d15 --- /dev/null +++ b/docs/security/FILE_IO_RACES.md @@ -0,0 +1,94 @@ +# Datei-Races / File I/O races (#338) + +Deutsch zuerst, [English below](#english). + +**Stand:** 27.11.2026, PR 1 (Ist-Zustand, Bedrohungsmodell, Tests). Umsetzung in PR 2–5, +Reihenfolge freigegeben: Veröffentlichung Linux → Windows → Quellen → Reste. + +## Bedrohungsmodell + +- **Vertrauenswürdiger Ordner:** nur der Nutzer selbst schreibt dort (übliches Home). Races + sind dort keine Angriffsfläche, nur Robustheit (gleichzeitige eigene Prozesse). +- **Fremd beschreibbarer Ordner:** ein anderer lokaler Nutzer oder Prozess darf im Quell- oder + Zielordner anlegen, löschen und umbenennen (gemeinsame Ordner, synchronisierte Ordner, + Austauschordner). Root bzw. Administrator ist **nicht** Teil des Modells (kann ohnehin alles). +- **Schutzziele:** (1) nie etwas anderes lesen und verschlüsseln als die geprüfte Quelle, + (2) nie ein fremdes Ziel überschreiben oder ersetzen, (3) nie außerhalb des gewählten Pfads + schreiben, (4) nie ungeprüften Klartext unter dem Zielnamen, (5) möglichst kein benannter + Klartextrest nach Kill. + +## Ist-Zustand + +| Stelle | Heute | Bewertung | Test (`src/files/race_tests.rs`) | +|---|---|---|---| +| Temporärausgabe anlegen | `create_new` (O_EXCL, folgt keinem Symlink), Zufallsname, Linux 0600, Ordner 0700 | hält | über vorhandene REC-Tests | +| Dateiziel veröffentlichen | Hardlink auf den Zielnamen (scheitert, wenn er existiert), dann Temporärname entfernen | hält, atomar | `file_target_created_before_publish_is_never_overwritten` (scharf) | +| Rückfall ohne Hardlinks (z. B. FAT) | prüfen, dann `rename` – ersetzt ein dazwischen angelegtes Ziel | **Lücke** (2) | `fallback_without_hard_links_never_overwrites` (ignoriert bis PR 2) | +| Ordnerziel veröffentlichen | prüfen, dann `rename` – unter POSIX ersetzt `rename` einen leeren Ordner | **Lücke** (2) | `directory_target_created_before_rename_is_not_replaced` (ignoriert bis PR 2) | +| Quellen öffnen | Durchlauf prüft mit `symlink_metadata`, später `File::open` folgt Symlinks | **Lücke** (1): ein dazwischen gesetzter Symlink lässt eine andere, für den Nutzer lesbare Datei verschlüsseln | `source_swapped_for_symlink_is_never_read` (ignoriert bis PR 4) | +| Pfade der Elternordner | Operationen über Pfade, nicht über Verzeichnis-Handles | Restrisiko: Austausch eines Elternordners gegen einen Symlink | PR 4 (Durchlauf über Handles) | +| Temporärausgabe nach dem Anlegen | Weitere Schritte über Pfade, nicht über Handles | **Offenes Risiko** in fremd beschreibbaren Zielordnern ohne Sticky-Bit (Austausch der Temporärausgabe); Behebung mit Vorrang in Arbeit | folgt mit der Behebung | +| Rest nach Kill | benannte Temporärdatei kann bleiben (Audit #335, L1) | Restrisiko (5) | `tests/integrity_kill.rs` | + +Die ersten drei Lücken waren bereits in [FILE_FORMAT.md](../FILE_FORMAT.md) unter „Grenzen“ +dokumentiert. Der Austausch der Temporärausgabe in fremd beschreibbaren Zielordnern ist ein +**offenes Risiko** (Hinweis aus dem Review von #357) und wird mit Vorrang behoben; bis dahin nur +vertrauenswürdige Zielordner (nur Eigentümer schreibt, oder Sticky-Bit) verwenden. Die Tests stellen sie über Test-Haltepunkte (nur `cfg(test)`, +kein produktiver Hook) deterministisch nach: `cargo test --lib race_tests -- --include-ignored` +zeigt heute drei Fehlschläge, die mit PR 2 bzw. PR 4 verschwinden und dann scharf geschaltet +werden. + +## Geplante Abhilfe + +- **Vorrang (Linux und Windows):** Ausgabe durchgehend über Handles statt Pfade, Prüfung des + veröffentlichten Objekts. +- **PR 2 (Linux):** Datei-, Strom- und `.pqkf`-Ziele als namenlose Datei (`O_TMPFILE`) im + Zielordner, Veröffentlichung per `linkat` (scheitert bei vorhandenem Ziel; zuerst + `AT_EMPTY_PATH`, sonst `/proc/self/fd`); Ordner per `renameat2(RENAME_NOREPLACE)`; Rückfall auf + den heutigen Weg nur, wo das Dateisystem es nicht kann – nie schwächer als heute. +- **PR 3 (Windows):** Datei mit „Löschen ausstehend“, Veröffentlichen per Handle ohne Ersetzen. +- **PR 4 (Quellen):** `O_NOFOLLOW` + `fstat` mit Abgleich von Gerät/Inode/Größe, Durchlauf über + Verzeichnis-Handles; Windows: Reparse-Punkte abweisen, Datei-ID vergleichen. +- **PR 5 (Reste):** eigene Reste beim nächsten Lauf erkennen; interaktiv mit Rückfrage + entfernen, mit `--batch` nur Hinweis. +- **Bleibt:** Stromausfall – Klartextblöcke können physisch auf dem Datenträger bleiben; + Vollverschlüsselung empfohlen. + +--- + +## English + +**Status:** 2026-11-27, PR 1 (current state, threat model, tests). Implementation in PR 2–5 in the +approved order: publication Linux → Windows → sources → leftovers. + +**Threat model:** a *trusted* directory is written only by the user (races are robustness, not +attack surface); in a *foreign-writable* directory another local user or process may create, +delete and rename in the source or target directory (shared, synced or exchange folders). Root or +administrator is out of scope. Goals: (1) never read and encrypt anything but the checked source, +(2) never overwrite or replace a foreign target, (3) never write outside the chosen path, (4) never +unverified plaintext under the target name, (5) ideally no named plaintext leftover after a kill. + +**Current state:** temporary outputs use `create_new` (O_EXCL, no symlink following), random +names, Linux 0600/0700 – holds. File targets are published via a hard link that fails if the name +exists – holds, atomic (test enforced). **Gaps:** the fallback without hard links (e.g. FAT) and +directory publication are check-then-`rename`, which replaces a target created in between (POSIX +`rename` replaces an empty directory) – goal (2); sources are checked with `symlink_metadata` +during the walk but opened later with `File::open`, which follows symlinks – a symlink swapped in +between makes PQKeep encrypt another file readable by the user – goal (1); parent directories are +handled by path, not by directory handles; a named temporary file may remain after a kill (audit +#335, L1). The first three gaps were already documented in [FILE_FORMAT.md](../FILE_FORMAT.md). +Further steps after creating the temporary output also use paths instead of handles – an **open +risk** in foreign-writable target directories without the sticky bit (replacement of the temporary +output; pointed out in the review of #357), fixed with priority; until then use trusted target +directories only (owner-only or sticky). `src/files/race_tests.rs` reproduces them deterministically via test checkpoints +(`cfg(test)` only, no productive hook); the gap tests are `#[ignore]` until PR 2 or PR 4 fixes them. + +**Planned remedy:** priority – handle-based output throughout and verification of the published +object (Linux and Windows); PR 2 Linux – unnamed `O_TMPFILE` outputs published with `linkat` (fails if the +target exists; `AT_EMPTY_PATH` first, else `/proc/self/fd`), directories via +`renameat2(RENAME_NOREPLACE)`, fallback to today's path only where the file system cannot – never +weaker than today; PR 3 Windows – delete-pending file, handle-based rename without replace; PR 4 +sources – `O_NOFOLLOW` + `fstat` matching device/inode/size, walking via directory handles, +Windows: reject reparse points, compare file IDs; PR 5 leftovers – detect own leftovers on the next +run, remove after confirmation interactively, notice only with `--batch`. Remaining: power loss – +plaintext blocks may physically remain; full-disk encryption recommended. diff --git a/docs/security/attack-baseline.json b/docs/security/attack-baseline.json index 273a621..9c43ce5 100644 --- a/docs/security/attack-baseline.json +++ b/docs/security/attack-baseline.json @@ -1,7 +1,7 @@ { "schema_version": 1, - "baseline_version": "1.7.0", - "matrix_version": "1.7.0", + "baseline_version": "1.8.0", + "matrix_version": "1.8.0", "evidence": [ { "id": "B1-linux-x86_64", diff --git a/docs/security/attack-matrix.json b/docs/security/attack-matrix.json index f83f899..3af2754 100644 --- a/docs/security/attack-matrix.json +++ b/docs/security/attack-matrix.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "matrix_version": "1.7.0", + "matrix_version": "1.8.0", "reviewed_source_commit": "ab65cd0cf736366acf2d6fad8569fe76b291c2da", "cases": [ { @@ -2157,9 +2157,11 @@ "id": "QA1-FS-008", "category": "Filesystem", "component_paths": [ - "src/fsutil.rs", + "docs/security/FILE_IO_RACES.md", "src/files/output.rs", - "src/files/paths.rs" + "src/files/paths.rs", + "src/files/race_tests.rs", + "src/fsutil.rs" ], "scenario": { "de": "Source-Austausch/gleichzeitige Zielanlage/FAT-Fallback", @@ -2173,9 +2175,9 @@ "de": "Dokumentierte TOCTOU-/Publish-/FAT-Grenzen; keine deterministische Race-Prüfung.", "en": "Documented TOCTOU/publication/FAT boundaries; no deterministic race test." }, - "implementation_state": "documented-only", - "coverage_status": "missing", - "automation": "automatable", + "implementation_state": "implemented", + "coverage_status": "partial", + "automation": "automated", "platforms": [ "linux-x86_64", "linux-arm64", @@ -2189,23 +2191,62 @@ "de": "Nur synthetische Testdaten; OS-/Featurebedingungen der referenzierten Tests beachten.", "en": "Synthetic test data only; observe OS/feature conditions of referenced tests." }, - "test_refs": [], - "ci_refs": [], + "test_refs": [ + { + "path": "src/files/race_tests.rs", + "symbol": "file_target_created_before_publish_is_never_overwritten", + "kind": "rust-unit", + "stage": "existing" + }, + { + "path": "src/files/race_tests.rs", + "symbol": "fallback_without_hard_links_never_overwrites", + "kind": "rust-unit", + "stage": "existing" + }, + { + "path": "src/files/race_tests.rs", + "symbol": "directory_target_created_before_rename_is_not_replaced", + "kind": "rust-unit", + "stage": "existing" + }, + { + "path": "src/files/race_tests.rs", + "symbol": "source_swapped_for_symlink_is_never_read", + "kind": "rust-unit", + "stage": "existing" + } + ], + "ci_refs": [ + { + "workflow": ".github/workflows/ci.yml", + "job": "test", + "matrix_filter": [ + "ubuntu-latest", + "ubuntu-22.04", + "ubuntu-22.04-arm", + "windows-latest" + ], + "gate": "required-except-arm64", + "stage": "existing" + } + ], "priority": "P1", "issues": [ 151, 152, - 153 + 153, + 338 ], "v2_ids": [], "evidence_refs": [], "gap": { - "de": "Dokumentierte TOCTOU-/Publish-/FAT-Grenzen; keine deterministische Race-Prüfung.", - "en": "Documented TOCTOU/publication/FAT boundaries; no deterministic race test." + "de": "Race-Tests stellen die Lücken nach (Rückfall ohne Hardlinks, Ordner per Prüfen + Umbenennen, Quelle folgt Symlink nach dem Durchlauf); drei Tests sind bis zur Behebung ignoriert.", + "en": "Race tests reproduce the gaps (fallback without hard links, directory check + rename, source follows a symlink after the walk); three tests are ignored until fixed." }, "next_evidence": { - "de": "Konkrete fehlende Variante im verknüpften Issue prüfen; keine Produktänderung in #151.", - "en": "Review the missing variant in the linked issue; no production change in #151." + "de": "#338 PR 2 (O_TMPFILE/linkat, renameat2 NOREPLACE), PR 3 (Windows per Handle), PR 4 (O_NOFOLLOW + fstat, Verzeichnis-Handles); dann Tests scharf schalten.", + "en": "#338 PR 2 (O_TMPFILE/linkat, renameat2 NOREPLACE), PR 3 (Windows handle-based), PR 4 (O_NOFOLLOW + fstat, directory handles); then enforce the tests." }, "retired": false, "replacement": null diff --git a/src/fault_io_tests.rs b/src/fault_io_tests.rs index c2f570b..b586b82 100644 --- a/src/fault_io_tests.rs +++ b/src/fault_io_tests.rs @@ -44,12 +44,18 @@ impl Failure { #[derive(Clone, Copy)] pub(crate) enum Action { Fail(Failure), - Partial { after: usize, failure: Failure }, + Partial { + after: usize, + failure: Failure, + }, Short(usize), Interrupt, Zero, Pause, PauseAfter(usize), + /// DE: Führt am Haltepunkt eine Aktion mit dessen Pfad aus (Race-Tests, #338). + /// EN: Runs an action with the checkpoint's path (race tests, #338). + Run(fn(&Path)), } #[derive(Clone, Copy)] @@ -87,8 +93,10 @@ impl Scope { for plan in &plans { assert!(plan.occurrence > 0, "Fault occurrence / Fehlervorkommen"); assert!( - matches!(plan.action, Action::Fail(_) | Action::Pause) - || plan.point == Point::Write + matches!( + plan.action, + Action::Fail(_) | Action::Pause | Action::Run(_) + ) || plan.point == Point::Write ); assert!(!matches!(plan.action, Action::Short(0))); } @@ -174,6 +182,10 @@ pub(crate) fn consume(state: &Shared) { } pub(crate) fn check_state(state: &Shared, point: Point) -> io::Result<()> { + check_state_at(state, point, None) +} + +fn check_state_at(state: &Shared, point: Point, path: Option<&Path>) -> io::Result<()> { match action(state, point) { None => Ok(()), Some(Action::Fail(failure)) => { @@ -184,10 +196,15 @@ pub(crate) fn check_state(state: &Shared, point: Point) -> io::Result<()> { consume(state); crate::crash_driver_tests::pause() } + Some(Action::Run(run)) => { + consume(state); + run(path.unwrap()); + Ok(()) + } Some(_) => panic!("Invalid fault point / Ungültiger Fehlerpunkt"), } } pub(crate) fn checkpoint(path: &Path, point: Point) -> io::Result<()> { - capture(path).map_or(Ok(()), |s| check_state(&s, point)) + capture(path).map_or(Ok(()), |s| check_state_at(&s, point, Some(path))) } diff --git a/src/fault_writer_tests.rs b/src/fault_writer_tests.rs index 97b15b8..99ddd13 100644 --- a/src/fault_writer_tests.rs +++ b/src/fault_writer_tests.rs @@ -64,7 +64,7 @@ impl OutputFile { crate::crash_driver_tests::pause()?; Ok(length) } - Action::Partial { .. } | Action::PauseAfter(_) => unreachable!(), + Action::Partial { .. } | Action::PauseAfter(_) | Action::Run(_) => unreachable!(), } } } diff --git a/src/files/mod.rs b/src/files/mod.rs index eaa45ae..9ea70a0 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -34,6 +34,9 @@ mod locked_owner_tests; mod original; mod output; pub mod paths; +#[cfg(test)] +#[path = "race_tests.rs"] +mod race_tests; pub mod random_name; #[cfg(test)] #[path = "recovery_v4_tests.rs"] diff --git a/src/files/race_tests.rs b/src/files/race_tests.rs new file mode 100644 index 0000000..5582a48 --- /dev/null +++ b/src/files/race_tests.rs @@ -0,0 +1,164 @@ +//! DE: Datei-Races (#338, PR 1): deterministische Tests über Test-Haltepunkte (nur `cfg(test)`): +//! ein konkurrierender Prozess legt das Ziel zwischen Prüfung und Veröffentlichung an oder tauscht +//! die Quelle zwischen Durchlauf und Öffnen gegen einen Symlink. Was heute schon hält, ist scharf; +//! bekannte Lücken sind mit `#[ignore]` markiert und werden mit PR 2 (Veröffentlichung) bzw. PR 4 +//! (Quellen) scharf geschaltet – `cargo test -- --ignored` zeigt den heutigen Stand. +//! EN: File races (#338, PR 1): deterministic tests via test checkpoints (`cfg(test)` only): a +//! concurrent process creates the target between check and publication or swaps the source for a +//! symlink between walk and open. What already holds is enforced; known gaps are marked +//! `#[ignore]` and get enforced with PR 2 (publication) or PR 4 (sources) – `cargo test -- +//! --ignored` shows today's state. +#![allow(clippy::unwrap_used)] + +use std::io::ErrorKind; +use std::path::Path; + +use crate::crypto::kdf; +use crate::fault_fixture_tests::{assert_no_temps, plan}; +use crate::fault_io_tests::{Action, Failure, Point, Scope}; +use crate::files::{self, Protection, Unlock}; +use crate::security::{StrongPassphrase, generator}; +use crate::{Error, Result}; + +const FOREIGN: &[u8] = b"fremd / foreign"; +#[cfg(unix)] +const SECRET: &[u8] = b"geheim, nie verschluesseln / secret, never encrypt"; + +fn pass() -> StrongPassphrase { + generator::generate(&generator::Options::default()).unwrap() +} + +fn encrypt(source: &Path, target: &Path, pass: &StrongPassphrase) -> Result { + let params = kdf::KdfParams { + memory_kib: kdf::MIN_MEMORY_KIB, + iterations: kdf::MIN_ITERATIONS, + parallelism: 1, + }; + let p = Protection::Passphrase { + passphrase: pass, + params, + }; + files::encrypt(source, target, &p) +} + +/// DE: Konkurrierender Prozess: legt `out` (Datei) neben der Temporärausgabe an. +/// EN: Concurrent process: creates `out` (file) next to the temporary output. +fn create_foreign_file(temp: &Path) { + std::fs::write(temp.parent().unwrap().join("out"), FOREIGN).unwrap(); +} + +/// DE: Konkurrierender Prozess: legt `out` als leeren Ordner an. EN: Creates `out` as empty dir. +#[cfg(unix)] +fn create_foreign_dir(temp: &Path) { + std::fs::create_dir(temp.parent().unwrap().join("out")).unwrap(); +} + +/// DE: Konkurrierender Prozess: tauscht `src/a` gegen einen Symlink auf `geheim`. +/// EN: Concurrent process: swaps `src/a` for a symlink to `geheim`. +#[cfg(unix)] +fn swap_source_for_symlink(temp: &Path) { + let root = temp.parent().unwrap(); + std::fs::remove_file(root.join("src/a")).unwrap(); + std::os::unix::fs::symlink(root.join("geheim"), root.join("src/a")).unwrap(); +} + +/// DE: Verschlüsselte Datei `archive.pqkf` aus einer Datei bzw. einem Ordner in `root`. +/// EN: Encrypted `archive.pqkf` from a file or a directory in `root`. +fn sealed(root: &Path, tree: bool, pass: &StrongPassphrase) -> std::path::PathBuf { + let src = root.join("src"); + if tree { + std::fs::create_dir(&src).unwrap(); + std::fs::write(src.join("a"), b"inhalt / content").unwrap(); + } else { + std::fs::write(&src, b"inhalt / content").unwrap(); + } + let archive = root.join("archive.pqkf"); + encrypt(&src, &archive, pass).unwrap(); + archive +} + +#[test] +fn file_target_created_before_publish_is_never_overwritten() { + let root = tempfile::tempdir().unwrap(); + let pass = pass(); + let archive = sealed(root.path(), false, &pass); + let out = root.path().join("out"); + let scope = Scope::new( + root.path(), + plan(Point::BeforePublish, Action::Run(create_foreign_file)), + ); + let result = files::decrypt(&archive, &out, &Unlock::Passphrase(pass.as_ref())); + scope.finish(); + assert_eq!(result, Err(Error::Io(ErrorKind::AlreadyExists))); + assert_eq!(std::fs::read(&out).unwrap(), FOREIGN); + assert_no_temps(root.path()); +} + +#[test] +#[ignore = "bekannte Lücke / known gap #338 PR 2: Rückfall ohne Hardlinks ersetzt / fallback replaces"] +fn fallback_without_hard_links_never_overwrites() { + let root = tempfile::tempdir().unwrap(); + let pass = pass(); + let archive = sealed(root.path(), false, &pass); + let out = root.path().join("out"); + let plans = vec![ + plan( + Point::BeforeHardLink, + Action::Fail(Failure::Kind(ErrorKind::Unsupported)), + ), + plan(Point::BeforeRename, Action::Run(create_foreign_file)), + ]; + let scope = Scope::sequence(root.path(), plans); + let result = files::decrypt(&archive, &out, &Unlock::Passphrase(pass.as_ref())); + scope.finish(); + assert_eq!(result, Err(Error::Io(ErrorKind::AlreadyExists))); + assert_eq!(std::fs::read(&out).unwrap(), FOREIGN); +} + +#[test] +#[cfg(unix)] +#[ignore = "bekannte Lücke / known gap #338 PR 2: Ordner per Prüfen + Umbenennen / check + rename"] +fn directory_target_created_before_rename_is_not_replaced() { + let root = tempfile::tempdir().unwrap(); + let pass = pass(); + let archive = sealed(root.path(), true, &pass); + let out = root.path().join("out"); + let scope = Scope::new( + root.path(), + plan(Point::BeforeRename, Action::Run(create_foreign_dir)), + ); + let result = files::decrypt(&archive, &out, &Unlock::Passphrase(pass.as_ref())); + scope.finish(); + assert_eq!(result, Err(Error::Io(ErrorKind::AlreadyExists))); + assert!( + std::fs::read_dir(&out).unwrap().next().is_none(), + "fremder Ordner ersetzt / replaced" + ); +} + +#[test] +#[cfg(unix)] +#[ignore = "bekannte Lücke / known gap #338 PR 4: Quelle folgt Symlink nach dem Durchlauf / follows"] +fn source_swapped_for_symlink_is_never_read() { + let root = tempfile::tempdir().unwrap(); + let pass = pass(); + std::fs::write(root.path().join("geheim"), SECRET).unwrap(); + let src = root.path().join("src"); + std::fs::create_dir(&src).unwrap(); + std::fs::write(src.join("a"), vec![b'x'; SECRET.len()]).unwrap(); + let archive = root.path().join("archive.pqkf"); + let run = Action::Run(swap_source_for_symlink); + let scope = Scope::new(root.path(), plan(Point::AfterTempCreate, run)); + let result = encrypt(&src, &archive, &pass); + scope.finish(); + let leaked = result.is_ok() && { + let out = root.path().join("check"); + files::decrypt(&archive, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); + std::fs::read(out.join("a")).unwrap() == SECRET + }; + assert!( + !leaked, + "Ziel des Symlinks verschlüsselt / symlink target encrypted" + ); + assert!(result.is_err() && !archive.exists()); +} From deca57ee271553c40b0d8437c602f8ece4c015ef Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:07:37 +0100 Subject: [PATCH 08/26] Prelock shared page registry records and guard ownership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Gewöhnliche BTree-Records durch vor Befüllung gesperrte Kontroll-/Node-Arenen ersetzen; Wachstum zwischen gesperrten Zielen, Wipe vor Unlock, echte Kernel-Fehler/Poisoning fail-closed. Root-forbid bleibt; zwei unsafe Send/Sync-Impls entfallen, eng geprüfte reine Windows-Testabfrage ergänzt. EN: Preserve overlap/refcounts/prefix ownership and exact final kernel baseline; no recursive bootstrap, fallback, version upgrade or host-policy change. Source-bound full suites:280 API/250 no-API groups,31 integrations; final four strict lints and16 hardening groups per feature configuration include actual own-unmap release failure. Complete source archive verified, three unapproved Windows token prototype files excluded. Joint R7/R8 remains Draft pending native final acceptance and other plan rows. --- Cargo.lock | 2 + Cargo.toml | 2 +- docs/MEMORY_HARDENING.md | 10 + docs/ROADMAP.md | 8 + docs/SPEC.en.md | 7 + docs/SPEC.md | 7 + docs/security/LOCK_REGISTRY_VALIDATION.md | 112 ++++++++ platform/pqkeep-platform/Cargo.toml | 9 +- platform/pqkeep-platform/src/lib.rs | 3 + .../pqkeep-platform/src/memory_fixture.rs | 73 ++++++ src/hardening/lock_registry.rs | 238 +++++++++++++++++ src/hardening/lock_registry_storage.rs | 224 ++++++++++++++++ src/hardening/lock_registry_tests.rs | 242 ++++++++++++++++++ src/hardening/memlock.rs | 63 ++--- src/hardening/memlock_denial_tests.rs | 65 +++-- src/hardening/memlock_tests.rs | 6 +- src/hardening/mod.rs | 2 + vendor/patches-sha256.json | 6 +- vendor/region-4.0.1/Cargo.toml | 4 + vendor/region-4.0.1/src/lock.rs | 66 ++++- 20 files changed, 1068 insertions(+), 81 deletions(-) create mode 100644 docs/security/LOCK_REGISTRY_VALIDATION.md create mode 100644 platform/pqkeep-platform/src/memory_fixture.rs create mode 100644 src/hardening/lock_registry.rs create mode 100644 src/hardening/lock_registry_storage.rs create mode 100644 src/hardening/lock_registry_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 23d7eb3..ce2874a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -939,6 +939,7 @@ name = "pqkeep-platform" version = "0.1.0" dependencies = [ "windows-sys", + "zeroize", ] [[package]] @@ -1059,6 +1060,7 @@ dependencies = [ "libc", "mach2", "windows-sys", + "zeroize", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1b6e527..d320c0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,7 +142,7 @@ pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform" } [target.'cfg(windows)'.dev-dependencies] # DE: Nur sichere eigene Testfixture, nicht im normalen Produktionsbaum. # EN: Safe own-console fixture only, excluded from normal production features. -pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform", features = ["native-input-fixture"] } +pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform", features = ["native-input-fixture", "native-memory-fixture"] } # DE: `api` (Standard) baut den REST-Server `pqkeep serve` ein. Ohne das Feature # (`--no-default-features`) entsteht eine reine CLI ohne Netzwerkcode. diff --git a/docs/MEMORY_HARDENING.md b/docs/MEMORY_HARDENING.md index 8ec20c7..fa6635a 100644 --- a/docs/MEMORY_HARDENING.md +++ b/docs/MEMORY_HARDENING.md @@ -2,6 +2,16 @@ **DE** | [EN](#english) +DE: PR355 ersetzt die gewöhnlichen gemeinsamen Seiten-/Referenz-/Guard-Records +durch vorab gesperrte Kontroll- und Node-Arenen. Zusätzlicher Registerspeicher +gehört zum nativen Sperrbedarf; die bestehende Statistik zählt weiterhin Seiten +lebender Secret-Bereiche. Nach dem letzten Owner sämtliche Arena-/Kontrollsperren +freigeben; kein permanenter Bootstrap. Reale native Gesamtabnahme noch offen. +EN: No unprotected registry fallback or recursive bootstrap. Preserve overlap, +partial denial and exact final kernel baseline. Two unsafe Send/Sync impls removed; +the narrow native Windows observer is test-only. See +[registry lifetime and FFI review](security/LOCK_REGISTRY_VALIDATION.md). + DE: Feste HKDF/HMAC-Zustände und -Scratch sowie Archiv-Framing/Eintragsdatensätze verwenden SecretWorkspace: Der innere Pufferdescriptor wird vor Allokation und privater Befüllung stabil gesperrt. Hashausgabe, HKDF-PRK und -Ergebnis entstehen diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 5518c21..a2e1542 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -174,3 +174,11 @@ Sperrregister und Prozess-/Helper-Gesamtabnahme bleiben offen. EN: Protected framing and retained stream/holdback counters in the same joint PR; fallible Rust trailer API, unchanged wire bytes. No whole-row completion claim. See [scope and migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). + +DE: Im selben Draft folgt das vor Befüllung gesperrte gemeinsame Seitenregister: +Kontroll-/Node-Arenen, fallibles Wachstum, geprüfte Überlappung/Teilsperre und +Verweigerung weiterer Aufnahme nach echtem Release-Fehler oder Poisoning. +EN: Protected shared registry implemented and locally source-checked; native final +acceptance remains pending. Two unnecessary unsafe Send/Sync impls removed; +read-only native Windows observer is test-only. Other R7/R8 rows stay open. +See [registry contract and evidence](security/LOCK_REGISTRY_VALIDATION.md). diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 80679e4..b2cca9a 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -20,6 +20,13 @@ > Wire format unchanged; reports/transport and other R7/R8 paths remain open. > [Scope and API migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). +> R8 lock registry in PR355: separate control/node arenas locked before address/ +> reference ingress; growth between locked targets, wipe before unlock. No ordinary +> BTree records or recursive secret-lock bootstrap. Preserve root forbid; remove +> two unsafe Send/Sync impls. Narrow reviewed read-only Windows test observer is +> separate from production features. Final acceptance remains pending. +> [Registry contract and validation scope](security/LOCK_REGISTRY_VALIDATION.md). + > **Translation note:** This is the English translation of [`SPEC.md`](SPEC.md) (German), version > 2.22. Both versions are maintained together; every change to one is made to the other in the > same pull request. If they ever contradict each other, the German version applies until the diff --git a/docs/SPEC.md b/docs/SPEC.md index 33374b3..fea6464 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -20,6 +20,13 @@ > Wire-Format unverändert; Berichte/Transport und weitere R7/R8-Pfade bleiben offen. > [Umfang und API-Migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). +> R8-Sperrregister in PR355: Getrennte Kontroll-/Node-Arenen vor Adress- und +> Referenzeintritt sperren; Wachstum zwischen gesperrten Zielen, Wipe vor Unlock. +> Keine gewöhnlichen BTree-Records und keine rekursive Secret-Sperre im Bootstrap. +> Root-forbid erhalten; zwei unsafe Send/Sync-Impls entfallen. Eng geprüfte reine +> Windows-Testabfrage getrennt vom Produktionsfeature. Gesamtabnahme noch offen. +> [Registervertrag und Prüfumfang](security/LOCK_REGISTRY_VALIDATION.md). + > **English translation:** [`SPEC.en.md`](SPEC.en.md) – beide Fassungen werden im selben Pull Request gemeinsam geändert; bei Widersprüchen gilt bis zur Korrektur die deutsche. / Both versions are changed together in the same pull request; in case of contradiction the German one applies until fixed. > Änderung v2.19 (22.11.2026, Eigentümerauftrag zur autonomen Sicherheitsbehebung bis main): Secret-Speicher einschließlich KDF-/HKDF-Arbeitspuffern zwingend sperren; Fehler statt ungesperrtem Fallback, begrenzte Eingaben und sichere Freigabe. Keine Änderung von Format-/Ableitungsbytes. Details: [LOCKED_SECRETS.md](security/LOCKED_SECRETS.md). diff --git a/docs/security/LOCK_REGISTRY_VALIDATION.md b/docs/security/LOCK_REGISTRY_VALIDATION.md new file mode 100644 index 0000000..652048c --- /dev/null +++ b/docs/security/LOCK_REGISTRY_VALIDATION.md @@ -0,0 +1,112 @@ +# Protected lock registry / Geschützte Sperrbuchhaltung + +DE: M6-Baustein des ausdrücklich freigegebenen gemeinsamen R7/R8-Plans in +Draft355. Lokale Implementierung; vollständige native Abnahme dieses Bausteins +und übrige Planzeilen bleiben erforderlich. Kein R7/R8-Gesamtabschluss. +EN: Shared bookkeeping component, not a claim of full process/metadata protection. + +## Ownership and lifetime / Eigentum und Lebensdauer + +DE: Die gewöhnlichen BTreeMap-Knoten mit Seitenadressen, Referenzzählern und +Sperr-Guards entfallen. Ein seitendisjunkter statischer Kontrollbereich enthält +Mutex, Hash-Wurzeln und Arenadescriptoren. Der Kontrollbereich wird direkt mit +region gesperrt, bevor private Records befüllt werden; keine rekursive Nutzung +von SecretState/SecretBytes zum Bootstrap des eigenen Registers. +EN: Fixed alignment supports actual page sizes dividing64KiB; unsupported geometry +fails closed. Control and arena allocations cannot share OS pages with separately +managed data allocations. Statistics alone do not allocate or bootstrap locks. + +DE: Fallibles Arenawachstum: neue Nodes ausschließlich öffentlich leer anlegen, +gesamte neue Allocation sperren, dann skalare Felder zwischen geliehenen Nodes +übertragen und Guard-Eigentum feldweise tauschen. Keine private Guard-Gesamtkopie +in gewöhnliche Container. Alte Felder und gesamtes Allocation-Padding vor Unlock +löschen. Kein fixer Gesamtseiten-Cap; arithmetische/allokative/native Fehler +verweigern weitere Aufnahme ohne Verlust bestehender Datensperren. +EN: Overlap reference counts and the successful contiguous prefix retain their +previous semantics. Removed page records are wiped before native data unlock. +Free nodes may be reused while the arena remains locked. After the final owner, +wipe/free the entire arena and release the control lock; no permanent bootstrap +allocation remains locked. Tests require the exact kernel VmLck baseline again. + +DE: Ein vergifteter Mutex erlaubt nur Bereinigung bestehenden Eigentums, keine +neuen Secret-Sperren. Ein beschädigter Registerzustand wird nicht stillschweigend +als gesund übernommen. Noch lebende Guards werden bei Invariantenfehlern nicht +pauschal freigegeben. Native Release-Fehler sperren weitere Aufnahme und werden +als fehlgeschlagene Sperrverwaltung gezählt. +EN: Existing `LockStats.locked_pages` continues to count pages owned by secret +ranges, preserving API semantics. Locked bookkeeping is additional memory, included +in internal native capacity planning. Arena capacity may remain until the last +owner; data records are cleared on each release. Budget failure has no ordinary +memory fallback and never raises host limits or privileges. + +## Safe code and narrow FFI / Sicherer Code und enge FFI + +DE: Root bleibt forbid(unsafe_code). region::LockGuard hält numerische OS-Adressen +statt Rust-Raw-Pointern; beide bisherigen unsafe Send/Sync-Implementierungen +entfallen. Die Adresse wird niemals in Rust dereferenziert. Öffentlich leere +Guards lassen sich direkt in geschütztem Speicher befüllen, eigenes Eigentum +fallibel freigeben und feldweise tauschen. Release löscht die tatsächlichen +gespeicherten Wörter volatil vor dem nativen Unlock. Es entsteht keine sichere +API zum beliebigen Unlock fremder Spannen; das bestehende unsafe unlock bleibt +eine getrennte unbenutzte Fremd-Caller-Grenze. +EN: Reuse the already locked zeroize1.9.2 dependency, MSRV1.85, Apache-2.0/MIT. +No package version/source upgrade or installation. Update exact region patch +inventory only, without modifying upstream provenance or validation rules. + +DE: Ein einzelner neuer notwendiger FFI-Block ist ausschließlich Teil der nativen +Windows-Testfixture, nicht des normalen Produktionsfeatures. K32QueryWorkingSetEx +liest Seiteneigenschaften ausschließlich des eigenen Prozesses. Der Caller legt +den vollständigen öffentlich leeren Query-Record in SecretState ab, bevor eine +Adresse eingeht. repr(C), zwei initialisierte ABI-Wörter, statisch gleiche Größe/ +Ausrichtung wie der SDK-Typ, exklusiv lebende Ausgabe über genau dessen Größe; +keine Pointeraufbewahrung, kein Rust-Dereferenzieren, kein Lesen von Seiteninhalten. +EN: Both Valid and Locked must be set; the locked bit has no meaning if Valid is +clear. The test fixture checks actually locked and unlocked owned pages, +including guard transfers, and queries each registry/control page. No policy, +token, account, host, Registry or process rights mutation by this observer. + +Sources / Quellen: +- [QueryWorkingSetEx](https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-queryworkingsetex) +- [Valid/Locked bit layout](https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_ex_block) + +## Required evidence / Erforderliche Belege + +DE: Bestehende Überlappungs-, Sättigungs-, Prefix-, Konkurrenz-, Unwind- und +Double-Zeroize-Fälle erhalten. Neue begrenzte eigene Kinder prüfen tatsächliches +Wachstum/Wiederverwendung, reale geschützte Node-/Kontrollseiten und Poison- +Verweigerung. Der echte Linux-Teilsperrtest berücksichtigt die zusätzliche +Buchhaltung anhand tatsächlicher Kernelwerte: weiterhin erster Zielseite Erfolg, +zweiter Seite Verweigerung, unabhängiger Owner unverändert und exakter vollständiger +Kernel-Rücklauf. Elternlimit unverändert; keine Nullbudget-/Prefix-Abschwächung. +EN: Full source-bound lint/tests on both feature configurations and native Linux, +ARM64/Windows, plus strict provenance/audit/fuzz, remain mandatory. Defining a test +or successful cross-compilation alone does not claim native execution. Caller- +owned buffers, allocator/OS internals and transient compiler/register scalar copies +remain explicit limits; known ordinary application records are not renamed as +compiler limits. Other native path/report/helper/host rows remain open. + +DE: Zusätzlicher echter Release-Fehlerfall: Nur die eigene öffentliche Testabbildung +vor dem Guard freigeben. Der anschließende native Unlock muss fehlschlagen; weitere +Secret-Aufnahme wird verweigert, ein unabhängiger lebender Owner bleibt tatsächlich +gesperrt. Danach alle übrigen eigenen Sperren bereinigen und Kernel-Baseline prüfen. +EN: Bounded child only, no private test contents or foreign mappings; no mocked +release success. The error counter increases and no live owner's lock is sacrificed. + +DE: Lokaler Quellenstand v1: 865 Rust-/Manifestdateien über alle14 Befehle +bytegleich. Vier strenge All-Target-Clippy-Konfigurationen (Linux/Windows-GNU, +mit/ohne API), direktes region-Clippy, 280 Bibliothekstests mit API, 250 ohne und31 +Integrationsfälle erfolgreich; Format/Limits/Herkunft/Angriffsmatrix/Diff grün. +EN: Explicitly ignored child entry points run through their actual parents; +separately known ignored #338 race gaps stay documented and are not counted as +executed successes. Source-delta proof for the later additional release-error +test confirms unchanged production code; two bilingual comment-only updates. +Native exact-head acceptance of the complete new registry component remains pending. + +DE: Letzter lokaler v2-Stand nach dem zusätzlichen echten Release-Fehlerfall: +alle zwölf Prüfungen erfolgreich, erneut865 Quellen vor/nach dem Lauf identisch. +Vier strenge Clippy-Konfigurationen, je16 Härtungsgruppen mit/ohne API samt den +tatsächlich aufgerufenen begrenzten Kindern; Format/Limits/Herkunft/Matrix/Diff grün. +EN: `registry-release-test-source-delta-proof.json` binds unchanged production code +to the broad v1 suites; only the new test/parent invocation and two comment-only +files differ. `protected-registry-v2.json` binds the final focused checks to exact +source hashes. No new unapproved token/thread experiment was executed or published. diff --git a/platform/pqkeep-platform/Cargo.toml b/platform/pqkeep-platform/Cargo.toml index 23ad80b..6b9093a 100644 --- a/platform/pqkeep-platform/Cargo.toml +++ b/platform/pqkeep-platform/Cargo.toml @@ -8,7 +8,12 @@ publish = false description = "Narrow synchronous platform adapters for PQKeep" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] } +windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_UI_Input_KeyboardAndMouse"] } + +[target.'cfg(windows)'.dependencies.zeroize] +version = "1.9.1" +default-features = false +optional = true [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "=0.61.2", features = ["Win32_Security", "Win32_Security_Authorization"] } @@ -16,6 +21,8 @@ windows-sys = { version = "=0.61.2", features = ["Win32_Security", "Win32_Securi [features] # DE/EN: Ausschließlich feste öffentliche Testereignisse / fixed public test events only. native-input-fixture = [] +# DE/EN: Nur lesende eigene Seitensperrprobe / read-only own page-lock fixture only. +native-memory-fixture = ["dep:zeroize"] # DE/EN: Nur ausdrücklich gestartete öffentliche Prozessprobe / explicitly run public probe only. process-access-probe = [] diff --git a/platform/pqkeep-platform/src/lib.rs b/platform/pqkeep-platform/src/lib.rs index 08d7c83..b6e2521 100644 --- a/platform/pqkeep-platform/src/lib.rs +++ b/platform/pqkeep-platform/src/lib.rs @@ -23,3 +23,6 @@ pub use console_input_record::CONSOLE_INPUT_STORAGE; #[cfg(all(windows, feature = "native-input-fixture"))] pub mod input_fixture; + +#[cfg(all(windows, feature = "native-memory-fixture"))] +pub mod memory_fixture; diff --git a/platform/pqkeep-platform/src/memory_fixture.rs b/platform/pqkeep-platform/src/memory_fixture.rs new file mode 100644 index 0000000..81729db --- /dev/null +++ b/platform/pqkeep-platform/src/memory_fixture.rs @@ -0,0 +1,73 @@ +//! DE: Ausschließlich lesende eigene Windows-Seitensperrprobe für native Tests. +//! EN: Read-only own Windows page-lock observation for native tests only. + +use std::io; +use windows_sys::Win32::System::{ + ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}, + Threading::GetCurrentProcess, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +/// DE: Öffentlich leer konstruieren, vor der ersten Abfrage im Caller sperren. +/// EN: Construct public-empty and lock in the caller before the first query. +/// No Clone/Debug; the caller owns the stable protected query storage. +#[repr(C)] +pub struct MemoryLockQuery { + address: usize, + flags: usize, +} + +// DE: Zwei native ABI-Wörter, kein Rust-Dereferenzieren der abgefragten Adresse. +// EN: Two native ABI words; Rust never dereferences the queried numeric address. +const _: () = + assert!(size_of::() == size_of::()); +const _: () = + assert!(align_of::() == align_of::()); + +impl MemoryLockQuery { + /// DE: Nur öffentliche Anfangswerte. EN: Only public initial values. + #[must_use] + pub const fn empty() -> Self { + Self { + address: 0, + flags: 0, + } + } + + /// DE: Tatsächlichen Valid-/Locked-Status einer eigenen Seite lesen. + /// EN: Read the actual Valid/Locked status of one own-process page. + /// + /// # Errors + /// DE/EN: Native Abfrageverweigerung / native query refusal. + pub fn is_locked(&mut self, address: usize) -> io::Result { + self.address = address; + self.flags.zeroize(); + let size = u32::try_from(size_of::()).map_err(|_| io::ErrorKind::InvalidInput)?; + // DE: Initialisierte, ABI-geprüfte Wörter im exklusiven lebenden Caller-Record; + // nur eigene Seiteneigenschaften, keine Inhalte und keine Pointeraufbewahrung. + // SAFETY: repr(C), compile-checked ABI and fully initialized integer words. + // The exclusive live request is writable for exactly size bytes. The API + // queries only this process, retains no pointer and reads no page contents. + let ok = unsafe { + K32QueryWorkingSetEx(GetCurrentProcess(), std::ptr::from_mut(self).cast(), size) + }; + if ok == 0 { + return Err(io::Error::last_os_error()); + } + // DE/EN: Locked ist nur bei Valid gültig / Locked is meaningful only if Valid. + Ok(self.flags & 1 != 0 && self.flags & (1 << 22) != 0) + } +} + +impl Zeroize for MemoryLockQuery { + fn zeroize(&mut self) { + self.address.zeroize(); + self.flags.zeroize(); + } +} +impl Drop for MemoryLockQuery { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for MemoryLockQuery {} diff --git a/src/hardening/lock_registry.rs b/src/hardening/lock_registry.rs new file mode 100644 index 0000000..8c8de87 --- /dev/null +++ b/src/hardening/lock_registry.rs @@ -0,0 +1,238 @@ +//! DE: Gemeinsame Sperrbuchhaltung vor Adress-/Referenz-Eintritt selbst sperren. +//! EN: Lock shared bookkeeping before address/reference ingress, without recursion. + +#[cfg(test)] +use super::lock_registry_storage::Node; +use super::lock_registry_storage::{ALIGNMENT, Storage}; +use region::LockGuard; +use std::sync::{ + Mutex, MutexGuard, + atomic::{AtomicBool, Ordering}, +}; +use zeroize::Zeroize; + +const BUCKETS: usize = 2048; + +#[repr(align(65536))] +struct Control(Mutex); + +static CONTROL: Control = Control(Mutex::new(Registry::new())); +static POISONED: AtomicBool = AtomicBool::new(false); + +#[cfg(test)] +#[path = "lock_registry_tests.rs"] +mod tests; + +pub(super) fn registry() -> MutexGuard<'static, Registry> { + match CONTROL.0.lock() { + Ok(guard) => guard, + Err(error) => { + // DE: Nur bestehendes Eigentum bereinigen, keine neuen Secrets annehmen. + // EN: Allow cleanup of existing ownership, never accept new secrets. + POISONED.store(true, Ordering::Relaxed); + error.into_inner() + } + } +} + +pub(super) struct Registry { + storage: Storage, + buckets: [usize; BUCKETS], + control: LockGuard, + len: usize, + broken: bool, +} + +impl Registry { + const fn new() -> Self { + Self { + storage: Storage::new(), + buckets: [0; BUCKETS], + control: LockGuard::empty(), + len: 0, + broken: false, + } + } + + pub(super) fn len(&self) -> usize { + self.len + } + #[cfg(all(test, target_os = "linux"))] + pub(super) fn is_empty(&self) -> bool { + self.len == 0 + } + + pub(super) fn prepare(&mut self, extra: usize) -> bool { + if self.broken || !self.storage.healthy() || POISONED.load(Ordering::Relaxed) { + return false; + } + let page = region::page::size(); + if page > ALIGNMENT || !ALIGNMENT.is_multiple_of(page) { + return false; + } + let budget = self + .len + .checked_mul(page) + .and_then(|n| n.checked_add(extra)) + .and_then(|n| n.checked_add(size_of::())) + .and_then(|n| n.checked_add(self.storage.budget_for(extra / page)?)); + if budget.is_none_or(|n| region::prepare_lock_capacity(n).is_err()) { + return false; + } + self.control.is_active() + || self + .control + .acquire(std::ptr::from_ref(&CONTROL), size_of::()) + .is_ok() + } + + fn bucket(page: usize) -> usize { + (page / region::page::size()) % BUCKETS + } + + fn find(&self, page: usize) -> Result<(usize, usize), ()> { + let (mut index, mut previous) = (self.buckets[Self::bucket(page)], 0); + for _ in 0..self.len { + if index == 0 { + return Ok((0, previous)); + } + let node = self.storage.node(index).ok_or(())?; + if node.users == 0 || !node.guard.is_active() { + return Err(()); + } + if node.address == page { + return Ok((index, previous)); + } + previous = index; + index = node.next; + } + if index == 0 { + Ok((0, previous)) + } else { + Err(()) + } + } + + pub(super) fn contains_key(&self, page: usize) -> bool { + self.find(page).is_ok_and(|(index, _)| index != 0) + } + + pub(super) fn metadata_contains(&self, address: usize) -> bool { + let base = std::ptr::from_ref(&CONTROL).addr(); + (self.control.is_active() && (base..base + size_of::()).contains(&address)) + || self.storage.contains(address) + } + + #[cfg(test)] + pub(super) fn get(&self, page: usize) -> Option<&Node> { + self.storage.node(self.find(page).ok()?.0) + } + + #[cfg(test)] + pub(super) fn get_mut(&mut self, page: usize) -> Option<&mut Node> { + let index = self.find(page).ok()?.0; + self.storage.node_mut(index) + } + + pub(super) fn acquire_page(&mut self, page: usize, size: usize) -> bool { + let Ok((index, _)) = self.find(page) else { + self.broken = true; + return false; + }; + if index != 0 { + let Some(node) = self.storage.node_mut(index) else { + self.broken = true; + return false; + }; + let Some(count) = node.users.checked_add(1) else { + return false; + }; + node.users = count; + return true; + } + let budget = self + .len + .checked_add(1) + .and_then(|n| n.checked_mul(size)) + .and_then(|n| n.checked_add(size_of::())); + if budget.is_none_or(|n| !self.storage.extend(n)) { + return false; + } + let index = self.storage.free; + let Some(node) = self.storage.node_mut(index) else { + self.broken = true; + return false; + }; + if node + .guard + .acquire(std::ptr::without_provenance::(page), size) + .is_err() + { + return false; + } + self.storage.free = node.next; + let Some(node) = self.storage.node_mut(index) else { + self.broken = true; + return false; + }; + node.address = page; + node.users = 1; + node.next = self.buckets[Self::bucket(page)]; + self.buckets[Self::bucket(page)] = index; + self.len += 1; + true + } + + pub(super) fn release_page(&mut self, page: usize) -> bool { + let Ok((index, previous)) = self.find(page) else { + self.broken = true; + return false; + }; + let Some(node) = self.storage.node_mut(index) else { + self.broken = true; + return false; + }; + if node.users > 1 { + node.users -= 1; + return true; + } + let next = node.next; + if previous == 0 { + self.buckets[Self::bucket(page)] = next; + } else if let Some(node) = self.storage.node_mut(previous) { + node.next = next; + } else { + self.broken = true; + return false; + } + let free = self.storage.free; + let Some(node) = self.storage.node_mut(index) else { + self.broken = true; + return false; + }; + node.address.zeroize(); + node.users.zeroize(); + node.next.zeroize(); + let success = node.guard.release().is_ok(); + node.next = free; + self.storage.free = index; + self.len -= 1; + self.broken |= !success; + success + } + + pub(super) fn finish_release(&mut self) -> bool { + if self.len != 0 || !self.control.is_active() { + return true; + } + if !self.storage.clear() { + self.broken = true; + return false; + } + self.buckets.zeroize(); + self.len.zeroize(); + let success = self.control.release().is_ok(); + self.broken |= !success; + success + } +} diff --git a/src/hardening/lock_registry_storage.rs b/src/hardening/lock_registry_storage.rs new file mode 100644 index 0000000..dc0a46c --- /dev/null +++ b/src/hardening/lock_registry_storage.rs @@ -0,0 +1,224 @@ +//! DE: Vor Befüllung gesperrte, fallibel wachsende Registerarena ohne Rekursion. +//! EN: Prelocked fallibly growing registry arena without recursive memory locking. + +use region::LockGuard; +use zeroize::Zeroize; + +pub(super) const ALIGNMENT: usize = 65536; +const NODES: usize = 256; + +pub(super) struct Node { + pub(super) address: usize, + pub(super) users: usize, + pub(super) next: usize, + pub(super) guard: LockGuard, +} + +impl Node { + const fn empty() -> Self { + Self { + address: 0, + users: 0, + next: 0, + guard: LockGuard::empty(), + } + } + + fn transfer_to(&mut self, target: &mut Self) { + target.address = self.address; + self.address.zeroize(); + target.users = self.users; + self.users.zeroize(); + target.next = self.next; + self.next.zeroize(); + self.guard.swap(&mut target.guard); + } +} + +impl Drop for Node { + fn drop(&mut self) { + self.address.zeroize(); + self.users.zeroize(); + self.next.zeroize(); + } +} + +#[repr(align(65536))] +struct Chunk([Node; NODES]); + +impl Chunk { + const EMPTY: Self = Self([const { Node::empty() }; NODES]); + fn empty() -> Self { + Self::EMPTY + } +} + +pub(super) struct Storage { + chunks: Vec, + pending: Vec, + guard: LockGuard, + pending_guard: LockGuard, + pub(super) free: usize, + broken: bool, +} + +impl Storage { + pub(super) const fn new() -> Self { + Self { + chunks: Vec::new(), + pending: Vec::new(), + guard: LockGuard::empty(), + pending_guard: LockGuard::empty(), + free: 0, + broken: false, + } + } + + pub(super) fn node(&self, index: usize) -> Option<&Node> { + let index = index.checked_sub(1)?; + self.chunks.get(index / NODES)?.0.get(index % NODES) + } + + pub(super) fn node_mut(&mut self, index: usize) -> Option<&mut Node> { + let index = index.checked_sub(1)?; + self.chunks.get_mut(index / NODES)?.0.get_mut(index % NODES) + } + + pub(super) fn budget_for(&self, extra_pages: usize) -> Option { + let extra_chunks = extra_pages.checked_add(NODES - 1)? / NODES; + self.chunks + .capacity() + .checked_add(extra_chunks)? + .checked_next_power_of_two()? + .checked_mul(2)? + .checked_mul(size_of::()) + } + + pub(super) fn locked_bytes(&self) -> usize { + if self.guard.is_active() { + self.chunks.capacity() * size_of::() + } else { + 0 + } + } + + pub(super) fn healthy(&self) -> bool { + !self.broken + } + + #[cfg(test)] + pub(super) fn visit_storage(&self, mut check: impl FnMut(usize, usize) -> bool) -> bool { + (!self.guard.is_active() || check(self.chunks.as_ptr().addr(), self.locked_bytes())) + && self.chunks.iter().flat_map(|chunk| &chunk.0).all(|node| { + if node.users == 0 { + node.address == 0 && !node.guard.is_active() + } else { + node.guard.is_active() + } + }) + } + + pub(super) fn contains(&self, address: usize) -> bool { + let base = self.chunks.as_ptr().addr(); + self.guard.is_active() && (base..base + self.locked_bytes()).contains(&address) + } + + pub(super) fn extend(&mut self, data_and_control_bytes: usize) -> bool { + if self.broken { + return false; + } + if self.free != 0 { + return true; + } + let old = self.chunks.len(); + let Some(goal) = (if old == 0 { + Some(1) + } else { + old.checked_mul(2) + }) else { + return false; + }; + let Some(base) = old.checked_mul(NODES) else { + return false; + }; + let Some(last) = goal.checked_mul(NODES) else { + return false; + }; + if !self.prepare_growth(goal, data_and_control_bytes) { + return false; + } + for (source, target) in self.chunks.iter_mut().zip(&mut self.pending) { + for (source, target) in source.0.iter_mut().zip(&mut target.0) { + source.transfer_to(target); + } + } + // DE: Alte Felder und Padding unter ihrer noch gehaltenen Sperre löschen. + // EN: Wipe old fields and padding while their lock is still owned. + self.chunks.clear(); + self.chunks.spare_capacity_mut().zeroize(); + let released = self.guard.release().is_ok(); + self.chunks = Vec::new(); + std::mem::swap(&mut self.chunks, &mut self.pending); + self.guard.swap(&mut self.pending_guard); + self.broken |= !released; + for index in base + 1..=last { + if let Some(node) = self.node_mut(index) { + node.next = if index == last { 0 } else { index + 1 }; + } else { + self.broken = true; + return false; + } + } + self.free = base + 1; + released + } + + fn prepare_growth(&mut self, goal: usize, data_and_control_bytes: usize) -> bool { + let Some(extra) = goal.checked_sub(self.pending.len()) else { + return false; + }; + if self.pending.try_reserve_exact(extra).is_err() { + return false; + } + while self.pending.len() < goal { + self.pending.push(Chunk::empty()); + } + let Some(bytes) = self.pending.capacity().checked_mul(size_of::()) else { + return false; + }; + let budget = data_and_control_bytes + .checked_add(self.locked_bytes()) + .and_then(|n| n.checked_add(bytes)); + if budget.is_none_or(|n| region::prepare_lock_capacity(n).is_err()) { + return false; + } + self.pending_guard + .acquire(self.pending.as_ptr(), bytes) + .is_ok() + } + + pub(super) fn clear(&mut self) -> bool { + // DE: Invariantenfehler dürfen keine noch lebende fremde Sperre aufheben. + // EN: Invariant failures must not release another still-live lock. + if self + .chunks + .iter() + .chain(&self.pending) + .flat_map(|chunk| &chunk.0) + .any(|node| node.users != 0 || node.guard.is_active()) + { + return false; + } + self.chunks.clear(); + self.chunks.spare_capacity_mut().zeroize(); + self.pending.clear(); + self.pending.spare_capacity_mut().zeroize(); + let released = self.guard.release().is_ok(); + let pending_released = self.pending_guard.release().is_ok(); + self.chunks = Vec::new(); + self.pending = Vec::new(); + self.free.zeroize(); + self.broken |= !released || !pending_released; + released && pending_released + } +} diff --git a/src/hardening/lock_registry_tests.rs b/src/hardening/lock_registry_tests.rs new file mode 100644 index 0000000..6858e66 --- /dev/null +++ b/src/hardening/lock_registry_tests.rs @@ -0,0 +1,242 @@ +//! DE: Echte Arena-/Kernel-Sperren, Wachstum, Überlappung und Poison-Verweigerung. +//! EN: Actual arena/kernel locks, growth, overlap and refusal after poisoning. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::hardening::memlock::{self, lock_range}; + +#[test] +fn registry_growth_and_poison_run_in_bounded_owned_children() { + for name in [ + "registry_growth_child", + "registry_release_error_child", + "registry_poison_child", + "guard_transfer_child", + ] { + crate::locked_owner_test_support::isolated_test( + &format!("hardening::lock_registry::tests::{name}"), + "PQKEEP_REGISTRY_CHILD", + ); + } +} + +#[cfg(target_os = "linux")] +fn kernel_locked_bytes() -> u64 { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024 +} + +fn fixture() -> (Vec, usize) { + let page = region::page::size(); + let buffer = vec![0; 360 * page]; + let base = buffer.as_ptr().addr(); + let first = base - base % page + page; + (buffer, first) +} + +fn assert_metadata() { + #[cfg(windows)] + let mut query = crate::crypto::secret_state::SecretState::new( + pqkeep_platform::memory_fixture::MemoryLockQuery::empty(), + ) + .unwrap(); + let reg = registry(); + let mut observed = |base: usize, len: usize| { + (base..base + len) + .step_by(region::page::size()) + .all(|address| { + #[cfg(target_os = "linux")] + { + crate::locked_owner_test_support::own_mapping_locked(address) + } + #[cfg(windows)] + { + query.get_mut().is_locked(address).unwrap() + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = address; + false + } + }) + }; + assert!(reg.control.is_active()); + assert!(observed( + std::ptr::from_ref(&CONTROL).addr(), + size_of::() + )); + assert!(reg.storage.visit_storage(&mut observed)); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn registry_growth_child() { + assert_eq!(std::env::var("PQKEEP_REGISTRY_CHILD").unwrap(), "1"); + #[cfg(target_os = "linux")] + let before = kernel_locked_bytes(); + assert_eq!(memlock::stats().locked_pages, 0); + #[cfg(target_os = "linux")] + assert_eq!(kernel_locked_bytes(), before); + let (_buffer, first) = fixture(); + let page = region::page::size(); + let left = lock_range(first, 300 * page); + assert!(left.complete(first, 300 * page)); + let right = lock_range(first + 150 * page, 200 * page); + assert!(right.complete(first + 150 * page, 200 * page)); + assert_eq!(memlock::stats().locked_pages, 350); + assert_metadata(); + drop(left); + assert_eq!(memlock::stats().locked_pages, 200); + assert!(!memlock::is_locked(first)); + assert!(memlock::is_locked(first + 150 * page)); + let unwind = std::panic::catch_unwind(|| { + let reused = lock_range(first, 20 * page); + assert!(reused.complete(first, 20 * page)); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, 200); + assert_metadata(); + drop(right); + assert_eq!(memlock::stats().locked_pages, 0); + assert!(!registry().control.is_active()); + #[cfg(target_os = "linux")] + assert_eq!(kernel_locked_bytes(), before); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn registry_poison_child() { + assert_eq!(std::env::var("PQKEEP_REGISTRY_CHILD").unwrap(), "1"); + #[cfg(target_os = "linux")] + let before = kernel_locked_bytes(); + let (_buffer, first) = fixture(); + let page = region::page::size(); + let owner = lock_range(first, page); + assert!(owner.complete(first, page)); + let unwind = std::panic::catch_unwind(|| { + let _reg = registry(); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + let refused = lock_range(first + page, page); + assert!(!refused.complete(first + page, page)); + assert!(memlock::is_locked(first)); + drop(refused); + drop(owner); + assert_eq!(memlock::stats().locked_pages, 0); + assert!(!registry().control.is_active()); + #[cfg(target_os = "linux")] + assert_eq!(kernel_locked_bytes(), before); +} + +fn native_locked(address: usize) -> bool { + #[cfg(target_os = "linux")] + { + crate::locked_owner_test_support::own_mapping_locked(address) + } + #[cfg(windows)] + { + let mut query = crate::crypto::secret_state::SecretState::new( + pqkeep_platform::memory_fixture::MemoryLockQuery::empty(), + ) + .unwrap(); + query.get_mut().is_locked(address).unwrap() + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = address; + false + } +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn guard_transfer_child() { + assert_eq!(std::env::var("PQKEEP_REGISTRY_CHILD").unwrap(), "1"); + let (_buffer, first) = fixture(); + let page = region::page::size(); + region::prepare_lock_capacity(4 * ALIGNMENT).unwrap(); + let mut a = LockGuard::empty(); + let mut b = LockGuard::empty(); + a.acquire(std::ptr::without_provenance::(first), page) + .unwrap(); + assert!( + a.acquire(std::ptr::without_provenance::(first + page), page) + .is_err() + ); + assert!(native_locked(first)); + assert!(!native_locked(first + page)); + a.swap(&mut b); + assert!(!a.is_active() && b.is_active()); + a.release().unwrap(); + assert!(native_locked(first)); + b.release().unwrap(); + assert!(!native_locked(first)); + a.acquire(std::ptr::without_provenance::(first), page) + .unwrap(); + b.acquire(std::ptr::without_provenance::(first + page), page) + .unwrap(); + a.swap(&mut b); + a.release().unwrap(); + assert!(native_locked(first) && !native_locked(first + page)); + b.release().unwrap(); + assert!(!native_locked(first)); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn registry_release_error_child() { + assert_eq!(std::env::var("PQKEEP_REGISTRY_CHILD").unwrap(), "1"); + #[cfg(target_os = "linux")] + let before = kernel_locked_bytes(); + let (_buffer, first) = fixture(); + let page = region::page::size(); + let keep = lock_range(first, page); + assert!(keep.complete(first, page)); + #[cfg(windows)] + let mut query = crate::crypto::secret_state::SecretState::new( + pqkeep_platform::memory_fixture::MemoryLockQuery::empty(), + ) + .unwrap(); + let baseline = memlock::stats().locked_pages; + force_owned_unmap_before_release(page); + assert_eq!(memlock::stats().locked_pages, baseline); + assert!(memlock::is_locked(first)); + #[cfg(target_os = "linux")] + assert!(native_locked(first)); + #[cfg(windows)] + assert!(query.get_mut().is_locked(first).unwrap()); + let refused = lock_range(first + page, page); + assert!(!refused.complete(first + page, page)); + drop(refused); + drop(keep); + #[cfg(windows)] + drop(query); + assert_eq!(memlock::stats().locked_pages, 0); + assert!(!registry().control.is_active()); + #[cfg(target_os = "linux")] + assert_eq!(kernel_locked_bytes(), before); +} + +// DE: Absichtlich nur die eigene öffentliche Testabbildung vorzeitig freigeben. +// EN: Deliberately release only our own public test mapping before its guard. +fn force_owned_unmap_before_release(page: usize) { + let mapping = region::alloc(page, region::Protection::READ_WRITE).unwrap(); + let address = mapping.as_ptr::().addr(); + let owner = lock_range(address, page); + assert!(owner.complete(address, page)); + let failures = memlock::stats().failed_attempts; + drop(mapping); + drop(owner); + assert!(memlock::stats().failed_attempts > failures); +} diff --git a/src/hardening/memlock.rs b/src/hardening/memlock.rs index 4183e85..2597463 100644 --- a/src/hardening/memlock.rs +++ b/src/hardening/memlock.rs @@ -9,12 +9,10 @@ //! Locking is per page, not per variable. A page counter prevents releasing one //! secret from unlocking another on the same page. Secret constructors reject incomplete locks. -use std::collections::BTreeMap; use std::ops::Range; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; -use region::LockGuard; +use super::lock_registry::registry; use zeroize::Zeroize; #[cfg(test)] @@ -25,26 +23,16 @@ mod memlock_tests; #[path = "memlock_denial_tests.rs"] mod denial_tests; -/// DE: Gesperrte Seiten: Seitenadresse → (Anzahl Nutzer, Sperre). -/// EN: Locked pages: page address → (number of users, lock). -type Registry = BTreeMap; - -fn registry() -> MutexGuard<'static, Registry> { - static PAGES: OnceLock> = OnceLock::new(); - PAGES - .get_or_init(|| Mutex::new(BTreeMap::new())) - .lock() - .unwrap_or_else(PoisonError::into_inner) -} - static FAILED: AtomicUsize = AtomicUsize::new(0); /// DE: Momentaufnahme des Sperrstatus. EN: Snapshot of the lock status. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LockStats { - /// DE: Aktuell gesperrte Seiten. EN: Currently locked pages. + /// DE: Seiten lebender Secret-Bereiche, ohne die zusätzliche Registerarena. + /// EN: Pages owned by live secret ranges, excluding the additional registry arena. pub locked_pages: usize, - /// DE: Fehlgeschlagene Sperrversuche seit Start. EN: Failed lock attempts since start. + /// DE: Fehler beim Sperren/Freigeben seit Start. + /// EN: Failed lock/release operations since startup. pub failed_attempts: usize, } @@ -74,16 +62,16 @@ impl LockedRange { fn release(&mut self) { let mut reg = registry(); - for page in self.pages.clone().step_by(region::page::size()) { - let remove = reg.get_mut(&page).is_some_and(|entry| { - entry.0 -= 1; - entry.0 == 0 - }); - if remove { - // DE: Entfernen gibt die Sperre frei (Drop von LockGuard). - // EN: Removing releases the lock (drop of LockGuard). - reg.remove(&page); + let mut page = self.pages.start; + while page < self.pages.end { + if !reg.release_page(page) { + FAILED.fetch_add(1, Ordering::Relaxed); } + page += region::page::size(); + } + page.zeroize(); + if !reg.finish_release() { + FAILED.fetch_add(1, Ordering::Relaxed); } // DE: Eigenen Record löschen; temporäre Compiler-/Stackkopien bleiben offen. // EN: Wipe the owned record; temporary compiler/stack copies remain open. @@ -102,22 +90,6 @@ fn page_span(addr: usize, len: usize) -> Option> { Some((addr - addr % size)..end) } -fn acquire_page(reg: &mut Registry, page: usize, size: usize) -> bool { - if let Some(entry) = reg.get_mut(&page) { - let Some(count) = entry.0.checked_add(1) else { - return false; - }; - entry.0 = count; - return true; - } - if let Ok(guard) = region::lock(std::ptr::without_provenance::(page), size) { - reg.insert(page, (1, guard)); - true - } else { - false - } -} - fn lock_capacity(pages: usize, span: &Range) -> Option { pages .checked_mul(region::page::size())? @@ -156,12 +128,12 @@ impl LockedRange { let size = region::page::size(); let mut reg = registry(); let total = lock_capacity(reg.len(), &span); - if total.is_none_or(|n| region::prepare_lock_capacity(n).is_err()) { + if total.is_none() || !reg.prepare(span.len()) { FAILED.fetch_add(1, Ordering::Relaxed); return false; } for page in span.step_by(size) { - if !acquire_page(&mut reg, page, size) { + if !reg.acquire_page(page, size) { FAILED.fetch_add(1, Ordering::Relaxed); break; } @@ -199,7 +171,8 @@ impl Drop for LockedRange { #[must_use] pub fn is_locked(addr: usize) -> bool { let size = region::page::size(); - registry().contains_key(&(addr - addr % size)) + let reg = registry(); + reg.contains_key(addr - addr % size) || reg.metadata_contains(addr) } /// DE: Erlaubtes Sperrbudget (weiches `RLIMIT_MEMLOCK`) in Byte, nur zur Diagnose (#325); diff --git a/src/hardening/memlock_denial_tests.rs b/src/hardening/memlock_denial_tests.rs index fc108f6..a61c0dd 100644 --- a/src/hardening/memlock_denial_tests.rs +++ b/src/hardening/memlock_denial_tests.rs @@ -6,22 +6,13 @@ use super::{is_locked, lock_range, registry}; #[test] fn partial_os_denial_is_cleaned_up_in_isolated_child() { - let result = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "hardening::memlock::denial_tests::partial_os_denial_child", - "--ignored", - "--test-threads=1", - ]) - .env("PQKEEP_LOCK_RANGE_DENIAL_CHILD", "1") - .output() - .unwrap(); - assert!( - result.status.success(), - "{}", - String::from_utf8_lossy(&result.stderr) + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "hardening::memlock::denial_tests::partial_os_denial_child", + "PQKEEP_LOCK_RANGE_DENIAL_CHILD", ); - assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed")); + assert_eq!(getrlimit(Resource::Memlock), before); } #[test] @@ -37,19 +28,49 @@ fn partial_os_denial_child() { let buffer = vec![0u8; 4 * size]; let base = buffer.as_ptr().addr(); let first = base - base % size + size; + let baseline = kernel_locked_bytes(); + let warm = lock_range(first, size); + assert!(warm.complete(first, size)); + let warm_bytes = kernel_locked_bytes(); + let budget = warm_bytes + .checked_add(u64::try_from(size).unwrap()) + .unwrap(); setrlimit( Resource::Memlock, Rlimit { - current: Some(u64::try_from(size).unwrap()), - maximum: Some(u64::try_from(size).unwrap()), + current: Some(budget), + maximum: Some(budget), }, ) .unwrap(); - let range = lock_range(first, 2 * size); - assert!(!range.complete(first, 2 * size)); - assert!(PartialEq::eq(&range.pages, &(first..first + size))); - assert!(is_locked(first) && !is_locked(first + size)); + assert_eq!( + rustix::process::getrlimit(Resource::Memlock).current, + Some(budget) + ); + let target = first + size; + let range = lock_range(target, 2 * size); + assert!(!range.complete(target, 2 * size)); + assert!(PartialEq::eq(&range.pages, &(target..target + size))); + assert!(is_locked(target) && !is_locked(target + size)); drop(range); - assert!(!is_locked(first)); + assert!(!is_locked(target)); + assert!(is_locked(first)); + assert_eq!(kernel_locked_bytes(), warm_bytes); + drop(warm); + assert_eq!(kernel_locked_bytes(), baseline); assert!(registry().is_empty()); } + +fn kernel_locked_bytes() -> u64 { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024 +} diff --git a/src/hardening/memlock_tests.rs b/src/hardening/memlock_tests.rs index 6412654..8723c83 100644 --- a/src/hardening/memlock_tests.rs +++ b/src/hardening/memlock_tests.rs @@ -123,12 +123,12 @@ fn saturated_reference_stops_at_prefix_without_losing_existing_owner() { let second = first + size; let existing = lock_range(second, size); assert!(existing.complete(second, size)); - registry().get_mut(&second).unwrap().0 = usize::MAX; + registry().get_mut(second).unwrap().users = usize::MAX; let prefix = lock_range(first, 2 * size); let reference_preserved = { let mut reg = registry(); - let preserved = reg.get(&second).unwrap().0 == usize::MAX; - reg.get_mut(&second).unwrap().0 = 1; + let preserved = reg.get(second).unwrap().users == usize::MAX; + reg.get_mut(second).unwrap().users = 1; preserved }; assert!(reference_preserved); diff --git a/src/hardening/mod.rs b/src/hardening/mod.rs index d886a41..59aaf0a 100644 --- a/src/hardening/mod.rs +++ b/src/hardening/mod.rs @@ -10,6 +10,8 @@ //! separate process hardening reports OS-dependent limits. CLI startup calls [`harden_process`]; //! library embedders explicitly choose their own host policy. +mod lock_registry; +mod lock_registry_storage; pub mod memlock; pub mod sandbox; diff --git a/vendor/patches-sha256.json b/vendor/patches-sha256.json index d3cd75b..96e899c 100644 --- a/vendor/patches-sha256.json +++ b/vendor/patches-sha256.json @@ -25,13 +25,17 @@ ], "region-4.0.1": [ { - "sha256": "0060a028891aabcf99ecd0c2e48b025dd87e04ed2330d2f9c7e16eac8921d397", + "sha256": "41e01df7dcd6f063e58d865927ad6c9a201385481c349666fe19ce789b6dbbfc", "path": "Cargo.toml" }, { "sha256": "6dce58bd48179fd1a352e9c676df90d8840c2496a7561d7a40ef98fd1e50f23d", "path": "src/lib.rs" }, + { + "sha256": "a35b644e0f445695fd340f4a9348704672e00011857cdb592089f37d4f4bb623", + "path": "src/lock.rs" + }, { "sha256": "1d69f87df2e8d4a551294a91e5dc047203ceb01cf4df24e974b86249a6289ec4", "path": "src/os/bsd_protection.rs" diff --git a/vendor/region-4.0.1/Cargo.toml b/vendor/region-4.0.1/Cargo.toml index b38a724..9b81f42 100644 --- a/vendor/region-4.0.1/Cargo.toml +++ b/vendor/region-4.0.1/Cargo.toml @@ -60,6 +60,10 @@ path = "src/lib.rs" version = "2.6" default-features = false +[dependencies.zeroize] +version = "1.9.1" +default-features = false + [dependencies.libc] version = "0.2.172" default-features = false diff --git a/vendor/region-4.0.1/src/lock.rs b/vendor/region-4.0.1/src/lock.rs index 1f79c80..31bebb0 100644 --- a/vendor/region-4.0.1/src/lock.rs +++ b/vendor/region-4.0.1/src/lock.rs @@ -77,31 +77,81 @@ pub unsafe fn unlock(address: *const T, size: usize) -> Result<()> { /// released. #[must_use] pub struct LockGuard { - address: *const (), + // DE/EN: Numerische OS-Adressen, niemals dereferenzieren / numeric OS addresses, never dereferenced. + address: usize, size: usize, } impl LockGuard { #[inline(always)] fn new(address: *const T, size: usize) -> Self { - Self { - address: address.cast(), - size, + Self { address: address.addr(), size } + } + + /// DE: Öffentlich leer, zum Aufbau im bereits gesperrten Ziel. + /// EN: Public-empty guard for initialization in an already locked destination. + #[inline] + pub const fn empty() -> Self { Self { address: 0, size: 0 } } + + /// DE: Besitzt eine erfolgreiche native Sperre. EN: Owns a successful native lock. + #[inline] + pub const fn is_active(&self) -> bool { self.size != 0 } + + /// DE: Leeren Guard direkt befüllen; vorhandenes Eigentum niemals ersetzen. + /// EN: Populate an empty guard in place without replacing existing ownership. + /// + /// # Errors + /// DE/EN: Aktiver Guard, ungültige Spanne oder native Verweigerung / active guard, + /// invalid range or native refusal. The guard stays unchanged on failure. + #[inline] + pub fn acquire(&mut self, address: *const T, size: usize) -> Result<()> { + if self.is_active() { return Err(crate::Error::InvalidParameter("active guard")); } + let page = crate::page::size(); + if size == 0 || address.addr().checked_add(size).is_none() + || size.checked_add(page - 1).and_then(|n| n.checked_add(page - 1)).is_none() { + return Err(crate::Error::InvalidParameter("lock range")); } + let (address, size) = util::round_to_page_boundaries(address, size)?; + os::lock(address.cast(), size)?; + self.address = address.addr(); + self.size = size; + Ok(()) + } + + /// DE: Eigentum zwischen zwei Guards feldweise übertragen, ohne Gesamtrecord-Kopie. + /// EN: Exchange owned guards field by field, without moving a private aggregate record. + #[inline] + pub fn swap(&mut self, other: &mut Self) { + core::mem::swap(&mut self.address, &mut other.address); + core::mem::swap(&mut self.size, &mut other.size); + } + + /// DE: Nur eigene Sperre freigeben; gespeicherte Felder vor Unlock löschen. + /// EN: Release only this guard's lock; wipe retained fields before unlocking. + /// + /// # Errors + /// DE/EN: Native Unlock-Verweigerung / native unlock refusal. Like Drop, the + /// ownership is consumed; this never grants authority over an arbitrary range. + #[inline] + pub fn release(&mut self) -> Result<()> { + use zeroize::Zeroize; + if !self.is_active() { return Ok(()); } + let address = self.address; + let size = self.size; + self.address.zeroize(); + self.size.zeroize(); + os::unlock(core::ptr::without_provenance(address), size) } } impl Drop for LockGuard { #[inline] fn drop(&mut self) { - let result = os::unlock(self.address, self.size); + let result = self.release(); debug_assert!(result.is_ok(), "unlocking region: {:?}", result); } } -unsafe impl Send for LockGuard {} -unsafe impl Sync for LockGuard {} - #[cfg(test)] mod tests { use super::*; From a48d3053dabc919382d5e8d9d6dc93b3c6d96385 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:23:14 +0100 Subject: [PATCH 09/26] Respect Windows COFF alignment in protected registry storage DE: Nativen rustc/LLVM-Codegenerierungsabbruch reproduziert: COFF-Objekte mit16/64KiB Ausrichtung scheitern,8KiB funktionieren. Kontroll-/Node-Ausrichtung unter Windows auf8KiB setzen, ELF/Linux/ARM64 bei64KiB belassen. Reale OS-Seitengeometrie bleibt strikt erforderlich. EN: No weakened memory gate or fallback. Four strict lint configurations and16 hardening groups per feature configuration pass with865 source hashes unchanged across twelve final checks. Full GNU library build is not claimed: existing toolchain lacks dlltool; native MSVC test/release jobs remain required. No installation, privilege change, unsafe addition or unapproved token probe. --- docs/security/LOCK_REGISTRY_VALIDATION.md | 24 ++++++++++++++++++++++- src/hardening/lock_registry.rs | 6 +++++- src/hardening/lock_registry_storage.rs | 8 +++++++- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/security/LOCK_REGISTRY_VALIDATION.md b/docs/security/LOCK_REGISTRY_VALIDATION.md index 652048c..f3cdecb 100644 --- a/docs/security/LOCK_REGISTRY_VALIDATION.md +++ b/docs/security/LOCK_REGISTRY_VALIDATION.md @@ -12,7 +12,8 @@ Sperr-Guards entfallen. Ein seitendisjunkter statischer Kontrollbereich enthält Mutex, Hash-Wurzeln und Arenadescriptoren. Der Kontrollbereich wird direkt mit region gesperrt, bevor private Records befüllt werden; keine rekursive Nutzung von SecretState/SecretBytes zum Bootstrap des eigenen Registers. -EN: Fixed alignment supports actual page sizes dividing64KiB; unsupported geometry +EN: Target alignment is64KiB on ELF and8KiB on Windows/COFF. Actual page size must +divide that alignment; unsupported geometry fails closed. Control and arena allocations cannot share OS pages with separately managed data allocations. Statistics alone do not allocate or bootstrap locks. @@ -102,6 +103,20 @@ executed successes. Source-delta proof for the later additional release-error test confirms unchanged production code; two bilingual comment-only updates. Native exact-head acceptance of the complete new registry component remains pending. +DE: Native Windows-Codegenerierung am ersten Register-Head brach in rustc/LLVM +mit illegaler Instruktion ab. Minimaler COFF-Objekttest reproduziert denselben +WinCOFFObjectWriter-Abbruch für16/64KiB, während8KiB funktioniert. Kontroll- und +Node-Ausrichtung daher auf Windows auf die tatsächlich kodierbaren8KiB setzen; +Linux/ARM64 behalten64KiB. Die tatsächliche OS-Seitengröße wird weiterhin strikt +geprüft, keine ungesperrte/geometrisch unsichere Ausnahme. +EN: Cross-Clippy checks metadata, not this object-emission boundary. Actual COFF +object emission and native MSVC test/release builds are required in addition. +The local full GNU library attempt stopped on missing x86_64-w64-mingw32-dlltool +in getrandom before the root crate; it is not claimed as a successful build. +Use existing native CI for full builds; no tool installation or gate reduction. +Original failed CI logs and all reproduction results are retained, not relabeled. +[LLVM COFF writer alignment contract](https://llvm.org/doxygen/WinCOFFObjectWriter_8cpp_source.html). + DE: Letzter lokaler v2-Stand nach dem zusätzlichen echten Release-Fehlerfall: alle zwölf Prüfungen erfolgreich, erneut865 Quellen vor/nach dem Lauf identisch. Vier strenge Clippy-Konfigurationen, je16 Härtungsgruppen mit/ohne API samt den @@ -110,3 +125,10 @@ EN: `registry-release-test-source-delta-proof.json` binds unchanged production c to the broad v1 suites; only the new test/parent invocation and two comment-only files differ. `protected-registry-v2.json` binds the final focused checks to exact source hashes. No new unapproved token/thread experiment was executed or published. + +DE: COFF-Fix v3: erneut zwölf Befehle erfolgreich bei vor/nachher865 identischen +Quellhashes, vier strenge Linux/Windows-Cross-Lints und je16 Härtungsgruppen mit +beiden Featurekonfigurationen. ELF-Ausrichtung und Funktionskörper bleiben erhalten; +die Windows-Ausrichtung erfüllt nun den reproduzierten Objektformat-Vertrag. +EN: Final native MSVC code generation and page observations still required; +successful metadata checks are not substituted for those native jobs. diff --git a/src/hardening/lock_registry.rs b/src/hardening/lock_registry.rs index 8c8de87..85756fa 100644 --- a/src/hardening/lock_registry.rs +++ b/src/hardening/lock_registry.rs @@ -13,9 +13,13 @@ use zeroize::Zeroize; const BUCKETS: usize = 2048; -#[repr(align(65536))] +#[cfg_attr(windows, repr(align(8192)))] +#[cfg_attr(not(windows), repr(align(65536)))] struct Control(Mutex); +#[cfg(windows)] +const _: () = assert!(align_of::() <= 8192); + static CONTROL: Control = Control(Mutex::new(Registry::new())); static POISONED: AtomicBool = AtomicBool::new(false); diff --git a/src/hardening/lock_registry_storage.rs b/src/hardening/lock_registry_storage.rs index dc0a46c..1a3737d 100644 --- a/src/hardening/lock_registry_storage.rs +++ b/src/hardening/lock_registry_storage.rs @@ -4,6 +4,9 @@ use region::LockGuard; use zeroize::Zeroize; +#[cfg(windows)] +pub(super) const ALIGNMENT: usize = 8192; +#[cfg(not(windows))] pub(super) const ALIGNMENT: usize = 65536; const NODES: usize = 256; @@ -43,7 +46,10 @@ impl Drop for Node { } } -#[repr(align(65536))] +// DE: COFF kodiert höchstens 8KiB-Sektionsausrichtung, ELF unterstützt hier 64KiB. +// EN: COFF section alignment tops out at8KiB; retain64KiB geometry on ELF targets. +#[cfg_attr(windows, repr(align(8192)))] +#[cfg_attr(not(windows), repr(align(65536)))] struct Chunk([Node; NODES]); impl Chunk { From 5470c188c49ee3330709b55c07555ef90b1d09e7 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:33:24 +0100 Subject: [PATCH 10/26] Match protected Windows data to default PE image alignment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Native MSVC-Linkfehler LNK1164 am8KiB-Objektstand abgleichen. Windows-Kontroll-/Node-Ausrichtung auf die unveränderte standardmäßige PE-Image-Ausrichtung4KiB setzen; ELF/Linux/ARM64 bleiben64KiB. Keine /ALIGN- oder Härtungsflagänderung; reale OS-Seitengeometrie weiterhin zwingend. EN: Twelve source-bound checks pass with865 hashes unchanged, including four strict lints and16 hardening groups per feature configuration. Actual local4KiB object/image generation passes; observed permissive lld behavior is not substituted for native MSVC. Full native builds and memory observations pending; three unapproved token prototype files preserved. --- docs/security/LOCK_REGISTRY_VALIDATION.md | 19 ++++++++++++++++++- src/hardening/lock_registry.rs | 4 ++-- src/hardening/lock_registry_storage.rs | 8 ++++---- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/docs/security/LOCK_REGISTRY_VALIDATION.md b/docs/security/LOCK_REGISTRY_VALIDATION.md index f3cdecb..f87a810 100644 --- a/docs/security/LOCK_REGISTRY_VALIDATION.md +++ b/docs/security/LOCK_REGISTRY_VALIDATION.md @@ -12,7 +12,7 @@ Sperr-Guards entfallen. Ein seitendisjunkter statischer Kontrollbereich enthält Mutex, Hash-Wurzeln und Arenadescriptoren. Der Kontrollbereich wird direkt mit region gesperrt, bevor private Records befüllt werden; keine rekursive Nutzung von SecretState/SecretBytes zum Bootstrap des eigenen Registers. -EN: Target alignment is64KiB on ELF and8KiB on Windows/COFF. Actual page size must +EN: Target alignment is64KiB on ELF and4KiB on Windows/PE. Actual page size must divide that alignment; unsupported geometry fails closed. Control and arena allocations cannot share OS pages with separately managed data allocations. Statistics alone do not allocate or bootstrap locks. @@ -117,6 +117,15 @@ Use existing native CI for full builds; no tool installation or gate reduction. Original failed CI logs and all reproduction results are retained, not relabeled. [LLVM COFF writer alignment contract](https://llvm.org/doxygen/WinCOFFObjectWriter_8cpp_source.html). +DE: Der anschließende native Linklauf am8KiB-Stand erzeugte LNK1164, weil die +Objektausrichtung die unveränderte standardmäßige PE-Image-Ausrichtung4KiB +überstieg. Windows-Ausrichtung deshalb abschließend4KiB; Linux/ARM64 bleiben64KiB. +Compilerobjekt und ausführbares Image sind getrennte Grenzen. Keine Änderung +von /ALIGN, Linker-/Härtungsflags, OS-Seitenprüfung oder Sicherheitsgate. +EN: Actual page geometry must still divide the chosen alignment. Native MSVC +debug/release linking and memory observations remain required for the new head. +[Microsoft image-section alignment contract](https://learn.microsoft.com/en-us/cpp/build/reference/align-section-alignment?view=msvc-170). + DE: Letzter lokaler v2-Stand nach dem zusätzlichen echten Release-Fehlerfall: alle zwölf Prüfungen erfolgreich, erneut865 Quellen vor/nach dem Lauf identisch. Vier strenge Clippy-Konfigurationen, je16 Härtungsgruppen mit/ohne API samt den @@ -132,3 +141,11 @@ beiden Featurekonfigurationen. ELF-Ausrichtung und Funktionskörper bleiben erha die Windows-Ausrichtung erfüllt nun den reproduzierten Objektformat-Vertrag. EN: Final native MSVC code generation and page observations still required; successful metadata checks are not substituted for those native jobs. + +DE: PE-Fix v4: alle zwölf lokalen Prüfungen auf erneut865 unveränderten Quellen +erfolgreich, darunter vier strenge Lints und je16 echte Härtungsgruppen. Lokaler +4KiB-Minimalfall erzeugt sowohl COFF-Objekt als auch PE-Image mit dem vorhandenen +lld-link, ohne Installation oder Ausführung. Native MSVC-Linkprüfung bleibt maßgeblich: +lld-link akzeptiert auch einen8KiB-Minimalfall, den MSVC am echten Projekt verwirft. +EN: Preserve the observed linker difference; do not report the permissive local +linker as proof that the native MSVC failure passed. New native jobs remain required. diff --git a/src/hardening/lock_registry.rs b/src/hardening/lock_registry.rs index 85756fa..c924ecd 100644 --- a/src/hardening/lock_registry.rs +++ b/src/hardening/lock_registry.rs @@ -13,12 +13,12 @@ use zeroize::Zeroize; const BUCKETS: usize = 2048; -#[cfg_attr(windows, repr(align(8192)))] +#[cfg_attr(windows, repr(align(4096)))] #[cfg_attr(not(windows), repr(align(65536)))] struct Control(Mutex); #[cfg(windows)] -const _: () = assert!(align_of::() <= 8192); +const _: () = assert!(align_of::() <= 4096); static CONTROL: Control = Control(Mutex::new(Registry::new())); static POISONED: AtomicBool = AtomicBool::new(false); diff --git a/src/hardening/lock_registry_storage.rs b/src/hardening/lock_registry_storage.rs index 1a3737d..65136b8 100644 --- a/src/hardening/lock_registry_storage.rs +++ b/src/hardening/lock_registry_storage.rs @@ -5,7 +5,7 @@ use region::LockGuard; use zeroize::Zeroize; #[cfg(windows)] -pub(super) const ALIGNMENT: usize = 8192; +pub(super) const ALIGNMENT: usize = 4096; #[cfg(not(windows))] pub(super) const ALIGNMENT: usize = 65536; const NODES: usize = 256; @@ -46,9 +46,9 @@ impl Drop for Node { } } -// DE: COFF kodiert höchstens 8KiB-Sektionsausrichtung, ELF unterstützt hier 64KiB. -// EN: COFF section alignment tops out at8KiB; retain64KiB geometry on ELF targets. -#[cfg_attr(windows, repr(align(8192)))] +// DE: PE-Standardsektionen erfordern hier 4KiB, ELF unterstützt weiterhin 64KiB. +// EN: Match default4KiB PE image sections; retain64KiB geometry on ELF targets. +#[cfg_attr(windows, repr(align(4096)))] #[cfg_attr(not(windows), repr(align(65536)))] struct Chunk([Node; NODES]); From d818ff3aefa0d6abd57b3d915eda2a2b6e3732d2 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:59:17 +0100 Subject: [PATCH 11/26] Prelock native archive and source read paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Tatsächliche Leseeingänge mit vorab gesperrten nativen Pfaden und kompatibler Windows-Normalisierung schützen. Alle lokalen Prüfungen bestanden; native Pfadabnahme und übrige R7/R8-Lücken bleiben offen. EN: Preserve wire formats and read sharing, keep Root forbid, isolate three reviewed native FFI calls. Record completed native registry acceptance separately; no partial Main merge. --- Cargo.toml | 2 +- NOTICE | 8 + docs/ROADMAP.md | 11 +- docs/SPEC.en.md | 6 + docs/SPEC.md | 6 + docs/security/LOCK_REGISTRY_VALIDATION.md | 19 ++ docs/security/NATIVE_PATH_VALIDATION.md | 76 ++++++++ platform/pqkeep-platform/Cargo.toml | 2 +- platform/pqkeep-platform/src/lib.rs | 5 + platform/pqkeep-platform/src/path_windows.rs | 68 +++++++ src/files/decrypt.rs | 2 +- src/files/encrypt.rs | 4 +- src/files/mod.rs | 8 +- src/files/native_path.rs | 160 ++++++++++++++++ src/files/native_path_tests.rs | 181 +++++++++++++++++++ src/files/native_path_windows.rs | 78 ++++++++ src/files/native_path_windows_tests.rs | 113 ++++++++++++ 17 files changed, 738 insertions(+), 11 deletions(-) create mode 100644 docs/security/NATIVE_PATH_VALIDATION.md create mode 100644 platform/pqkeep-platform/src/path_windows.rs create mode 100644 src/files/native_path.rs create mode 100644 src/files/native_path_tests.rs create mode 100644 src/files/native_path_windows.rs create mode 100644 src/files/native_path_windows_tests.rs diff --git a/Cargo.toml b/Cargo.toml index d320c0d..0993fef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -130,7 +130,7 @@ tokio = { version = "1.54.1", default-features = false, features = ["macros", "r [target.'cfg(target_os = "linux")'.dependencies] landlock = "0.4.7" libc = "0.2.191" -rustix = { version = "1.1.6", default-features = false, features = ["std", "process", "termios", "event", "thread"] } +rustix = { version = "1.1.6", default-features = false, features = ["std", "process", "termios", "event", "thread", "fs"] } seccompiler = { version = "0.5.0", default-features = false } # DE: Kontextmenü unter Windows (HKCU). 0.6.x, da neuere Versionen Rust 1.95 verlangen (MSRV 1.88). diff --git a/NOTICE b/NOTICE index bcbca5f..0b29738 100644 --- a/NOTICE +++ b/NOTICE @@ -7,6 +7,14 @@ Lizenziert unter der Apache License, Version 2.0 (siehe LICENSE). This product includes no proprietary code. Dieses Produkt enthält keinen proprietären Code. +Windows native path normalization / Native Windows-Pfadnormalisierung: +- src/files/native_path_windows.rs adapts get_long_path branch logic from + Rust 1.88.0, library/std/src/sys/path/windows.rs. + Copyright The Rust Project Developers, licensed under Apache-2.0. + Modified: prelocked UTF16 destinations, fallible bounded growth, borrowed input. + DE: Angepasst auf vorab gesperrte UTF16-Ziele, fallibles begrenztes Wachstum + und geliehene Eingabe. + Test vectors / Testvektoren (tests/kat/): - NIST ACVP-Server (usnistgov/ACVP-Server): public domain / gemeinfrei (US Government work). - Project Wycheproof (C2SP/wycheproof): Copyright the Wycheproof authors, diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a2e1542..6742ad9 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -178,7 +178,14 @@ See [scope and migration](security/CONFIDENTIAL_FRAMING_VALIDATION.md). DE: Im selben Draft folgt das vor Befüllung gesperrte gemeinsame Seitenregister: Kontroll-/Node-Arenen, fallibles Wachstum, geprüfte Überlappung/Teilsperre und Verweigerung weiterer Aufnahme nach echtem Release-Fehler oder Poisoning. -EN: Protected shared registry implemented and locally source-checked; native final -acceptance remains pending. Two unnecessary unsafe Send/Sync impls removed; +EN: Protected shared registry accepted on native Linux/Windows/ARM at5470c188. +Two unnecessary unsafe Send/Sync impls removed; read-only native Windows observer is test-only. Other R7/R8 rows stay open. See [registry contract and evidence](security/LOCK_REGISTRY_VALIDATION.md). + +DE: Native Pfadkonvertierung an den tatsächlichen Archiv-/Quelldatei-Leseeingängen +vor privater Befüllung gesperrt; Windows-Normalisierung mit gesperrtem Ziel und +std-kompatibler248-Grenze. Quell-/Traversal-/Ziel-/Temppfade insgesamt weiter offen. +EN: First actual native read adapters implemented and locally source-checked in +the same Draft355; native acceptance pending, no M1/M3 closure. See +[native path scope](security/NATIVE_PATH_VALIDATION.md). diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index b2cca9a..9362c8b 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -564,3 +564,9 @@ without private return values. No private sponge conversion arrays or new unsafe casts. This protected mode may lose ARM SHA3 acceleration. KEM PKE also uses complete borrowed prelocked operation storage, including confidential recomputed candidate ciphertext. Native acceptance and DSA/AES/Argon2 proofs stay open; no full R6 closure. + +R7/R8 work in progress: actual archive/source read ingress converts native paths +into prelocked UTF8/UTF16 destinations. Root forbid remains; necessary native +Windows calls stay in the narrow platform adapter. Other traversal/target/temp +paths and process/helper gaps remain open; see +[native path scope](security/NATIVE_PATH_VALIDATION.md). diff --git a/docs/SPEC.md b/docs/SPEC.md index fea6464..49b0959 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -570,3 +570,9 @@ Sponge-Konvertierungsarrays oder neuen unsafe-Casts. Auf ARM kann diese geschüt Variante Hardwarebeschleunigung kosten. KEM-PKE nutzt ebenfalls vollständig geliehene vorab gesperrte Operationsflächen, einschließlich vertraulichem internem Vergleichs-Chiffrat. Native Abnahme und DSA-/AES-/Argon2-Nachweise bleiben offen; kein R6-Gesamtabschluss. + +R7/R8-Arbeitsstand: Native Konvertierung der Archiv-/Quelldatei-Leseeingänge +verwendet vor Befüllung gesperrte UTF8-/UTF16-Ziele. Root-forbid bleibt erhalten; +notwendige native Windows-Aufrufe bleiben im schmalen Plattformadapter. Übrige +Traversal-/Ziel-/Temppfad- und Prozess-/Helper-Lücken bleiben offen; siehe +[Nativer Pfadumfang](security/NATIVE_PATH_VALIDATION.md). diff --git a/docs/security/LOCK_REGISTRY_VALIDATION.md b/docs/security/LOCK_REGISTRY_VALIDATION.md index f87a810..e7a3118 100644 --- a/docs/security/LOCK_REGISTRY_VALIDATION.md +++ b/docs/security/LOCK_REGISTRY_VALIDATION.md @@ -149,3 +149,22 @@ lld-link, ohne Installation oder Ausführung. Native MSVC-Linkprüfung bleibt ma lld-link akzeptiert auch einen8KiB-Minimalfall, den MSVC am echten Projekt verwirft. EN: Preserve the observed linker difference; do not report the permissive local linker as proof that the native MSVC failure passed. New native jobs remain required. + +## Current native acceptance / Aktuelle native Abnahme + +DE: Der aktuelle signierte Stand5470c188 besteht alle vier nativen Rust-Jobs: +Ubuntu22 undARM je948 Tests/120Gruppen, Ubuntu-latest1817/238, Windows1636/240; +keine Testfehler. Vollständige Protokolle und tatsächliche Register-Eltern samt +vier eigenen Kindfällen geprüft. Alle acht Fuzz-Ziele, MSRV/deny/Historien-/ +Workflow-/Abhängigkeits-/Härtungsgates erfolgreich; keine Abschwächung. +EN: registry-5470-native-summary.json binds full logs to this exact head. Optional +native Windows observations prove actual page state, not just registry membership. +Explicitly ignored child entry points execute through their bounded parent; +unrelated known338 race gaps remain ignored and are not counted as passed. + +DE: Damit ist die Registerkomponente PR-seitig abgenommen, einschließlich echter +Windows-MSVC-Debug-/Release-Builds. Die getrennte R7-Prozesszugriffsprobe bleibt +wegen des nachgewiesenen Debugprivilegs fehlgeschlagen. Kein R7/R8-Gesamtabschluss, +kein Main-Merge. Spätere native Pfadänderungen sind nicht durch diesen Stand belegt. +EN: These results supersede the earlier pending registry-native acceptance only; +they do not grant or execute any restricted-token/thread experiment. diff --git a/docs/security/NATIVE_PATH_VALIDATION.md b/docs/security/NATIVE_PATH_VALIDATION.md new file mode 100644 index 0000000..042ff63 --- /dev/null +++ b/docs/security/NATIVE_PATH_VALIDATION.md @@ -0,0 +1,76 @@ +# Native path ingress / Nativer Pfadeingang + +DE: Teil von R7/R8 in genau Draft355; kein Abschluss von M1/M3 oder147. +EN: This component protects internal native conversion at actual archive/source +read calls. Caller-owned Path/OsStr memory remains the caller's responsibility. + +## Ownership and reached callers / Owner und tatsächliche Caller + +DE: NativePath sperrt den konkreten Pufferowner und den UTF8-/UTF16-Puffer vor +privater Befüllung. Linux übernimmt geliehene OsStr-Bytes ohne CString-Staging; +Windows kodiert direkt aus encode_wide in gesperrte Einheiten, auch bei isolierten +Surrogaten. Kein to_string_lossy, gewöhnlicher UTF16-Vec oder privates OsString. +Duplikation ist explizit fallibel; Debug redigiert, kein Clone/Display/Serialize. +EN: Public-empty owners are installed before private population. Existing +SecretBytes/SecretWorkspace and SecretState wipe storage before releasing locks. +Invalid native NUL input is rejected; failed duplication leaves the source intact. + +DE: inspect und inspect_v2 sowie der gemeinsame Entschlüsselungs-/Listen-/Check- +Quelleingang und der Quelldatei-Leser beim Verschlüsseln benutzen open_file. +Linux verwendet vorhandenes rustix1.1.6 mit geliehenem CStr und CLOEXEC; dessen +Arg-Implementierung reicht den Borrow direkt durch, ohne CString-Allokation. +EN: Existing package versions/sources are unchanged; only existing dependency +features are added. Missing files keep their I/O classification. A lock failure +refuses ingress before native open; no fallback to unprotected std conversion. + +## Windows compatibility and FFI / Kompatibilität und FFI + +DE: GetFullPathNameW schreibt direkt in ein gesperrtes Caller-Ziel. Begrenztes +fallibles Wachstum, anschließend Präfix direkt in ein weiteres gesperrtes Ziel. +Die Rust1.88-get_long_path-Verzweigungen einschließlich der248-Einheiten-Grenze, +UNC-/Device-/Verbatim-/NT-Präfixe und relativer Pfade bleiben erhalten; Herkunft +und Anpassung stehen in NOTICE. Kein Wechsel des Arbeitsverzeichnisses. +EN: CreateFileW retains read access, read/write/delete sharing, OPEN_EXISTING, +normal attributes and noninheritance, matching existing std read-open behavior. +No change to link following or source-race guarantees is claimed. + +DE: Drei notwendige unsafe-Blöcke sind ausschließlich im schmalen Windows- +Plattformadapter: synchroner nativer Normalisierungsaufruf, synchrones Öffnen, +einmalige Übergabe des neuen Handles an File. Eingabeslice vollständig NUL-geprüft; +Ausgabe exklusiv und längengeprüft; keine gespeicherten Zeiger. Fehler sofort +zurückgeben, bevor ein weiterer Win32-Aufruf den Fehlercode verändern kann. +EN: Root forbids unsafe code. No pointer casts of private records, shared mutable +aliases, rights/token/Registry mutation, new Send/Sync claims or host-policy changes. + +## Acceptance and limits / Abnahme und Grenzen + +DE: Tests prüfen echte gesperrte Owner, unabhängige fallible Kopien, Wipe/Unwind, +wirkliche Ressourcenverweigerung im begrenzten eigenen Linux-Kind und unveränderte +Elternlimits. Echte Dateiöffnungen decken Unicode, Linux-NonUTF8, EOF und fehlende +Dateien ab. Native Windows-Fälle: relative und lange Pfade, Präfixe,248-Grenze, +Surrogate sowie Ablehnung ungültiger nativer Eingabe vor einem Systemaufruf. +EN: Cross lint only proves compilation, not native execution. Source-bound local +and exact published-head native acceptance must be recorded before row closure. + +DE: Lokaler v1-Checkpoint:869 Rust-/Manifestquellen über13 erfolgreiche Befehle +unverändert. Vier strenge Linux-/Windows-Cross-Lints mit/ohne API, je73 Datei- +Testgruppen mit tatsächlichen eigenen Verweigerungskindern und21 ausgewählte +Format-/Sender-/STREAM-Integrationen, Format/Limits/Herkunft/Matrix/Diff bestanden. +EN: Final focused v2 passes all12 commands on869 unchanged source hashes: four +strict lints and six native-path groups per feature configuration, actual bounded +denial/unwind child, format/limits/provider/matrix/diff. It adds Windows owner/page +observations through the existing prelocked query fixture and preserves the old +invalid-NUL I/O class. Source delta is bound to v1; native Windows execution of +the new path tests remains pending. + +DE: Offen bleiben gespeicherte SourceEntry-/Skip-/Traversal-Datensätze, gewöhnliche +read_dir-/Metadaten-Ausgaben, Ziel-/Temppfade und deren Schreib-/Publish-/Cleanup- +Adapter, Berichte/Transport sowie Prozess-/GUI-/Host-Verträge. Keine dieser Flächen +wird durch den neuen Leseadapter nachträglich als geschützt erklärt. +EN: OS filesystem naming is an explicit disclosure boundary. Neither it nor scalar +compiler transit excuses known ordinary application-side path allocations. + +Sources / Quellen: +- [Rust1.88 Windows path source](https://github.com/rust-lang/rust/blob/1.88.0/library/std/src/sys/path/windows.rs) +- [GetFullPathNameW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew) +- [CreateFileW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew) diff --git a/platform/pqkeep-platform/Cargo.toml b/platform/pqkeep-platform/Cargo.toml index 6b9093a..ef92fae 100644 --- a/platform/pqkeep-platform/Cargo.toml +++ b/platform/pqkeep-platform/Cargo.toml @@ -8,7 +8,7 @@ publish = false description = "Narrow synchronous platform adapters for PQKeep" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_UI_Input_KeyboardAndMouse"] } +windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_Storage_FileSystem", "Win32_Security", "Win32_UI_Input_KeyboardAndMouse"] } [target.'cfg(windows)'.dependencies.zeroize] version = "1.9.1" diff --git a/platform/pqkeep-platform/src/lib.rs b/platform/pqkeep-platform/src/lib.rs index b6e2521..227b8bf 100644 --- a/platform/pqkeep-platform/src/lib.rs +++ b/platform/pqkeep-platform/src/lib.rs @@ -26,3 +26,8 @@ pub mod input_fixture; #[cfg(all(windows, feature = "native-memory-fixture"))] pub mod memory_fixture; + +#[cfg(windows)] +mod path_windows; +#[cfg(windows)] +pub use path_windows::{absolute_path_into, open_file_read}; diff --git a/platform/pqkeep-platform/src/path_windows.rs b/platform/pqkeep-platform/src/path_windows.rs new file mode 100644 index 0000000..e8452d6 --- /dev/null +++ b/platform/pqkeep-platform/src/path_windows.rs @@ -0,0 +1,68 @@ +//! DE: Native Dateipfade nur aus geliehenen, vom Caller geschützten UTF16-Zielen. +//! EN: Native file paths use borrowed caller-protected UTF16 storage only. + +use std::{fs::File, io, os::windows::io::FromRawHandle, ptr}; +use windows_sys::Win32::{ + Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE}, + Storage::FileSystem::{ + CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, + GetFullPathNameW, OPEN_EXISTING, + }, +}; + +fn validate(path: &[u16]) -> io::Result<()> { + if path.last() != Some(&0) || path[..path.len() - 1].contains(&0) { + return Err(io::ErrorKind::InvalidInput.into()); + } + Ok(()) +} + +/// DE: Absolute Pfadform direkt in einen lebenden Caller-Puffer schreiben. +/// EN: Write the absolute path directly into live caller-owned storage. +/// # Errors +/// DE/EN: Ungültige UTF16-Geometrie oder native Verweigerung / invalid UTF16 geometry or native refusal. +pub fn absolute_path_into(input: &[u16], output: &mut [u16]) -> io::Result { + validate(input)?; + let len = u32::try_from(output.len()).map_err(|_| io::ErrorKind::InvalidInput)?; + if len == 0 { + return Err(io::ErrorKind::InvalidInput.into()); + } + // DE: Getrennte lebende Slices, NUL-geprüfte Eingabe, exklusives vollständiges Ziel. + // SAFETY: Input terminates within its live borrow; output is exclusive and + // writable for len units. The API retains no pointer; no file-part output requested. + let count = + unsafe { GetFullPathNameW(input.as_ptr(), len, output.as_mut_ptr(), ptr::null_mut()) }; + if count == 0 { + return Err(io::Error::last_os_error()); + } + Ok(count as usize) +} + +/// DE: Bestehende Datei wie `std::File::open` aus bereits nativ kodiertem Pfad öffnen. +/// EN: Open an existing file with `std::File::open` sharing semantics from native storage. +/// # Errors +/// DE/EN: Ungültige Pfadgeometrie oder nativer Öffnungsfehler / invalid path geometry or native open failure. +pub fn open_file_read(path: &[u16]) -> io::Result { + validate(path)?; + // DE: NUL-geprüfte lebende Eingabe; kein vererbbarer Handle, keine Security-Mutation. + // SAFETY: The immutable input is terminated in bounds and stays live through + // this synchronous call. Null security/template pointers are permitted; no inheritance. + let handle = unsafe { + CreateFileW( + path.as_ptr(), + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error()); + } + // DE: Genau ein neuer besessener Handle; File übernimmt ausschließlich dieses Eigentum. + // SAFETY: Successful CreateFileW returns a fresh owned file handle; transfer + // it exactly once, with no other owner that could close it. + Ok(unsafe { File::from_raw_handle(handle.cast()) }) +} diff --git a/src/files/decrypt.rs b/src/files/decrypt.rs index 0550474..bde65c7 100644 --- a/src/files/decrypt.rs +++ b/src/files/decrypt.rs @@ -84,7 +84,7 @@ pub(super) fn open( unlock: &Unlock<'_>, signer: Option<&PublicKeyFile>, ) -> Result<(ArchiveReader, Content, Option)> { - let mut file = BufReader::new(File::open(source)?); + let mut file = BufReader::new(super::native_path::open_file(source)?); let file_len = file.get_ref().metadata()?.len(); // DE: Magic und Version vorab lesen und dem passenden Parser wieder voranstellen. // EN: Read magic and version up front and put them back in front of the matching parser. diff --git a/src/files/encrypt.rs b/src/files/encrypt.rs index 1931979..2a00c46 100644 --- a/src/files/encrypt.rs +++ b/src/files/encrypt.rs @@ -3,7 +3,7 @@ //! EN: Encrypting a file or directory into `target` (atomic, no overwriting). //! Fresh file key and nonce prefix for every operation. -use std::fs::{self, File}; +use std::fs; use std::io::{BufWriter, Write}; use std::path::Path; @@ -275,7 +275,7 @@ fn write_entry( report.directories += 1; } SourceKind::File(size) => { - let mut reader = File::open(&entry.abs)?; + let mut reader = super::native_path::open_file(&entry.abs)?; archive.file(&entry.rel, &mut reader, size)?; report.files += 1; report.bytes += size; diff --git a/src/files/mod.rs b/src/files/mod.rs index 9ea70a0..4e4accd 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -31,6 +31,7 @@ mod hidden_result; mod list; #[cfg(test)] mod locked_owner_tests; +mod native_path; mod original; mod output; pub mod paths; @@ -51,7 +52,6 @@ mod tail_v4; mod tail_v4_drain; mod walk; -use std::fs::File; use std::io::BufReader; use std::path::Path; @@ -179,9 +179,9 @@ pub struct Report { /// /// # Errors /// DE/EN: [`crate::Error::Io`], [`crate::Error::InvalidInput`], [`crate::Error::Unsupported`], -/// [`crate::Error::KdfParams`]. +/// [`crate::Error::KdfParams`], [`crate::Error::MemoryLock`]. pub fn inspect(source: &Path) -> Result { - let mut reader = BufReader::new(File::open(source)?); + let mut reader = BufReader::new(native_path::open_file(source)?); FileHeader::read(&mut reader) } @@ -191,6 +191,6 @@ pub fn inspect(source: &Path) -> Result { /// # Errors /// DE/EN: wie [`inspect`]; [`crate::Error::Unsupported`] auch für v1-Dateien / also for v1 files. pub fn inspect_v2(source: &Path) -> Result { - let mut reader = BufReader::new(File::open(source)?); + let mut reader = BufReader::new(native_path::open_file(source)?); HeaderV2::read(&mut reader) } diff --git a/src/files/native_path.rs b/src/files/native_path.rs new file mode 100644 index 0000000..993fe7f --- /dev/null +++ b/src/files/native_path.rs @@ -0,0 +1,160 @@ +//! DE: Native Pfade vor Befüllung sperren; keine Klartext-PathBuf-/OsString-Kopie. +//! EN: Lock native paths before population; no plaintext PathBuf/OsString copy. + +use crate::{Error, Result, crypto::secret_state::SecretState}; +use std::{fmt, path::Path}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[cfg(unix)] +type Units = crate::crypto::SecretBytes; +#[cfg(windows)] +type Units = crate::crypto::secret_workspace::SecretWorkspace; +#[cfg(unix)] +type Unit = u8; +#[cfg(windows)] +type Unit = u16; + +struct State(Units); + +impl Zeroize for State { + fn zeroize(&mut self) { + self.0.zeroize(); + } +} +impl Drop for State { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +/// DE: Auch der konkrete native Pufferowner bleibt im gesperrten Zustand. +/// EN: The concrete native buffer owner also remains in protected state. +pub(super) struct NativePath(SecretState); + +#[cfg(test)] +#[path = "native_path_tests.rs"] +mod tests; + +impl NativePath { + pub(super) fn prepare() -> Result { + Ok(Self(SecretState::new(State(Units::zeroed(0)?))?)) + } + + /// DE: Caller verantwortet seine Quelle; internes Ziel vor privater Kopie sperren. + /// EN: Caller owns input responsibility; lock internal destination before copying. + pub(super) fn from_path(path: &Path) -> Result { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + Self::from_native(path.as_os_str().as_bytes()) + } + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + let mut out = Self::prepare()?; + let len = path.as_os_str().encode_wide().count(); + out.allocate(len)?; + for (slot, unit) in out.0.get_mut().0.expose_mut()[..len] + .iter_mut() + .zip(path.as_os_str().encode_wide()) + { + if unit == 0 { + return Err(Error::InvalidInput { field: "path" }); + } + *slot = unit; + } + Ok(out) + } + } + + #[cfg(any(unix, test))] + pub(super) fn from_native(source: &[Unit]) -> Result { + let mut out = Self::prepare()?; + out.copy_native(source)?; + Ok(out) + } + + #[cfg(any(unix, test))] + pub(super) fn copy_native(&mut self, source: &[Unit]) -> Result<()> { + if source.contains(&0) { + return Err(Error::InvalidInput { field: "path" }); + } + self.allocate(source.len())?; + self.0.get_mut().0.expose_mut()[..source.len()].copy_from_slice(source); + Ok(()) + } + + fn allocate(&mut self, len: usize) -> Result<()> { + let len = len.checked_add(1).ok_or(Error::MemoryLock)?; + // DE: Nur öffentlich leeren Owner bewegen; erst danach private Einheiten schreiben. + // EN: Move only the public-empty owner, then write private native units in place. + self.0.get_mut().0 = Units::zeroed(len)?; + Ok(()) + } + + pub(super) fn encoded(&self) -> Result<&[Unit]> { + let units = self.0.get().0.expose(); + if units.last() != Some(&0) || units[..units.len() - 1].contains(&0) { + return Err(Error::Crypto); + } + Ok(units) + } + + #[cfg(unix)] + pub(super) fn c_str(&self) -> Result<&std::ffi::CStr> { + std::ffi::CStr::from_bytes_with_nul(self.encoded()?).map_err(|_| Error::Crypto) + } + + #[cfg(test)] + pub(super) fn try_duplicate(&self) -> Result { + let units = self.encoded()?; + Self::from_native(&units[..units.len() - 1]) + } +} + +impl Zeroize for NativePath { + fn zeroize(&mut self) { + self.0.get_mut().zeroize(); + } +} +impl fmt::Debug for NativePath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("NativePath([REDACTED])") + } +} + +#[cfg(windows)] +#[path = "native_path_windows.rs"] +mod windows; + +pub(super) fn open_file(path: &Path) -> Result { + let path = NativePath::from_path(path).map_err(|error| match error { + // DE: Bestehende File::open-Fehlerklasse für NUL-Pfade erhalten. + // EN: Preserve the existing File::open error class for NUL paths. + Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), + other => other, + })?; + #[cfg(target_os = "linux")] + { + use rustix::fs::{Mode, OFlags, open}; + open( + path.c_str()?, + OFlags::RDONLY | OFlags::CLOEXEC, + Mode::empty(), + ) + .map(std::fs::File::from) + .map_err(|error| std::io::Error::from(error).into()) + } + #[cfg(windows)] + { + let normalized = windows::for_open(&path)?; + pqkeep_platform::open_file_read(normalized.as_ref().unwrap_or(&path).encoded()?) + .map_err(Into::into) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = path; + Err(Error::Unsupported) + } +} diff --git a/src/files/native_path_tests.rs b/src/files/native_path_tests.rs new file mode 100644 index 0000000..1759a04 --- /dev/null +++ b/src/files/native_path_tests.rs @@ -0,0 +1,181 @@ +//! DE: Native Repräsentation und reale Owner-Sperren vor Caller-Portierung prüfen. +//! EN: Check native representation and actual owner locks before porting callers. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::locked_owner_test_support::locked; + +fn assert_owner(path: &NativePath) { + locked(path.0.get()); + locked(path.0.get().0.expose()); + #[cfg(unix)] + path.0.get().0.assert_metadata_locked(); + #[cfg(windows)] + { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let owner = std::ptr::from_ref(path.0.get()).addr(); + let units = path.0.get().0.expose(); + assert!(query.get_mut().is_locked(owner).unwrap()); + assert!( + query + .get_mut() + .is_locked(owner + size_of_val(path.0.get()) - 1) + .unwrap() + ); + assert!(query.get_mut().is_locked(units.as_ptr().addr()).unwrap()); + assert!( + query + .get_mut() + .is_locked(units.as_ptr().addr() + size_of_val(units) - 1) + .unwrap() + ); + } +} + +#[test] +fn native_open_preserves_the_std_invalid_nul_error_class() { + assert!(matches!( + open_file(Path::new("public\0fixture")), + Err(Error::Io(std::io::ErrorKind::InvalidInput)) + )); +} + +#[test] +fn native_path_roundtrips_and_duplicates_in_distinct_locked_owners() { + let input = Path::new("public directory/öffentlicher Name.txt"); + let original = NativePath::from_path(input).unwrap(); + let copy = original.try_duplicate().unwrap(); + assert_owner(&original); + assert_owner(©); + let equal = original.encoded().unwrap() == copy.encoded().unwrap(); + assert!(equal); + let distinct = original.encoded().unwrap().as_ptr() != copy.encoded().unwrap().as_ptr(); + assert!(distinct); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + let equal = original.c_str().unwrap().to_bytes() == input.as_os_str().as_bytes(); + assert!(equal); + } + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + assert!( + original + .encoded() + .unwrap() + .iter() + .copied() + .eq(input.as_os_str().encode_wide().chain(std::iter::once(0))) + ); + } + assert_eq!(format!("{original:?}"), "NativePath([REDACTED])"); +} + +#[test] +fn native_read_adapter_preserves_file_contents_and_missing_file_error() { + use std::io::Read; + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("öffentlicher fixture.txt"); + let expected = b"public native file fixture"; + std::fs::write(&source, expected).unwrap(); + let mut file = open_file(&source).unwrap(); + let mut actual = crate::crypto::SecretBytes::zeroed(expected.len()).unwrap(); + file.read_exact(actual.expose_mut()).unwrap(); + let equal = actual.expose() == expected; + assert!(equal); + let mut eof = [0]; + assert_eq!(file.read(&mut eof).unwrap(), 0); + assert!(matches!( + open_file(&root.path().join("missing fixture")), + Err(Error::Io(std::io::ErrorKind::NotFound)) + )); +} + +#[cfg(unix)] +#[test] +fn non_utf8_native_bytes_survive_without_lossy_string_staging() { + use std::{ffi::OsStr, os::unix::ffi::OsStrExt}; + let bytes = b"public/\xff\xfe fixture"; + let path = NativePath::from_path(Path::new(OsStr::from_bytes(bytes))).unwrap(); + let equal = path.c_str().unwrap().to_bytes() == bytes; + assert!(equal); + assert_owner(&path); + let root = tempfile::tempdir().unwrap(); + let source = root.path().join(OsStr::from_bytes(bytes)); + std::fs::create_dir_all(source.parent().unwrap()).unwrap(); + std::fs::write(&source, b"public fixture").unwrap(); + assert!(open_file(&source).is_ok()); +} + +#[cfg(windows)] +#[test] +fn native_wide_surrogates_survive_without_a_lossy_utf8_roundtrip() { + use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + let units = [0x61, 0xd800, 0x62, 0xdc00, 0xd83d, 0xde00]; + let input = OsString::from_wide(&units); + let path = NativePath::from_path(Path::new(&input)).unwrap(); + assert!( + path.encoded() + .unwrap() + .iter() + .copied() + .eq(units.into_iter().chain(std::iter::once(0))) + ); + assert_owner(&path); +} + +#[test] +fn invalid_native_nul_preserves_previous_path_and_explicit_wiping_clears_units() { + let mut path = NativePath::from_path(Path::new("public fixture")).unwrap(); + let before = path.try_duplicate().unwrap(); + assert!(matches!( + path.copy_native(&[65, 0, 66]), + Err(Error::InvalidInput { field: "path" }) + )); + let equal = path.encoded().unwrap() == before.encoded().unwrap(); + assert!(equal); + path.zeroize(); + assert!(path.0.get().0.expose().iter().all(|unit| *unit == 0)); +} + +#[cfg(target_os = "linux")] +#[test] +fn native_path_denial_child_preserves_parent_limit() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::native_path::tests::native_path_denial_child", + "PQKEEP_NATIVE_PATH_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn native_path_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_NATIVE_PATH_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let unwind = std::panic::catch_unwind(|| { + let path = NativePath::from_path(Path::new("public fixture")).unwrap(); + assert_owner(&path); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let source = vec![b'x'; 2 * region::page::size()]; + let path = NativePath::from_native(&source).unwrap(); + let baseline = memlock::stats().locked_pages; + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + assert!(matches!(path.try_duplicate(), Err(Error::MemoryLock))); + let unchanged = path.c_str().unwrap().to_bytes() == source; + assert!(unchanged); + assert_eq!(memlock::stats().locked_pages, baseline); +} diff --git a/src/files/native_path_windows.rs b/src/files/native_path_windows.rs new file mode 100644 index 0000000..275985a --- /dev/null +++ b/src/files/native_path_windows.rs @@ -0,0 +1,78 @@ +//! DE: Rust-1.88-Pfadsemantik mit gesperrten Zielen statt gewöhnlicher UTF16-Vecs. +//! EN: Rust1.88 path semantics using locked destinations instead of ordinary UTF16 Vecs. +//! DE/EN: Adapted branch logic: rust-lang/rust1.88 library/std/src/sys/path/windows.rs, +//! `get_long_path(prefer_verbatim=true)`, MIT OR Apache-2.0; no cryptographic changes. + +use super::{Error, NativePath, Result}; + +const SEP: u16 = 92; +const ALT: u16 = 47; +const COLON: u16 = 58; +const QUERY: u16 = 63; +const VERBATIM: &[u16] = &[SEP, SEP, QUERY, SEP]; +const NT: &[u16] = &[SEP, QUERY, QUERY, SEP]; +const UNC: &[u16] = &[SEP, SEP, QUERY, SEP, 85, 78, 67, SEP]; +const MAX_NATIVE: usize = 32768; +const LEGACY_MAX_PATH: usize = 248; + +fn unchanged(path: &[u16]) -> bool { + if path.starts_with(VERBATIM) || path.starts_with(NT) || path == [0] { + return true; + } + if path.len() >= LEGACY_MAX_PATH { + return false; + } + match path { + [drive, COLON, 0] | [drive, COLON, SEP | ALT, ..] if *drive != SEP && *drive != ALT => true, + [SEP | ALT, SEP | ALT, ..] => true, + _ => false, + } +} + +#[cfg(test)] +#[path = "native_path_windows_tests.rs"] +mod tests; + +pub(super) fn for_open(input: &NativePath) -> Result> { + let path = input.encoded()?; + if unchanged(path) { + return Ok(None); + } + let mut absolute = NativePath::prepare()?; + absolute.allocate(259)?; + for _ in 0..4 { + let count = pqkeep_platform::absolute_path_into(path, absolute.0.get_mut().0.expose_mut())?; + if count < absolute.0.get().0.expose().len() { + absolute.0.get_mut().0.truncate(count + 1); + return with_prefix(&absolute).map(Some); + } + if count >= MAX_NATIVE { + return Err(Error::InvalidInput { field: "path" }); + } + absolute.allocate(count)?; + } + Err(Error::Io(std::io::ErrorKind::InvalidInput)) +} + +fn with_prefix(absolute: &NativePath) -> Result { + let units = absolute.encoded()?; + let raw = &units[..units.len() - 1]; + let (prefix, skip) = match raw { + [_, COLON, SEP, ..] => (VERBATIM, 0), + [SEP, SEP, 46, SEP, ..] => (VERBATIM, 4), + [SEP, SEP | QUERY, QUERY, SEP, ..] => (&[][..], 0), + [SEP, SEP, ..] => (UNC, 2), + _ => (&[][..], 0), + }; + let tail = &raw[skip..]; + let len = prefix + .len() + .checked_add(tail.len()) + .ok_or(Error::MemoryLock)?; + let mut out = NativePath::prepare()?; + out.allocate(len)?; + let target = out.0.get_mut().0.expose_mut(); + target[..prefix.len()].copy_from_slice(prefix); + target[prefix.len()..len].copy_from_slice(tail); + Ok(out) +} diff --git a/src/files/native_path_windows_tests.rs b/src/files/native_path_windows_tests.rs new file mode 100644 index 0000000..9350e9b --- /dev/null +++ b/src/files/native_path_windows_tests.rs @@ -0,0 +1,113 @@ +//! DE: Echte native Aufrufe und std-kompatible Windows-Pfadgrenzen. +//! EN: Actual native calls and std-compatible Windows path boundaries. +#![allow(clippy::unwrap_used)] + +use super::*; +use std::{io::Read, path::Path}; + +fn owned(text: &str) -> NativePath { + NativePath::from_path(Path::new(text)).unwrap() +} + +#[test] +fn legacy_boundary_matches_the_std_248_unit_rule() { + let short = owned(&format!("C:\\{}", "x".repeat(243))); + let boundary = owned(&format!("C:\\{}", "x".repeat(244))); + assert!(unchanged(short.encoded().unwrap())); + assert!(!unchanged(boundary.encoded().unwrap())); + let normalized = for_open(&boundary).unwrap().unwrap(); + assert!(normalized.encoded().unwrap().starts_with(VERBATIM)); + crate::locked_owner_test_support::locked(normalized.0.get().0.expose()); +} + +#[test] +fn absolute_drive_unc_verbatim_and_nt_prefixes_follow_std_branches() { + for text in [ + "", + "C:", + "C:\\public", + "C:/public", + "\\\\host\\share", + "\\\\?\\C:\\public", + "\\??\\C:\\public", + ] { + let input = owned(text); + assert!(for_open(&input).unwrap().is_none()); + } + for (source, expected) in [ + ("C:\\public", "\\\\?\\C:\\public"), + ("\\\\.\\public", "\\\\?\\public"), + ("\\\\host\\share", "\\\\?\\UNC\\host\\share"), + ("\\\\?\\C:\\public", "\\\\?\\C:\\public"), + ("\\??\\C:\\public", "\\??\\C:\\public"), + ] { + let input = owned(source); + let prefixed = with_prefix(&input).unwrap(); + let reference = owned(expected); + let equal = prefixed.encoded().unwrap() == reference.encoded().unwrap(); + assert!(equal); + } +} + +#[test] +fn relative_paths_read_the_same_file_as_std_without_changing_cwd() { + let root = tempfile::tempdir_in(".").unwrap(); + let path = root.path().join("public Unicode ä fixture.txt"); + let expected = b"public fixture"; + std::fs::write(&path, expected).unwrap(); + let cwd = std::env::current_dir().unwrap(); + let mut protected = super::super::open_file(&path).unwrap(); + let mut reference = std::fs::File::open(&path).unwrap(); + let mut actual = crate::crypto::SecretBytes::zeroed(expected.len()).unwrap(); + let mut standard = vec![0; expected.len()]; + protected.read_exact(actual.expose_mut()).unwrap(); + reference.read_exact(&mut standard).unwrap(); + let equal = actual.expose() == standard; + assert!(equal); + assert_eq!(std::env::current_dir().unwrap(), cwd); +} + +#[test] +fn long_native_paths_match_std_open_and_missing_file_errors() { + let root = tempfile::tempdir().unwrap(); + let mut directory = root.path().to_path_buf(); + for _ in 0..6 { + directory.push("public-long-component-123456789012345678901234567890"); + } + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("public fixture.txt"); + std::fs::write(&path, b"fixture").unwrap(); + let input = NativePath::from_path(&path).unwrap(); + let normalized = for_open(&input).unwrap().unwrap(); + assert!(normalized.encoded().unwrap().starts_with(VERBATIM)); + assert!(super::super::open_file(&path).is_ok()); + assert!(std::fs::File::open(&path).is_ok()); + let missing = directory.join("missing fixture"); + assert!(matches!( + super::super::open_file(&missing), + Err(Error::Io(std::io::ErrorKind::NotFound)) + )); +} + +#[test] +fn native_adapters_reject_unterminated_and_interior_nul_input() { + for input in [&[][..], &[65][..], &[65, 0, 66, 0][..]] { + assert_eq!( + pqkeep_platform::open_file_read(input).unwrap_err().kind(), + std::io::ErrorKind::InvalidInput + ); + let mut output = [0; 8]; + assert_eq!( + pqkeep_platform::absolute_path_into(input, &mut output) + .unwrap_err() + .kind(), + std::io::ErrorKind::InvalidInput + ); + } + assert_eq!( + pqkeep_platform::absolute_path_into(&[65, 0], &mut []) + .unwrap_err() + .kind(), + std::io::ErrorKind::InvalidInput + ); +} From cfcac6a26121b2a77224507ec32102309dd45d6b Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:57:00 +0100 Subject: [PATCH 12/26] Preserve sandbox compatibility in native file reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Explizit openat statt altem x86-open-Syscall, ohne Sandbox-Regeländerung. Echte native Positiv-/Negativ-Sandboxproben und ursprünglicher CLI-Fehlerfall in beiden Featurevarianten bestanden. EN: Four strict feature/platform lints and all fourteen source-bound checks pass. Preserve protected path storage and existing syscall policy; retain original failed native logs. Joint R7/R8 remains Draft. --- docs/security/NATIVE_PATH_VALIDATION.md | 25 +++++++++++++++++++++++++ src/files/native_path.rs | 7 +++++-- tests/sandbox_cli.rs | 23 +++++++++++++++++++++-- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/docs/security/NATIVE_PATH_VALIDATION.md b/docs/security/NATIVE_PATH_VALIDATION.md index 042ff63..1a52ba0 100644 --- a/docs/security/NATIVE_PATH_VALIDATION.md +++ b/docs/security/NATIVE_PATH_VALIDATION.md @@ -74,3 +74,28 @@ Sources / Quellen: - [Rust1.88 Windows path source](https://github.com/rust-lang/rust/blob/1.88.0/library/std/src/sys/path/windows.rs) - [GetFullPathNameW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew) - [CreateFileW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew) + +## Native follow-up / Nativer Folgeabgleich + +DE: d818ff3 besteht die vollständigen nativen Windows- und ARM-Jobs. Insbesondere +alle zehn Windows-Pfadfälle mit/ohne API einschließlich physischer Seitensperren, +248-Grenze, langer/relativer Pfade, Surrogate und Fehlerklassen tatsächlich grün. +EN: Full logs are retained; this is native execution, not cross-compilation only. + +DE: Linux-x86-CI findet dagegen eine echte Sandbox-Regression: rustix::fs::open +verwendet dort den alten open-Syscall, den die bestehende Allowlist korrekt +verweigert. ARM nutzt bereits openat. Der Adapter fordert nun explizit openat +mit CWD an; Allowlist/Landlock/Flags bleiben unverändert. Die bestehende Sandbox- +Probe prüft zusätzlich tatsächliche native Leseeingänge und fremde Pfadverweigerung +bei nachgewiesen aktivem Seccomp. Der betroffene echte CLI-Ablauf bleibt Teil der +Abnahme; ursprüngliche Fehlerprotokolle werden nicht als Erfolg umgedeutet. +EN: New complete Linux/native acceptance remains required after the targeted fix. + +DE: Abschließender lokaler openat-v1-Checkpoint: alle14 Befehle erfolgreich, +Quellen vor/nachher unverändert. Vier strenge Lints, je sechs Pfadgruppen, +echter CLI-Anonymitätsfall und sechs Sandbox-Gruppen in beiden Featurevarianten; +freigegebene native Pfade erreichbar, fremde gesperrt, Seccomp auf Zielarchitektur +nachweislich Full. Keine Allowlist-/Landlock-/Flagänderung. +EN: Complete native reruns for the corrected head remain required; previous +Linux failures retained and not counted as passes. Three unrelated unapproved +local token/thread prototype sources remain excluded and unexecuted. diff --git a/src/files/native_path.rs b/src/files/native_path.rs index 993fe7f..001c515 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -137,8 +137,11 @@ pub(super) fn open_file(path: &Path) -> Result { })?; #[cfg(target_os = "linux")] { - use rustix::fs::{Mode, OFlags, open}; - open( + use rustix::fs::{CWD, Mode, OFlags, openat}; + // DE: Unveränderte Sandbox nutzt openat, nicht den älteren x86-open-Syscall. + // EN: The unchanged sandbox permits openat, not legacy x86 open. + openat( + CWD, path.c_str()?, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty(), diff --git a/tests/sandbox_cli.rs b/tests/sandbox_cli.rs index f82ebba..21386a8 100644 --- a/tests/sandbox_cli.rs +++ b/tests/sandbox_cli.rs @@ -30,6 +30,8 @@ fn zz_probe_entry() { write_dirs: vec![root.join("ziel")], }; let report = sandbox::apply(&Profile::Cli(access)).unwrap(); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + assert_eq!(report.seccomp, sandbox::Status::Full); println!("LANDLOCK={}", report.landlock.as_str()); println!("RESULT={}", run_probe(&probe, &root)); std::process::exit(0); @@ -39,11 +41,23 @@ fn ok_or_err(r: &Result) -> &'static str { if r.is_ok() { "ok" } else { "err" } } +// DE: Fehlerhafter öffentlicher Header muss erreichbar sein; native Öffnungsverweigerung trennen. +// EN: An invalid public header must be reachable; distinguish native open denial. +fn native_read_probe(path: &Path) -> &'static str { + match pqkeep::files::inspect(path) { + Err(pqkeep::Error::InvalidInput { field: "header" }) => "ok", + Err(pqkeep::Error::Io(std::io::ErrorKind::PermissionDenied)) => "err", + _ => "unexpected", + } +} + fn run_probe(probe: &str, root: &Path) -> &'static str { let ziel = root.join("ziel"); match probe { "read_source" => ok_or_err(&std::fs::read(root.join("quelle.txt"))), + "read_source_native" => native_read_probe(&root.join("quelle.txt")), "read_other" => ok_or_err(&std::fs::read(root.join("fremd.txt"))), + "read_other_native" => native_read_probe(&root.join("fremd.txt")), "write_target" => { let file = ziel.join("neu.txt"); let steps = std::fs::write(&file, b"x") @@ -95,7 +109,7 @@ fn landlock_active(out: &Output) -> bool { #[test] fn permitted_paths_work() { - for name in ["read_source", "write_target"] { + for name in ["read_source", "read_source_native", "write_target"] { let (out, root, _dir) = probe(name); assert!( result(&out).contains("RESULT=ok"), @@ -111,7 +125,12 @@ fn permitted_paths_work() { #[test] fn other_paths_are_denied() { - for name in ["read_other", "write_outside", "symlink_target"] { + for name in [ + "read_other", + "read_other_native", + "write_outside", + "symlink_target", + ] { let (out, root, _dir) = probe(name); if !landlock_active(&out) && name != "symlink_target" { eprintln!("Landlock nicht verfügbar – {name} übersprungen / skipped"); From 3dc0fdf374013973045bd44456a6fd0597b564d7 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:41:59 +0100 Subject: [PATCH 13/26] fix(security): prelock source collection records and sort state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Quellrecords, Sortierindizes und konkreten Iterator vor privater Befüllung sperren; feldweises fallibles Wachstum und echte Speicherfehler prüfen. Alle 13 lokalen Prüfungen mit 876 unveränderten Quellen bestanden. R7/R8 bleiben gemeinsam in Arbeit. EN: Prelock source records, ordering and concrete iterator before private ingress; verify fallible fieldwise growth and real lock denial. All 13 source-bound local checks pass; native acceptance remains pending. No unsafe addition or security gate change. --- docs/ROADMAP.md | 7 + docs/SPEC.en.md | 6 + docs/SPEC.md | 7 + docs/security/SOURCE_RECORD_VALIDATION.md | 79 ++++++ src/files/confidential_text.rs | 11 + src/files/encrypt.rs | 29 +-- src/files/mod.rs | 2 + src/files/native_path.rs | 11 +- src/files/source_entries.rs | 158 ++++++++++++ src/files/source_entries_iter.rs | 46 ++++ src/files/source_entries_sort.rs | 64 +++++ src/files/source_entry.rs | 95 +++++++ src/files/source_entry_tests.rs | 292 ++++++++++++++++++++++ src/files/walk.rs | 101 +++----- tests/sandbox_cli.rs | 5 + 15 files changed, 827 insertions(+), 86 deletions(-) create mode 100644 docs/security/SOURCE_RECORD_VALIDATION.md create mode 100644 src/files/source_entries.rs create mode 100644 src/files/source_entries_iter.rs create mode 100644 src/files/source_entries_sort.rs create mode 100644 src/files/source_entry.rs create mode 100644 src/files/source_entry_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6742ad9..d05ba90 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -189,3 +189,10 @@ std-kompatibler248-Grenze. Quell-/Traversal-/Ziel-/Temppfade insgesamt weiter of EN: First actual native read adapters implemented and locally source-checked in the same Draft355; native acceptance pending, no M1/M3 closure. See [native path scope](security/NATIVE_PATH_VALIDATION.md). + +DE: Gesammelte Quellrecords, Sortierindizes und konkreter Iterator vor privater +Befüllung in gesperrten Arenen; Wachstum nur zwischen geschützten Zielen, +stabile Referenzreihenfolge ohne gewöhnlichen Sortier-Scratch. Abnahme offen. +EN: Actual single/tree/multi/container callers ported in the same joint work; +native traversal/skip/FS intermediates and other plan rows remain open. See +[source collection scope](security/SOURCE_RECORD_VALIDATION.md). diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 9362c8b..24b42c1 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -570,3 +570,9 @@ into prelocked UTF8/UTF16 destinations. Root forbid remains; necessary native Windows calls stay in the narrow platform adapter. Other traversal/target/temp paths and process/helper gaps remain open; see [native path scope](security/NATIVE_PATH_VALIDATION.md). + +R7/R8 work in progress: actual source collectors and archive writers use prelocked +source records, occupancy, sort indices and iterator state. Fallible growth copies +only between protected targets; stable ordering without ordinary record sorting +scratch. Native traversal, skip/filesystem intermediates and other R7/R8 gaps +remain open; see [source collection](security/SOURCE_RECORD_VALIDATION.md). diff --git a/docs/SPEC.md b/docs/SPEC.md index 49b0959..c47a8e9 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -576,3 +576,10 @@ verwendet vor Befüllung gesperrte UTF8-/UTF16-Ziele. Root-forbid bleibt erhalte notwendige native Windows-Aufrufe bleiben im schmalen Plattformadapter. Übrige Traversal-/Ziel-/Temppfad- und Prozess-/Helper-Lücken bleiben offen; siehe [Nativer Pfadumfang](security/NATIVE_PATH_VALIDATION.md). + +R7/R8-Arbeitsstand: Tatsächliche Quellsammler und Archivschreiber verwenden vorab +gesperrte Quelleinträge, Belegung, Sortierindizes und Iteratorzustände. Fallibles +Wachstum kopiert nur zwischen gesperrten Zielen; stabile Reihenfolge ohne +gewöhnlichen Record-Sortierscratch. Native Traversierung, Skip-/FS-Zwischenwerte +und übrige R7/R8-Flächen bleiben offen; siehe +[Quellsammlung](security/SOURCE_RECORD_VALIDATION.md). diff --git a/docs/security/SOURCE_RECORD_VALIDATION.md b/docs/security/SOURCE_RECORD_VALIDATION.md new file mode 100644 index 0000000..c8227b0 --- /dev/null +++ b/docs/security/SOURCE_RECORD_VALIDATION.md @@ -0,0 +1,79 @@ +# Protected source collection / Geschützte Quellsammlung + +DE: Teil von R7/R8 im gemeinsamen Draft355. Diese Komponente schützt die +gesammelten Quelleinträge vor ihrer privaten Befüllung; sie schließt M1/M2/M3 +insgesamt noch nicht ab. CLI-/Archivbytes und bestehende Pfadregeln bleiben erhalten. +EN: Private implementation types only; no public Rust signature or wire-format +change. Source, traversal, skip and filesystem-adapter boundaries are listed below. + +## Concrete ownership / Konkretes Eigentum + +DE: SourceEntries sperrt den gesamten Sammlungszustand, die tatsächlichen +SourceEntry-Slots und ihre Sortierindizes vor Befüllung. Relative Texte, native +UTF8-/UTF16-Pfade, Art, Größe, Belegung, Wachstumscursor und Sortierpositionen +bleiben in gesperrten Zielen. Keine privaten SourceEntry-Werte als Rückgaben, +kein gewöhnlicher Vec mit privaten Records oder ihren Sperrdeskriptoren. +EN: Public-empty default slots are locked before fill. Required nested owners are +fallible; a partial fill is wiped before slot reuse and does not increase occupancy. +There is no unprotected allocation or std conversion fallback on lock failure. + +DE: Wachstum kopiert einzelne Felder zwischen bereits gesperrten Arenen. +Namen und native Pfade werden explizit fallibel dupliziert. Scheitert eine Kopie, +wird das neue Ziel unter seiner Sperre gelöscht; die alte Sammlung bleibt gültig. +Die alte Arena einschließlich freier Kapazität und Padding wird vor Unlock/Free +gelöscht. Vorhandene SecretState-/SecretWorkspace-Mechanismen bleiben maßgeblich. +EN: No whole populated source record is moved through an ordinary sort buffer. +In-place heapsort swaps protected scalar indices, with original indices breaking +ties to retain the previous stable ordering. Record payloads stay stationary. + +DE: try_iter sperrt den konkreten Cursor einschließlich Quell-Borrow vor Eintritt. +Private Positionen verbleiben im gesperrten Zustand. Fehlerhafte interne Indizes +liefern einen expliziten Fehler statt stillschweigend Einträge auszulassen. +EN: Record borrows cannot outlive the collection. No Clone/Debug/Serialize exposes +the collection; scalar fields are borrowed/read only by the intended archive writer. +Intrinsic compiler/register/ownership transit is not a claim of whole-stack wiping. + +## Reached paths / Tatsächliche Pfade + +DE: Einzeldatei-, Ordner-, Mehrfach- und Container-Sammlung sowie der echte +Archivschreiber verwenden SourceEntries. Relative Pfade und Traversierungspräfixe +werden direkt in gesperrten UTF8-Zielen zusammengesetzt; das vorherige format!- +Staging gültiger Namen entfällt. Der Dateileser leiht den gespeicherten nativen +Pfad direkt aus, ohne Rückkonvertierung zu PathBuf oder neuer gewöhnlicher Kopie. +EN: Existing native read adapters preserve explicit openat/CLOEXEC on Linux and +the verified Windows normalization/read-sharing behavior. No sandbox rule changes. + +## Verification and remaining scope / Prüfung und offene Flächen + +DE: Prüfungen müssen echte gesperrte Zustände, vollständige Record-/Indexarenen, +relative/native Blattpuffer und Iteratoren zeigen; Windows mit dem vorhandenen +gesperrten nativen Seitenbeobachter. Referenzsortierung einschließlich gleicher +Namen, Wachstumsgrenzen, gültige Dateiinhalte und fehlgeschlagene Slotbefüllung. +EN: Bounded own Linux children exercise actual zero-budget refusal, failure after +some growth copies already succeeded, previous-state preservation, unwind, native +lock cleanup and unchanged parent limits. Native acceptance of this source-record +component is pending; the local checkpoint below passed. + +DE: Weiter offen: read_dir-/DirEntry-/fs::Metadata-Zwischenwerte, gewöhnliche +native Traversierungspfade/-stapel, Top-Level-to_lowercase/BTreeSet und Skip-Records. +M3 umfasst weiterhin Ziel-/Temp-/Cleanup-/Publish-Pfade und die aus Main358 +übernommenen Handle-/Identitäts-/Metadatenrecords. Berichte, Serialisierung, +CLI-Kontext und Prozess-/Helper-Verträge bleiben eigene tatsächliche Lücken. +EN: These internal buffers are not reclassified as caller-owned memory or compiler +boundaries. Known ignored338 source-race coverage stays explicit. This component +does not claim to close338, all of M1/M2/M3, R7/R8 or147. + +## Local checkpoint / Lokaler Prüfstand + +DE: source-records-v1 bindet 876 Rust-/Manifest-Hashes vor und nach allen +13 erfolgreichen Kommandos unverändert. Vier strenge All-Target-Clippy-Läufe +prüfen Linux und Windows-GNU jeweils mit/ohne API; jeweils 85 Datei-Testgruppen +bestanden. Zehn explizit ignorierte Kind-/Race-Einstiegspunkte bleiben sichtbar; +die beiden eigenen Speicherfehler-Kinder werden vom bestandenen Elternfall +tatsächlich ausgeführt. 57 Integrationsfälle prüfen echte Datei-/CLI-/JSON-, +anonyme, signierte und verborgene Absender sowie Sandbox-Pfade. +EN: Root/platform formatting, size limits, vendor inventory, attack-matrix and +diff checks passed. The native sandbox cases now require actual Landlock support +rather than reporting an unsupported kernel as proof of denial. No sandbox rule, +security gate, dependency version or unsafe boundary was weakened or added. +The separate Windows process probe remains unsuccessful; no R7/R8 closure. diff --git a/src/files/confidential_text.rs b/src/files/confidential_text.rs index 71773d2..22ecea6 100644 --- a/src/files/confidential_text.rs +++ b/src/files/confidential_text.rs @@ -17,6 +17,17 @@ impl Zeroize for ConfidentialText { } impl ConfidentialText { + pub(crate) fn joined(left: &str, right: &str) -> Result { + let len = left + .len() + .checked_add(right.len()) + .ok_or(Error::MemoryLock)?; + let mut bytes = SecretBytes::zeroed(len)?; + bytes.expose_mut()[..left.len()].copy_from_slice(left.as_bytes()); + bytes.expose_mut()[left.len()..].copy_from_slice(right.as_bytes()); + Self::from_locked(bytes) + } + pub(crate) fn prepare() -> Result { Ok(Self(SecretState::new(SecretBytes::zeroed(0)?)?)) } diff --git a/src/files/encrypt.rs b/src/files/encrypt.rs index 2a00c46..f906418 100644 --- a/src/files/encrypt.rs +++ b/src/files/encrypt.rs @@ -13,8 +13,8 @@ use super::format::Content; use super::output::TempOutput; use super::signed_io::{HashingWriter, check_signing_key}; use super::tail_v4::TailWrite; -use super::walk::{self, SourceEntry, SourceKind}; use super::{EncryptOptions, Protection, Report}; +use super::{source_entries::SourceEntries, source_entry::SourceEntry, walk}; use crate::crypto::stream::{EncryptWriter, PREFIX_LEN}; use crate::crypto::{aead, rng}; use crate::envelope::UnlockedKey; @@ -84,7 +84,7 @@ fn encrypt_with( let (e, s) = walk::collect_dir(source)?; (e, s, Content::Directory) } else { - (vec![walk::collect_file(source)?], Vec::new(), Content::File) + (walk::collect_file(source)?, Vec::new(), Content::File) }; let job = Job { target, @@ -204,7 +204,7 @@ pub fn encrypt_many_under( } fn write_archive( - entries: &[SourceEntry], + entries: &SourceEntries, skipped: Vec, content: Content, job: &Job<'_>, @@ -240,8 +240,8 @@ fn write_archive( skipped, ..Report::default() }; - for entry in entries { - write_entry(&mut archive, entry, &mut report)?; + for entry in entries.try_iter()? { + write_entry(&mut archive, entry?, &mut report)?; } // DE: Jede v4-Datei (Füllung, anonym, verborgener Absender) hat einen Trailer. // EN: Every v4 file (padding, anonymous, hidden sender) has a trailer. @@ -269,17 +269,14 @@ fn write_entry( entry: &SourceEntry, report: &mut Report, ) -> Result<()> { - match entry.kind { - SourceKind::Dir => { - archive.dir(&entry.rel)?; - report.directories += 1; - } - SourceKind::File(size) => { - let mut reader = super::native_path::open_file(&entry.abs)?; - archive.file(&entry.rel, &mut reader, size)?; - report.files += 1; - report.bytes += size; - } + if entry.is_directory() { + archive.dir(entry.path()?)?; + report.directories += 1; + } else { + let mut reader = entry.open()?; + archive.file(entry.path()?, &mut reader, entry.size())?; + report.files += 1; + report.bytes += entry.size(); } Ok(()) } diff --git a/src/files/mod.rs b/src/files/mod.rs index 1f3b53c..4672ee0 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -48,6 +48,8 @@ mod signed_by; mod signed_io; mod signer_v3; mod slot_v2; +mod source_entries; +mod source_entry; mod stream_v4; mod tail_v4; mod tail_v4_drain; diff --git a/src/files/native_path.rs b/src/files/native_path.rs index 001c515..fa24451 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -68,14 +68,12 @@ impl NativePath { } } - #[cfg(any(unix, test))] pub(super) fn from_native(source: &[Unit]) -> Result { let mut out = Self::prepare()?; out.copy_native(source)?; Ok(out) } - #[cfg(any(unix, test))] pub(super) fn copy_native(&mut self, source: &[Unit]) -> Result<()> { if source.contains(&0) { return Err(Error::InvalidInput { field: "path" }); @@ -106,7 +104,6 @@ impl NativePath { std::ffi::CStr::from_bytes_with_nul(self.encoded()?).map_err(|_| Error::Crypto) } - #[cfg(test)] pub(super) fn try_duplicate(&self) -> Result { let units = self.encoded()?; Self::from_native(&units[..units.len() - 1]) @@ -135,6 +132,10 @@ pub(super) fn open_file(path: &Path) -> Result { Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), other => other, })?; + open_native(&path) +} + +pub(super) fn open_native(path: &NativePath) -> Result { #[cfg(target_os = "linux")] { use rustix::fs::{CWD, Mode, OFlags, openat}; @@ -151,8 +152,8 @@ pub(super) fn open_file(path: &Path) -> Result { } #[cfg(windows)] { - let normalized = windows::for_open(&path)?; - pqkeep_platform::open_file_read(normalized.as_ref().unwrap_or(&path).encoded()?) + let normalized = windows::for_open(path)?; + pqkeep_platform::open_file_read(normalized.as_ref().unwrap_or(path).encoded()?) .map_err(Into::into) } #[cfg(not(any(target_os = "linux", windows)))] diff --git a/src/files/source_entries.rs b/src/files/source_entries.rs new file mode 100644 index 0000000..c38351c --- /dev/null +++ b/src/files/source_entries.rs @@ -0,0 +1,158 @@ +//! DE: Quellrecords, Permutation und Geometrie vor privatem Eintritt sperren. +//! EN: Prelock source records, permutation and geometry before private ingress. + +use super::{paths::MAX_ENTRIES, source_entry::SourceEntry}; +use crate::{ + Error, Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, +}; +use std::path::Path; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct Sort { + start: usize, + end: usize, + root: usize, + child: usize, +} +impl Zeroize for Sort { + fn zeroize(&mut self) { + self.start.zeroize(); + self.end.zeroize(); + self.root.zeroize(); + self.child.zeroize(); + } +} + +struct State { + records: SecretWorkspace, + order: SecretWorkspace, + used: usize, + scan: usize, + sort: Sort, +} +impl Zeroize for State { + fn zeroize(&mut self) { + self.records.zeroize(); + self.order.zeroize(); + self.used.zeroize(); + self.scan.zeroize(); + self.sort.zeroize(); + } +} +impl Drop for State { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for State {} +impl ZeroizeOnDrop for crate::crypto::secret_buffer::SecretBuffer {} + +pub(crate) struct SourceEntries(SecretState); + +#[path = "source_entries_iter.rs"] +mod iteration; +#[path = "source_entries_sort.rs"] +mod sorting; + +impl SourceEntries { + pub(super) fn prepare() -> Result { + Ok(Self(SecretState::new(State { + records: SecretWorkspace::zeroed(0)?, + order: SecretWorkspace::zeroed(0)?, + used: 0, + scan: 0, + sort: Sort::default(), + })?)) + } + + pub(super) fn len(&self) -> usize { + self.0.get().used + } + + pub(super) fn push( + &mut self, + rel: &str, + abs: &Path, + directory: bool, + bytes: u64, + ) -> Result<()> { + let state = self.0.get_mut(); + state.reserve()?; + let slot = &mut state.records.expose_mut()[state.used]; + if let Err(error) = slot.fill(rel, abs, directory, bytes) { + slot.zeroize(); + return Err(error); + } + state.order.expose_mut()[state.used] = state.used; + state.used += 1; + Ok(()) + } + + pub(super) fn get(&self, position: usize) -> Result<&SourceEntry> { + self.0.get().entry(position) + } + + pub(super) fn prepend_all(&mut self, root: &str) -> Result<()> { + let state = self.0.get_mut(); + state.scan = 0; + while state.scan < state.used { + state.records.expose_mut()[state.scan].prepend(root)?; + state.scan += 1; + } + state.scan = 0; + Ok(()) + } +} + +impl State { + fn entry(&self, position: usize) -> Result<&SourceEntry> { + if position >= self.used { + return Err(Error::Crypto); + } + let index = *self.order.expose().get(position).ok_or(Error::Crypto)?; + if index >= self.used { + return Err(Error::Crypto); + } + let entry = self.records.expose().get(index).ok_or(Error::Crypto)?; + if entry.rel.is_none() || entry.abs.is_none() { + return Err(Error::Crypto); + } + Ok(entry) + } + + fn reserve(&mut self) -> Result<()> { + let limit = usize::try_from(MAX_ENTRIES).map_err(|_| Error::MemoryLock)?; + if self.used >= limit { + return Err(Error::InvalidInput { field: "entries" }); + } + if self.used < self.records.expose().len() { + return Ok(()); + } + let capacity = self + .used + .checked_mul(2) + .ok_or(Error::MemoryLock)? + .max(16) + .min(limit); + let mut records = SecretWorkspace::::zeroed(capacity)?; + let mut order = SecretWorkspace::::zeroed(capacity)?; + self.scan = 0; + // DE: Nur Feldkopien zwischen gesperrten Zielen; alte Sammlung bleibt bei Fehler gültig. + // EN: Copy fields only between protected targets; failure preserves the old collection. + while self.scan < self.used { + records.expose_mut()[self.scan].copy_from(&self.records.expose()[self.scan])?; + order.expose_mut()[self.scan] = self.order.expose()[self.scan]; + self.scan += 1; + } + self.records = records; + self.order = order; + self.scan = 0; + Ok(()) + } +} + +#[cfg(test)] +#[path = "source_entry_tests.rs"] +mod tests; diff --git a/src/files/source_entries_iter.rs b/src/files/source_entries_iter.rs new file mode 100644 index 0000000..51fe621 --- /dev/null +++ b/src/files/source_entries_iter.rs @@ -0,0 +1,46 @@ +//! DE: Konkreten Iterator mit Quelle und laufender Position vor Nutzung sperren. +//! EN: Prelock the concrete iterator source and running position before use. +use super::{Result, SecretState, SourceEntries, SourceEntry}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +pub(super) struct Cursor<'a> { + source: Option<&'a SourceEntries>, + position: usize, +} +impl Zeroize for Cursor<'_> { + fn zeroize(&mut self) { + self.source = None; + self.position.zeroize(); + } +} +impl Drop for Cursor<'_> { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for Cursor<'_> {} + +pub(crate) struct Iter<'a>(pub(super) SecretState>); +impl SourceEntries { + pub(crate) fn try_iter(&self) -> Result> { + let mut out = Iter(SecretState::new(Cursor { + source: None, + position: 0, + })?); + out.0.get_mut().source = Some(self); + Ok(out) + } +} +impl<'a> Iterator for Iter<'a> { + type Item = Result<&'a SourceEntry>; + fn next(&mut self) -> Option { + let cursor = self.0.get_mut(); + let source = cursor.source?; + if cursor.position >= source.len() { + return None; + } + let entry = source.get(cursor.position); + cursor.position += 1; + Some(entry) + } +} diff --git a/src/files/source_entries_sort.rs b/src/files/source_entries_sort.rs new file mode 100644 index 0000000..6dbf42f --- /dev/null +++ b/src/files/source_entries_sort.rs @@ -0,0 +1,64 @@ +//! DE: Nur gesperrte skalare Indizes tauschen; keine Record- oder Sortier-Scratchkopie. +//! EN: Swap locked scalar indices only; no record or sorting scratch copy. +use super::{Result, SourceEntries, State}; +use std::cmp::Ordering; + +impl SourceEntries { + pub(crate) fn sort(&mut self) -> Result<()> { + let state = self.0.get_mut(); + state.sort.start = state.used / 2; + state.sort.end = state.used; + while state.sort.start > 0 { + state.sort.start -= 1; + state.sort.root = state.sort.start; + state.sift()?; + } + while state.sort.end > 1 { + state.sort.end -= 1; + state.order.expose_mut().swap(0, state.sort.end); + state.sort.root = 0; + state.sift()?; + } + state.sort.zeroize(); + Ok(()) + } +} + +use zeroize::Zeroize; +impl State { + fn compare(&self, a: usize, b: usize) -> Result { + // DE: Originalindex erhält auch bei gleichen Pfaden die bisherige stabile Reihenfolge. + // EN: Original indices retain the previous stable order even for equal paths. + Ok(self + .entry(a)? + .path_bytes() + .cmp(self.entry(b)?.path_bytes()) + .then(self.order.expose()[a].cmp(&self.order.expose()[b]))) + } + + fn sift(&mut self) -> Result<()> { + loop { + self.sort.child = self + .sort + .root + .checked_mul(2) + .and_then(|n| n.checked_add(1)) + .ok_or(crate::Error::MemoryLock)?; + if self.sort.child >= self.sort.end { + return Ok(()); + } + if self.sort.child + 1 < self.sort.end + && self.compare(self.sort.child, self.sort.child + 1)? == Ordering::Less + { + self.sort.child += 1; + } + if self.compare(self.sort.root, self.sort.child)? != Ordering::Less { + return Ok(()); + } + self.order + .expose_mut() + .swap(self.sort.root, self.sort.child); + self.sort.root = self.sort.child; + } + } +} diff --git a/src/files/source_entry.rs b/src/files/source_entry.rs new file mode 100644 index 0000000..7826328 --- /dev/null +++ b/src/files/source_entry.rs @@ -0,0 +1,95 @@ +//! DE: Retinierte Quelldatensätze vor privaten Feldern stabil sperren. +//! EN: Stably lock retained source records before filling private fields. + +use super::{ConfidentialText, native_path::NativePath, paths}; +use crate::{Error, Result, crypto::SecretBytes}; +use std::path::Path; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +pub(crate) struct SourceEntry { + pub(super) rel: Option, + pub(super) abs: Option, + directory: bool, + bytes: u64, +} + +impl Zeroize for SourceEntry { + fn zeroize(&mut self) { + self.rel = None; + self.abs = None; + self.directory.zeroize(); + self.bytes.zeroize(); + } +} +impl Drop for SourceEntry { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for SourceEntry {} + +impl SourceEntry { + // DE: Nur bereits gesperrte Arenaslots befüllen; keine privaten Record-Rückgaben. + // EN: Populate only prelocked arena slots; no private record return values. + pub(super) fn fill( + &mut self, + rel: &str, + abs: &Path, + directory: bool, + bytes: u64, + ) -> Result<()> { + if self.rel.is_some() || self.abs.is_some() { + return Err(Error::Crypto); + } + self.rel = Some(ConfidentialText::from_text(rel)?); + self.abs = Some(NativePath::from_path(abs)?); + self.directory = directory; + self.bytes = bytes; + Ok(()) + } + + pub(super) fn copy_from(&mut self, source: &Self) -> Result<()> { + if self.rel.is_some() || self.abs.is_some() { + return Err(Error::Crypto); + } + self.rel = Some(source.rel.as_ref().ok_or(Error::Crypto)?.try_duplicate()?); + self.abs = Some(source.abs.as_ref().ok_or(Error::Crypto)?.try_duplicate()?); + self.directory = source.directory; + self.bytes = source.bytes; + Ok(()) + } + + pub(super) fn path(&self) -> Result<&str> { + self.rel.as_ref().ok_or(Error::Crypto)?.expose() + } + pub(super) fn path_bytes(&self) -> &[u8] { + self.rel.as_ref().map_or(&[], ConfidentialText::bytes) + } + pub(super) fn is_directory(&self) -> bool { + self.directory + } + pub(super) fn size(&self) -> u64 { + self.bytes + } + + pub(super) fn open(&self) -> Result { + super::native_path::open_native(self.abs.as_ref().ok_or(Error::Crypto)?) + } + + /// DE: Präfix direkt gesperrt zusammensetzen; bisherigen Zustand bei Fehler erhalten. + /// EN: Assemble the prefix directly in locked storage; preserve old state on error. + pub(super) fn prepend(&mut self, root: &str) -> Result<()> { + let original = self.path_bytes(); + let head = root.len().checked_add(1).ok_or(Error::MemoryLock)?; + let len = head.checked_add(original.len()).ok_or(Error::MemoryLock)?; + let mut bytes = SecretBytes::zeroed(len)?; + bytes.expose_mut()[..root.len()].copy_from_slice(root.as_bytes()); + bytes.expose_mut()[root.len()] = b'/'; + bytes.expose_mut()[head..].copy_from_slice(original); + let rel = ConfidentialText::from_locked(bytes)?; + paths::validate_only(rel.expose()?)?; + self.rel = Some(rel); + Ok(()) + } +} diff --git a/src/files/source_entry_tests.rs b/src/files/source_entry_tests.rs new file mode 100644 index 0000000..fd34fa7 --- /dev/null +++ b/src/files/source_entry_tests.rs @@ -0,0 +1,292 @@ +//! DE: Echte Quelldatensätze, stabile Sperren und fallible Präfixübernahme. +//! EN: Actual source records, stable locks and fallible prefix adoption. +#![allow(clippy::unwrap_used)] + +use super::*; +use crate::crypto::SecretBytes; +use std::io::Read; + +fn locked(value: &T) { + crate::locked_owner_test_support::locked(value); + #[cfg(windows)] + if size_of_val(value) > 0 { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let address = std::ptr::from_ref(value).addr(); + assert!(query.get_mut().is_locked(address).unwrap()); + assert!( + query + .get_mut() + .is_locked(address + size_of_val(value) - 1) + .unwrap() + ); + } +} + +fn owners(entries: &SourceEntries) { + let state = entries.0.get(); + locked(state); + locked(state.records.expose()); + locked(state.order.expose()); + for entry in &state.records.expose()[..state.used] { + locked(entry); + locked(entry.rel.as_ref().unwrap().bytes()); + if let Some(path) = &entry.abs { + locked(path.encoded().unwrap()); + } + } +} + +#[test] +fn actual_collected_source_records_stay_locked_through_moves_and_sorting() { + let root = tempfile::tempdir().unwrap(); + for name in ["z.txt", "ä.txt", "a.txt"] { + std::fs::write(root.path().join(name), b"public source fixture").unwrap(); + } + let (entries, skipped) = super::super::walk::collect_dir(root.path()).unwrap(); + let no_skipped_entries = skipped.is_empty(); + assert!(no_skipped_entries); + assert_eq!(entries.len(), 3); + owners(&entries); + for (entry, expected) in entries.try_iter().unwrap().zip(["a.txt", "z.txt", "ä.txt"]) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == expected; + assert!(equal); + assert!(!entry.is_directory()); + assert_eq!(entry.size(), b"public source fixture".len() as u64); + let mut contents = SecretBytes::zeroed(usize::try_from(entry.size()).unwrap()).unwrap(); + entry + .open() + .unwrap() + .read_exact(contents.expose_mut()) + .unwrap(); + let equal = contents.expose() == b"public source fixture"; + assert!(equal); + } +} + +#[test] +fn prelocked_empty_record_and_prefixed_records_preserve_original_on_validation_error() { + let empty = SourceEntries::prepare().unwrap(); + owners(&empty); + let mut entry = SourceEntries::prepare().unwrap(); + entry + .push("child.txt", Path::new("public fixture"), false, 9) + .unwrap(); + entry.prepend_all("root").unwrap(); + let equal = entry.get(0).unwrap().path().unwrap() == "root/child.txt"; + assert!(equal); + owners(&entry); + assert!(entry.prepend_all("../invalid").is_err()); + let unchanged = entry.get(0).unwrap().path().unwrap() == "root/child.txt"; + assert!(unchanged); + assert_eq!(entry.get(0).unwrap().size(), 9); +} + +#[cfg(target_os = "linux")] +fn kernel_locked_bytes() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + status + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + .checked_mul(1024) + .unwrap() +} + +#[cfg(target_os = "linux")] +#[test] +fn real_source_record_denial_and_unwind_run_in_owned_child() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::source_entries::tests::source_record_denial_child", + "PQKEEP_SOURCE_RECORD_CHILD", + ); + crate::locked_owner_test_support::isolated_test( + "files::source_entries::tests::partial_growth_denial_child", + "PQKEEP_SOURCE_RECORD_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn source_record_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_SOURCE_RECORD_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let unwind = std::panic::catch_unwind(|| { + let mut entry = SourceEntries::prepare().unwrap(); + entry + .push("public.txt", Path::new("public fixture"), false, 9) + .unwrap(); + owners(&entry); + std::panic::resume_unwind(Box::new(())); + }); + assert!(unwind.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let mut entry = SourceEntries::prepare().unwrap(); + for index in 0..128 { + entry + .push( + &format!("entry-{index:03}"), + Path::new("public fixture"), + false, + 9, + ) + .unwrap(); + } + let prefix = "x".repeat(2 * region::page::size()); + let baseline = memlock::stats().locked_pages; + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(0)); + assert!(matches!( + entry.push("new", Path::new("fixture"), false, 1), + Err(Error::MemoryLock) + )); + assert_eq!(entry.len(), 128); + assert!(matches!(entry.prepend_all(&prefix), Err(Error::MemoryLock))); + assert_eq!(memlock::stats().locked_pages, baseline); + let unchanged = entry.get(0).unwrap().path().unwrap() == "entry-000"; + assert!(unchanged); + assert_eq!(entry.get(0).unwrap().size(), 9); +} + +#[test] +fn protected_index_sort_preserves_fields_across_growth_boundaries() { + for length in [0, 1, 2, 3, 16, 17, 31, 32, 65] { + let mut entries = SourceEntries::prepare().unwrap(); + for index in (0..length).rev() { + entries + .push( + &format!("entry-{index:03}"), + Path::new("public fixture"), + index % 2 == 0, + u64::try_from(index).unwrap(), + ) + .unwrap(); + } + entries.sort().unwrap(); + owners(&entries); + for (entry, index) in entries.try_iter().unwrap().zip(0..length) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == format!("entry-{index:03}"); + assert!(equal); + assert_eq!(entry.size(), u64::try_from(index).unwrap()); + assert_eq!(entry.is_directory(), index % 2 == 0); + } + } +} + +#[test] +fn iterator_source_and_cursor_remain_protected_while_advancing() { + let mut entries = SourceEntries::prepare().unwrap(); + entries + .push("a", Path::new("public fixture"), false, 1) + .unwrap(); + entries + .push("b", Path::new("public fixture"), true, 0) + .unwrap(); + let mut iterator = entries.try_iter().unwrap(); + locked(iterator.0.get()); + let equal = iterator.next().unwrap().unwrap().path().unwrap() == "a"; + assert!(equal); + locked(iterator.0.get()); + let equal = iterator.next().unwrap().unwrap().path().unwrap() == "b"; + assert!(equal); + locked(iterator.0.get()); + assert!(iterator.next().is_none()); +} + +#[test] +fn equal_path_order_matches_the_previous_stable_reference_sort() { + let mut entries = SourceEntries::prepare().unwrap(); + let mut reference = Vec::new(); + for index in (0..65u64).rev() { + let path = format!("public-{}", index % 5); + entries + .push(&path, Path::new("public fixture"), false, index) + .unwrap(); + reference.push((path, index)); + } + reference.sort_by(|a, b| a.0.cmp(&b.0)); + entries.sort().unwrap(); + for (entry, (path, size)) in entries.try_iter().unwrap().zip(reference) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == path; + assert!(equal); + assert_eq!(entry.size(), size); + } +} + +#[test] +fn partial_native_path_failure_cleans_slot_and_preserves_previous_entries() { + let mut entries = SourceEntries::prepare().unwrap(); + entries + .push("old", Path::new("public fixture"), false, 9) + .unwrap(); + assert!(matches!( + entries.push("new", Path::new("public\0fixture"), true, 0), + Err(Error::InvalidInput { field: "path" }) + )); + assert_eq!(entries.len(), 1); + assert!(entries.0.get().records.expose()[1].rel.is_none()); + assert!(entries.0.get().records.expose()[1].abs.is_none()); + let unchanged = entries.get(0).unwrap().path().unwrap() == "old"; + assert!(unchanged); + entries + .push("new", Path::new("public fixture"), true, 0) + .unwrap(); + assert_eq!(entries.len(), 2); + owners(&entries); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded owned child only"] +fn partial_growth_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_SOURCE_RECORD_CHILD").unwrap(), "1"); + let baseline = memlock::stats().locked_pages; + let kernel_baseline = kernel_locked_bytes(); + let mut entries = SourceEntries::prepare().unwrap(); + let page = region::page::size(); + let source = "x".repeat(2 * page); + for index in 0..16 { + entries + .push(&format!("entry-{index:02}"), Path::new(&source), false, 9) + .unwrap(); + } + let budget = kernel_locked_bytes().checked_add(12 * page).unwrap(); + let mut limit = getrlimit(Resource::Memlock); + let budget = u64::try_from(budget).unwrap(); + assert!(limit.current.is_none_or(|original| budget < original)); + limit.current = Some(budget); + setrlimit(Resource::Memlock, limit).unwrap(); + assert_eq!(getrlimit(Resource::Memlock).current, Some(budget)); + let before = memlock::stats().locked_pages; + assert!(matches!( + entries.push("new", Path::new(&source), false, 1), + Err(Error::MemoryLock) + )); + assert!(entries.0.get().scan > 0 && entries.0.get().scan < entries.len()); + assert_eq!(entries.len(), 16); + assert_eq!(memlock::stats().locked_pages, before); + owners(&entries); + let unchanged = entries.get(0).unwrap().path().unwrap() == "entry-00"; + assert!(unchanged); + drop(entries); + assert_eq!(memlock::stats().locked_pages, baseline); + assert_eq!(kernel_locked_bytes(), kernel_baseline); +} diff --git a/src/files/walk.rs b/src/files/walk.rs index 7c28ed8..ed4bd7a 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -9,7 +9,9 @@ use std::fs; use std::path::{Path, PathBuf}; +use super::ConfidentialText; use super::paths::{self, MAX_ENTRIES}; +use super::source_entries::SourceEntries; use crate::{Error, Result}; /// DE: Grund für das Überspringen. EN: Reason for skipping. @@ -36,22 +38,15 @@ pub struct Skipped { pub reason: SkipReason, } -/// DE: Art eines Quelleintrags. EN: Kind of source entry. -pub(crate) enum SourceKind { - Dir, - File(u64), -} - -/// DE: Quelleintrag mit relativem Archivpfad. EN: Source entry with relative archive path. -pub(crate) struct SourceEntry { - pub rel: String, - pub abs: PathBuf, - pub kind: SourceKind, -} - /// DE: Einzeldatei als einziger Eintrag (Name muss portabel sein). /// EN: Single file as the only entry (name must be portable). -pub(crate) fn collect_file(path: &Path) -> Result { +pub(crate) fn collect_file(path: &Path) -> Result { + let mut entries = SourceEntries::prepare()?; + collect_file_into(path, &mut entries)?; + Ok(entries) +} + +fn collect_file_into(path: &Path, entries: &mut SourceEntries) -> Result<()> { let meta = fs::symlink_metadata(path)?; if !meta.file_type().is_file() { return Err(Error::InvalidInput { field: "source" }); @@ -61,19 +56,15 @@ pub(crate) fn collect_file(path: &Path) -> Result { .and_then(|n| n.to_str()) .ok_or(Error::InvalidInput { field: "path" })?; paths::validate_only(name)?; - Ok(SourceEntry { - rel: name.to_owned(), - abs: path.to_path_buf(), - kind: SourceKind::File(meta.len()), - }) + entries.push(name, path, false, meta.len()) } /// DE: Ordner rekursiv; der Ordner selbst ist nicht Teil des Archivs. /// EN: Directory recursively; the directory itself is not part of the archive. -pub(crate) fn collect_dir(root: &Path) -> Result<(Vec, Vec)> { - let (mut entries, mut skipped) = (Vec::new(), Vec::new()); +pub(crate) fn collect_dir(root: &Path) -> Result<(SourceEntries, Vec)> { + let (mut entries, mut skipped) = (SourceEntries::prepare()?, Vec::new()); collect_tree(root, "", &mut entries, &mut skipped)?; - entries.sort_by(|a, b| a.rel.cmp(&b.rel)); + entries.sort()?; Ok((entries, skipped)) } @@ -83,11 +74,11 @@ pub(crate) fn collect_dir(root: &Path) -> Result<(Vec, Vec /// EN: Several sources as one archive (multi-selection): each source becomes a top-level entry, /// directories with their content. Equal names (ignoring case) → abort; a selected symlink is /// skipped and reported. -pub(crate) fn collect_many(sources: &[&Path]) -> Result<(Vec, Vec)> { +pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, Vec)> { if sources.is_empty() || sources.len() as u64 > MAX_ENTRIES { return Err(Error::InvalidInput { field: "source" }); } - let (mut entries, mut skipped) = (Vec::new(), Vec::new()); + let (mut entries, mut skipped) = (SourceEntries::prepare()?, Vec::new()); let mut names = std::collections::BTreeSet::new(); for src in sources { let name = src @@ -105,17 +96,14 @@ pub(crate) fn collect_many(sources: &[&Path]) -> Result<(Vec, Vec Result<(Vec, Vec Result<(Vec, Vec)> { +) -> Result<(SourceEntries, Vec)> { if paths::validate(root)?.len() != 1 { return Err(Error::InvalidInput { field: "path" }); } - let (inner, skipped) = collect_many(sources)?; - let mut entries = Vec::with_capacity(inner.len() + 1); - entries.push(SourceEntry { - rel: root.to_owned(), - abs: PathBuf::new(), - kind: SourceKind::Dir, - }); - for mut entry in inner { - entry.rel = format!("{root}/{}", entry.rel); - paths::validate_only(&entry.rel)?; - entries.push(entry); - } + let (mut entries, skipped) = collect_many(sources)?; + entries.prepend_all(root)?; + entries.push(root, Path::new(""), true, 0)?; + entries.sort()?; Ok((entries, skipped)) } @@ -149,13 +129,13 @@ pub(crate) fn collect_under( fn collect_tree( root: &Path, base: &str, - entries: &mut Vec, + entries: &mut SourceEntries, skipped: &mut Vec, ) -> Result<()> { if !fs::symlink_metadata(root)?.file_type().is_dir() { return Err(Error::InvalidInput { field: "source" }); } - let mut stack = vec![(root.to_path_buf(), base.to_owned())]; + let mut stack = vec![(root.to_path_buf(), ConfidentialText::from_text(base)?)]; while let Some((dir, prefix)) = stack.pop() { let mut children: Vec<_> = fs::read_dir(&dir)?.collect::>()?; children.sort_by_key(fs::DirEntry::file_name); @@ -163,7 +143,7 @@ fn collect_tree( // EN: Pushed in reverse so that the order stays alphabetical. let mut subdirs = Vec::new(); for child in children { - visit(&child, &prefix, entries, skipped, &mut subdirs)?; + visit(&child, prefix.expose()?, entries, skipped, &mut subdirs)?; if entries.len() as u64 > MAX_ENTRIES { return Err(Error::InvalidInput { field: "entries" }); } @@ -176,15 +156,14 @@ fn collect_tree( fn visit( child: &fs::DirEntry, prefix: &str, - entries: &mut Vec, + entries: &mut SourceEntries, skipped: &mut Vec, - subdirs: &mut Vec<(PathBuf, String)>, + subdirs: &mut Vec<(PathBuf, ConfidentialText)>, ) -> Result<()> { let name = child.file_name(); - let lossy = format!("{prefix}{}", name.to_string_lossy()); let mut skip = |reason| { skipped.push(Skipped { - path: lossy.clone(), + path: format!("{prefix}{}", name.to_string_lossy()), reason, }); Ok(()) @@ -192,8 +171,8 @@ fn visit( let Some(name) = name.to_str() else { return skip(SkipReason::NonUtf8Name); }; - let rel = format!("{prefix}{name}"); - if paths::validate_only(&rel).is_err() { + let rel = ConfidentialText::joined(prefix, name)?; + if paths::validate_only(rel.expose()?).is_err() { return skip(SkipReason::InvalidName); } let file_type = child.file_type()?; @@ -202,19 +181,11 @@ fn visit( } let abs = child.path(); if file_type.is_dir() { - subdirs.push((abs.clone(), format!("{rel}/"))); - entries.push(SourceEntry { - rel, - abs, - kind: SourceKind::Dir, - }); + subdirs.push((abs.clone(), ConfidentialText::joined(rel.expose()?, "/")?)); + entries.push(rel.expose()?, &abs, true, 0)?; } else if file_type.is_file() { let size = fs::symlink_metadata(&abs)?.len(); - entries.push(SourceEntry { - rel, - abs, - kind: SourceKind::File(size), - }); + entries.push(rel.expose()?, &abs, false, size)?; } else { return skip(SkipReason::Special); } diff --git a/tests/sandbox_cli.rs b/tests/sandbox_cli.rs index 21386a8..a1661df 100644 --- a/tests/sandbox_cli.rs +++ b/tests/sandbox_cli.rs @@ -32,6 +32,11 @@ fn zz_probe_entry() { let report = sandbox::apply(&Profile::Cli(access)).unwrap(); #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] assert_eq!(report.seccomp, sandbox::Status::Full); + if probe.ends_with("_native") { + // DE: Native Verweigerung tatsächlich prüfen, bei fehlendem Landlock nicht überspringen. + // EN: Actually prove native denial; do not skip it when Landlock is unavailable. + assert_ne!(report.landlock, sandbox::Status::Unsupported); + } println!("LANDLOCK={}", report.landlock.as_str()); println!("RESULT={}", run_probe(&probe, &root)); std::process::exit(0); From 5cf5747475f6d2258f81f4d1221379aac838c9e8 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:21:05 +0100 Subject: [PATCH 14/26] fix(security): fold confidential names without private expansion scratch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Geschützten Pfadindex für Top-Level-Namen wiederverwenden, ungeschützte Kleinschreibkopien und private Unicode-Expansionsarrays entfernen. Sigma-Konflikte vor Archivschreiben ablehnen. 13 Prüfungen, 879 unveränderte Quellen, vier strenge Lints, je88 Dateigruppen und57 Integrationen bestanden. EN: Generate public Unicode folding data at build time; write private names directly into locked targets. Exhaustive scalar oracle and real selection regressions pass; package includes build.rs. Native acceptance pending. Joint R7/R8 remains in progress; no new unsafe. --- Cargo.toml | 1 + build.rs | 32 +++++++++++ docs/ROADMAP.md | 5 ++ docs/SPEC.en.md | 5 ++ docs/SPEC.md | 5 ++ docs/security/CONFIDENTIAL_NAME_FOLDING.md | 49 +++++++++++++++++ docs/security/SOURCE_RECORD_VALIDATION.md | 19 +++++-- src/files/mod.rs | 1 + src/files/paths.rs | 16 ++---- src/files/unicode_fold.rs | 28 ++++++++++ src/files/unicode_fold_tests.rs | 62 ++++++++++++++++++++++ src/files/walk.rs | 9 ++-- 12 files changed, 213 insertions(+), 19 deletions(-) create mode 100644 build.rs create mode 100644 docs/security/CONFIDENTIAL_NAME_FOLDING.md create mode 100644 src/files/unicode_fold.rs create mode 100644 src/files/unicode_fold_tests.rs diff --git a/Cargo.toml b/Cargo.toml index 0993fef..0cf4b06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ categories = ["cryptography", "command-line-utilities"] # EN: Only what is needed to build and for the licence (no tests, scripts, workflows). include = [ "/src/**", + "/build.rs", "/data/wordlists/**", "/Cargo.toml", "/Cargo.lock", diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..d6d86f1 --- /dev/null +++ b/build.rs @@ -0,0 +1,32 @@ +//! DE: Öffentliche Unicode-Falttabelle ohne private Laufzeit-Eingaben erzeugen. +//! EN: Generate a public Unicode folding table without private runtime inputs. +use std::{env, error::Error, fmt::Write, fs, path::PathBuf}; + +fn main() -> Result<(), Box> { + println!("cargo:rerun-if-changed=build.rs"); + let mut table = String::from("static FOLD: &[(u32, &[u8])] = &[\n"); + for scalar in 0..=0x0010_ffff { + let Some(c) = char::from_u32(scalar) else { + continue; + }; + // DE: Nur öffentliche Skalare; privates ToLowercase-Scratch entfällt zur Laufzeit. + // EN: Public scalars only; runtime needs no private ToLowercase scratch. + let folded: String = c + .to_lowercase() + .map(|v| if v == 'ς' { 'σ' } else { v }) + .collect(); + if !folded.chars().eq(std::iter::once(c)) { + writeln!( + table, + "(0x{:04x}_{:04x}, &{:?}),", + scalar >> 16, + scalar & 0xffff, + folded.as_bytes() + )?; + } + } + table.push_str("];\n"); + let destination = PathBuf::from(env::var_os("OUT_DIR").ok_or("missing OUT_DIR")?); + fs::write(destination.join("unicode_fold.rs"), table)?; + Ok(()) +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index d05ba90..4939944 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -196,3 +196,8 @@ stabile Referenzreihenfolge ohne gewöhnlichen Sortier-Scratch. Abnahme offen. EN: Actual single/tree/multi/container callers ported in the same joint work; native traversal/skip/FS intermediates and other plan rows remain open. See [source collection scope](security/SOURCE_RECORD_VALIDATION.md). + +DE/EN: R7/R8 in progress: gemeinsame geschützte Top-Level-/Archiv-Pfadprüfung +und öffentliche Unicode-Buildtabelle lokal implementiert / shared protected +top-level/archive path checks and public build-time Unicode table implemented +locally. Vollständige Abnahme läuft / full acceptance running; kein Gesamtabschluss. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 24b42c1..627ccfb 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -576,3 +576,8 @@ source records, occupancy, sort indices and iterator state. Fallible growth copi only between protected targets; stable ordering without ordinary record sorting scratch. Native traversal, skip/filesystem intermediates and other R7/R8 gaps remain open; see [source collection](security/SOURCE_RECORD_VALIDATION.md). + +EN: R7/R8 top-level names share the protected archive-reader PathSet. A public +build-time Unicode table replaces private runtime expansion arrays; original +name/wire bytes stay intact, sigma conflicts are rejected before writing. +See security/CONFIDENTIAL_NAME_FOLDING.md. diff --git a/docs/SPEC.md b/docs/SPEC.md index c47a8e9..04a8571 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -583,3 +583,8 @@ Wachstum kopiert nur zwischen gesperrten Zielen; stabile Reihenfolge ohne gewöhnlichen Record-Sortierscratch. Native Traversierung, Skip-/FS-Zwischenwerte und übrige R7/R8-Flächen bleiben offen; siehe [Quellsammlung](security/SOURCE_RECORD_VALIDATION.md). + +DE: R7/R8 Top-Level-Namensprüfung verwendet denselben geschützten PathSet wie der +Archivleser. Öffentliche Buildzeit-Unicode-Tabelle ersetzt private Laufzeit- +Expansionsarrays; Originalnamen/Wire erhalten, Sigma-Konflikte bereits beim +Schreiben abweisen. Details: security/CONFIDENTIAL_NAME_FOLDING.md. diff --git a/docs/security/CONFIDENTIAL_NAME_FOLDING.md b/docs/security/CONFIDENTIAL_NAME_FOLDING.md new file mode 100644 index 0000000..a18c679 --- /dev/null +++ b/docs/security/CONFIDENTIAL_NAME_FOLDING.md @@ -0,0 +1,49 @@ +# Confidential name folding / Vertrauliche Namensfaltung + +DE: R7/R8-Teil von Draft355. Mehrfachauswahl verwendet für Top-Level-Namen +denselben bereits geschützten PathSet wie der Archivleser. Die gewöhnliche +BTreeSet mit privaten to_lowercase-Strings entfällt. Sperrfehler werden als +MemoryLock weitergegeben; kein gewöhnlicher Ersatzindex. Namenskonflikte +behalten das bisherige Feld duplicate. +EN: Source records and archive bytes retain their original Unicode spelling. +Only conflict keys are folded. The existing archive-reader rule conservatively +merges both sigma aliases, without adding Unicode normalization or new folding. + +DE: Bisher konnte die Auswahl beispielsweise ΟΣ und οσ akzeptieren, obwohl der +Archivleser diese Kombination zurückweist: str::to_lowercase verwendet beim +ersten Namen kontextuelles finales Sigma. Die gemeinsame Konfliktregel weist +solche nicht rundlauffähigen Kombinationen jetzt bereits beim Schreiben ab. +EN: Ordinary distinct names keep their ordering and bytes. This is an intentional +stricter rejection of combinations already incompatible with the archive reader, +not a wire-format change or a new case-insensitive filesystem assumption. + +## Runtime storage / Laufzeitspeicher + +DE: char::to_lowercase besitzt ein kleines Expansionsarray. Statt dieses mit +privaten Namen zu befüllen, erzeugt build.rs eine öffentliche Tabelle durch +vollständige Enumeration aller Unicode-Skalare. Gleiche Rust-Standardbibliothek +und bestehende Sigma-Regel liefern die Referenz. Generierte numerische Schlüssel +und UTF8-Bytes vermeiden versehentliche Quelltextnormalisierung. +EN: Runtime lookup returns only immutable public table slices. Mapped bytes are +copied directly into the existing prelocked key; identity scalars encode directly +there. No private expansion array, String, lowercase collection or extra crate. +Necessary scalar/register transit is not a whole-stack-wiping claim. + +DE: build.rs ist ausdrücklich im Cargo-Paket enthalten. Generierte Daten liegen +in OUT_DIR; die Erzeugung ist deterministisch für dieselbe Rust-Unicode-Version. +Compiler-/Unicode-Updates ändern die Referenz wie zuvor die Standardbibliothek. +Keine Buildzeit-Eingabe enthält Laufzeitnamen oder andere Geheimnisse. +EN: No new unsafe block, dependency version or sandbox/host-policy change. + +## Acceptance and remaining scope / Abnahme und offene Flächen + +DE: Exhaustiver Test vergleicht jeden Unicode-Skalar mit der bisherigen +char-Faltung einschließlich Sigma-Zusammenführung; Größen, tatsächliche Bytes, +unveränderter Zielrest und sortierte Tabellenschlüssel werden geprüft. Echte +Mehrfachauswahl prüft Sigma-/ASCII-/Expansionskonflikte und unveränderte +unterschiedliche Namen. Bestehende Pfadindex-Sperr-/Verweigerungsfälle bleiben. +DE: Lokaler Checkpoint unicode-names-v1:879 unveränderte Rust-/Manifest-Hashes, +13 erfolgreiche Befehle, vier strenge Linux-/Windows-GNU-Lints, je88 Datei- +gruppen mit/ohne API und57 Integrationen. Cargo-Paketliste enthält build.rs. +EN: Native acceptance of this component is pending. Native traversal, skip/output/report records and verified +process/helper/host contracts remain open; no complete M1/M2 or R7/R8 claim. diff --git a/docs/security/SOURCE_RECORD_VALIDATION.md b/docs/security/SOURCE_RECORD_VALIDATION.md index c8227b0..6c6358d 100644 --- a/docs/security/SOURCE_RECORD_VALIDATION.md +++ b/docs/security/SOURCE_RECORD_VALIDATION.md @@ -51,11 +51,12 @@ gesperrten nativen Seitenbeobachter. Referenzsortierung einschließlich gleicher Namen, Wachstumsgrenzen, gültige Dateiinhalte und fehlgeschlagene Slotbefüllung. EN: Bounded own Linux children exercise actual zero-budget refusal, failure after some growth copies already succeeded, previous-state preservation, unwind, native -lock cleanup and unchanged parent limits. Native acceptance of this source-record -component is pending; the local checkpoint below passed. +lock cleanup and unchanged parent limits. The source-record component passed +the local checkpoint below and the native checkpoint recorded at the end. DE: Weiter offen: read_dir-/DirEntry-/fs::Metadata-Zwischenwerte, gewöhnliche -native Traversierungspfade/-stapel, Top-Level-to_lowercase/BTreeSet und Skip-Records. +native Traversierungspfade/-stapel und Skip-Records. Top-Level-Namensschutz +und Unicode-Faltung werden in CONFIDENTIAL_NAME_FOLDING.md separat abgenommen. M3 umfasst weiterhin Ziel-/Temp-/Cleanup-/Publish-Pfade und die aus Main358 übernommenen Handle-/Identitäts-/Metadatenrecords. Berichte, Serialisierung, CLI-Kontext und Prozess-/Helper-Verträge bleiben eigene tatsächliche Lücken. @@ -77,3 +78,15 @@ diff checks passed. The native sandbox cases now require actual Landlock support rather than reporting an unsupported kernel as proof of denial. No sandbox rule, security gate, dependency version or unsafe boundary was weakened or added. The separate Windows process probe remains unsuccessful; no R7/R8 closure. + +## Native checkpoint / Native Abnahme + +DE: Exakter signierter Quellstand3dc0fdf: vollständige Rust-Jobs unter Linux22 +und ARM jeweils965 Tests/120 Gruppen, Linux-latest1851/238 sowie Windows1670/240 +bestanden, ohne Testfehler. Vollprotokolle und Hashes gesichert; konkrete +Owner-/Sortier-/Iteratorfälle, begrenzte Fehlerkinder und Windows-Seitenabfragen +nicht aus einem bloßen Cross-Check abgeleitet. +EN: All eight fuzz targets and the usual MSRV/audit/history/workflow/hardening +gates pass. Explicit ignored child/race entrypoints remain visible; actual child +invocation is checked separately. The owned Windows process-access probe still +fails due to enabled debug privilege; this is no joint R7/R8 acceptance. diff --git a/src/files/mod.rs b/src/files/mod.rs index 4672ee0..6807f15 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -53,6 +53,7 @@ mod source_entry; mod stream_v4; mod tail_v4; mod tail_v4_drain; +mod unicode_fold; mod walk; use std::io::BufReader; diff --git a/src/files/paths.rs b/src/files/paths.rs index 30c0586..6f0c171 100644 --- a/src/files/paths.rs +++ b/src/files/paths.rs @@ -112,14 +112,6 @@ pub struct PathSet { entries: super::confidential_path_index::Index, } -fn lower_chars(part: &str) -> impl Iterator + '_ { - // DE: Sigma-Aliase konservativ zusammenfassen; Originalnamen nicht ändern. - // EN: Conservatively merge sigma aliases; never alter original names. - part.chars() - .flat_map(char::to_lowercase) - .map(|c| if c == 'ς' { 'σ' } else { c }) -} - fn folded_size<'a>(parts: impl Iterator) -> Result { let (mut count, mut raw_len, mut len) = (0, 0, 0); for part in parts { @@ -131,7 +123,7 @@ fn folded_size<'a>(parts: impl Iterator) -> Result { if raw_len > MAX_PATH_BYTES { return Err(invalid()); } - len += lower_chars(part).map(char::len_utf8).sum::() + separator; + len += part.chars().map(super::unicode_fold::size).sum::() + separator; count += 1; } if count == 0 { @@ -148,10 +140,8 @@ fn folded_key<'a>(parts: impl Iterator + Clone) -> Result Option<&'static [u8]> { + FOLD.binary_search_by_key(&u32::from(c), |&(key, _)| key) + .ok() + .map(|index| FOLD[index].1) +} + +pub(super) fn size(c: char) -> usize { + mapped(c).map_or_else(|| c.len_utf8(), <[u8]>::len) +} + +// DE: Ziel ist bereits gesperrt; unveränderte Skalare direkt dorthin kodieren. +// EN: The destination is already locked; encode unchanged scalars directly there. +pub(super) fn write(c: char, target: &mut [u8]) -> usize { + if let Some(text) = mapped(c) { + target[..text.len()].copy_from_slice(text); + text.len() + } else { + c.encode_utf8(target).len() + } +} + +#[cfg(test)] +#[path = "unicode_fold_tests.rs"] +mod tests; diff --git a/src/files/unicode_fold_tests.rs b/src/files/unicode_fold_tests.rs new file mode 100644 index 0000000..8153f6f --- /dev/null +++ b/src/files/unicode_fold_tests.rs @@ -0,0 +1,62 @@ +//! DE: Öffentliche vollständige Unicode-Referenz und echte Mehrfachauswahl prüfen. +//! EN: Verify a public exhaustive Unicode oracle and actual multi-selection. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::{Error, crypto::SecretBytes}; + +#[test] +fn every_unicode_scalar_matches_existing_sigma_conservative_folding() { + let mut target = SecretBytes::zeroed(12).unwrap(); + for scalar in 0..=0x0010_ffff { + let Some(c) = char::from_u32(scalar) else { + continue; + }; + let expected: String = c + .to_lowercase() + .map(|v| if v == 'ς' { 'σ' } else { v }) + .collect(); + assert_eq!(size(c), expected.len()); + target.expose_mut().fill(0xa5); + let written = write(c, target.expose_mut()); + assert_eq!(written, expected.len()); + assert_eq!(&target.expose()[..written], expected.as_bytes()); + assert!(target.expose()[written..].iter().all(|&v| v == 0xa5)); + } + assert!(FOLD.windows(2).all(|pair| pair[0].0 < pair[1].0)); +} + +#[test] +fn actual_selection_rejects_names_that_its_archive_reader_would_reject() { + for (left, right) in [("ΟΣ", "οσ"), ("ος", "οσ"), ("İ", "i\u{307}"), ("A", "a")] { + let root = tempfile::tempdir().unwrap(); + let first = root.path().join("first"); + let second = root.path().join("second"); + std::fs::create_dir(&first).unwrap(); + std::fs::create_dir(&second).unwrap(); + let a = first.join(left); + let b = second.join(right); + std::fs::write(&a, b"public fixture").unwrap(); + std::fs::write(&b, b"public fixture").unwrap(); + let rejected = matches!( + super::super::walk::collect_many(&[&a, &b]), + Err(Error::InvalidInput { field: "duplicate" }) + ); + assert!(rejected); + } +} + +#[test] +fn actual_selection_keeps_distinct_names_and_original_unicode_bytes() { + let root = tempfile::tempdir().unwrap(); + let a = root.path().join("İ"); + let b = root.path().join("日本語"); + std::fs::write(&a, b"public fixture").unwrap(); + std::fs::write(&b, b"public fixture").unwrap(); + let (entries, skipped) = super::super::walk::collect_many(&[&b, &a]).unwrap(); + let no_skipped = skipped.is_empty(); + assert!(no_skipped); + assert_eq!(entries.len(), 2); + let equal = entries.get(0).unwrap().path().unwrap() == "İ" + && entries.get(1).unwrap().path().unwrap() == "日本語"; + assert!(equal); +} diff --git a/src/files/walk.rs b/src/files/walk.rs index ed4bd7a..e048910 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -79,15 +79,18 @@ pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, Vec Error::InvalidInput { field: "duplicate" }, + other => other, + }); } let kind = fs::symlink_metadata(src)?.file_type(); if kind.is_symlink() { From 8ea8d76400e35c16c6c89fc7cbe209e77e6e2982 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:10:44 +0100 Subject: [PATCH 15/26] fix(security): capture source metadata into prelocked native records MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Tatsächliche libc-/Windows-SDK-Metadaten vor Kernel-Ausgabe sperren, Quell-Caller migrieren und No-Follow-/Sharing-/Reparse-Vertrag erhalten. Unnötige Windows-Initialisierungs-/Raw-Wipe-unsafe-Blöcke mit typisierten Defaults und vollständiger Feldlöschung vermeiden. EN: All 16 source-bound local checks pass on886 unchanged sources: strict platform/root feature lints, eight platform tests,92 file groups per configuration and57 integrations. Real bounded denial/unwind and invalid-path tests pass; Windows native execution pending. All168 dependency versions/sources/checksums retained. Root forbids unsafe; joint R7/R8 remains in progress. --- Cargo.lock | 1 + Cargo.toml | 3 +- docs/ROADMAP.md | 5 + docs/SPEC.en.md | 5 + docs/SPEC.md | 5 + docs/security/CONFIDENTIAL_NAME_FOLDING.md | 5 +- docs/security/SOURCE_METADATA_VALIDATION.md | 69 +++++++ docs/security/SOURCE_RECORD_VALIDATION.md | 7 +- platform/pqkeep-platform/Cargo.toml | 10 +- platform/pqkeep-platform/src/lib.rs | 5 + platform/pqkeep-platform/src/path_windows.rs | 2 +- .../pqkeep-platform/src/source_metadata.rs | 105 ++++++++++ .../src/source_metadata_linux.rs | 37 ++++ .../src/source_metadata_windows.rs | 101 ++++++++++ .../src/source_metadata_windows_clear.rs | 46 +++++ .../src/source_metadata_windows_find.rs | 68 +++++++ src/files/mod.rs | 1 + src/files/native_path.rs | 12 ++ src/files/source_metadata.rs | 35 ++++ src/files/source_metadata_tests.rs | 179 ++++++++++++++++++ src/files/walk.rs | 12 +- 21 files changed, 700 insertions(+), 13 deletions(-) create mode 100644 docs/security/SOURCE_METADATA_VALIDATION.md create mode 100644 platform/pqkeep-platform/src/source_metadata.rs create mode 100644 platform/pqkeep-platform/src/source_metadata_linux.rs create mode 100644 platform/pqkeep-platform/src/source_metadata_windows.rs create mode 100644 platform/pqkeep-platform/src/source_metadata_windows_clear.rs create mode 100644 platform/pqkeep-platform/src/source_metadata_windows_find.rs create mode 100644 src/files/source_metadata.rs create mode 100644 src/files/source_metadata_tests.rs diff --git a/Cargo.lock b/Cargo.lock index ce2874a..7b74837 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -938,6 +938,7 @@ dependencies = [ name = "pqkeep-platform" version = "0.1.0" dependencies = [ + "libc", "windows-sys", "zeroize", ] diff --git a/Cargo.toml b/Cargo.toml index 0cf4b06..bed1c10 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -131,6 +131,7 @@ tokio = { version = "1.54.1", default-features = false, features = ["macros", "r [target.'cfg(target_os = "linux")'.dependencies] landlock = "0.4.7" libc = "0.2.191" +pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform" } rustix = { version = "1.1.6", default-features = false, features = ["std", "process", "termios", "event", "thread", "fs"] } seccompiler = { version = "0.5.0", default-features = false } @@ -143,7 +144,7 @@ pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform" } [target.'cfg(windows)'.dev-dependencies] # DE: Nur sichere eigene Testfixture, nicht im normalen Produktionsbaum. # EN: Safe own-console fixture only, excluded from normal production features. -pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform", features = ["native-input-fixture", "native-memory-fixture"] } +pqkeep-platform = { version = "0.1.0", path = "platform/pqkeep-platform", features = ["native-input-fixture", "native-memory-fixture", "native-metadata-fixture"] } # DE: `api` (Standard) baut den REST-Server `pqkeep serve` ein. Ohne das Feature # (`--no-default-features`) entsteht eine reine CLI ohne Netzwerkcode. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 4939944..10897ca 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -201,3 +201,8 @@ DE/EN: R7/R8 in progress: gemeinsame geschützte Top-Level-/Archiv-Pfadprüfung und öffentliche Unicode-Buildtabelle lokal implementiert / shared protected top-level/archive path checks and public build-time Unicode table implemented locally. Vollständige Abnahme läuft / full acceptance running; kein Gesamtabschluss. + +DE/EN: R7/R8 weiterhin in Arbeit: native Quellmetadaten direkt vorab gesperrt +lokal entwickelt / prelocked native source metadata locally developed; +Abnahme läuft / validation running. DirEntry/Traversierung/Skip/Output/Reports +und Prozess-/Helper-Verträge bleiben offen / remain open. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 627ccfb..2b8af6f 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -581,3 +581,8 @@ EN: R7/R8 top-level names share the protected archive-reader PathSet. A public build-time Unicode table replaces private runtime expansion arrays; original name/wire bytes stay intact, sigma conflicts are rejected before writing. See security/CONFIDENTIAL_NAME_FOLDING.md. + +EN: R7/R8 source collection captures native metadata directly in prelocked +libc/SDK records without private std::fs::Metadata return values. No-follow and +Windows reparse/sharing semantics stay explicit. Full local/native acceptance +pending; see security/SOURCE_METADATA_VALIDATION.md for the actual boundary. diff --git a/docs/SPEC.md b/docs/SPEC.md index 04a8571..37e63ac 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -588,3 +588,8 @@ DE: R7/R8 Top-Level-Namensprüfung verwendet denselben geschützten PathSet wie Archivleser. Öffentliche Buildzeit-Unicode-Tabelle ersetzt private Laufzeit- Expansionsarrays; Originalnamen/Wire erhalten, Sigma-Konflikte bereits beim Schreiben abweisen. Details: security/CONFIDENTIAL_NAME_FOLDING.md. + +DE: R7/R8-Quellsammlung erfasst native Metadaten direkt in vorab gesperrten +libc-/SDK-Records, ohne privaten std::fs::Metadata-Rückgabewert. No-Follow- +Semantik und Windows-Reparse-/Sharing-Vertrag bleiben explizit. Lokale/native +Vollabnahme offen; security/SOURCE_METADATA_VALIDATION.md beschreibt die Grenze. diff --git a/docs/security/CONFIDENTIAL_NAME_FOLDING.md b/docs/security/CONFIDENTIAL_NAME_FOLDING.md index a18c679..27208d1 100644 --- a/docs/security/CONFIDENTIAL_NAME_FOLDING.md +++ b/docs/security/CONFIDENTIAL_NAME_FOLDING.md @@ -45,5 +45,8 @@ unterschiedliche Namen. Bestehende Pfadindex-Sperr-/Verweigerungsfälle bleiben. DE: Lokaler Checkpoint unicode-names-v1:879 unveränderte Rust-/Manifest-Hashes, 13 erfolgreiche Befehle, vier strenge Linux-/Windows-GNU-Lints, je88 Datei- gruppen mit/ohne API und57 Integrationen. Cargo-Paketliste enthält build.rs. -EN: Native acceptance of this component is pending. Native traversal, skip/output/report records and verified +DE: Signierter5cf5747 nativ: Linux22/ARM je968 Tests/120 Gruppen, latest1857/238, +Windows1676/240 ohne Testfehler. Exhaustive Unicode- und echte Auswahlfälle +in allen vier Vollprotokollen ausgeführt; Hashes und exakter Head geprüft. +EN: All eight fuzz targets and the usual gates pass on5cf5747. Native traversal, skip/output/report records and verified process/helper/host contracts remain open; no complete M1/M2 or R7/R8 claim. diff --git a/docs/security/SOURCE_METADATA_VALIDATION.md b/docs/security/SOURCE_METADATA_VALIDATION.md new file mode 100644 index 0000000..227a879 --- /dev/null +++ b/docs/security/SOURCE_METADATA_VALIDATION.md @@ -0,0 +1,69 @@ +# Prelocked source metadata / Vorab gesperrte Quellmetadaten + +DE: Gemeinsamer R7/R8-Draft355; kein Gesamtabschluss. Die tatsächlichen +symlink_metadata-Aufrufe der Quellsammlung verwenden vor Kernel-Ausgabe +gesperrte SDK-/libc-Records. Datei-/Verzeichnis-/Linkart und Länge werden im +selben geschützten Zustand gehalten, ohne privaten std::fs::Metadata-Rückgabewert. +EN: Source path conversion reuses NativePath. The whole native record, Windows +reparse-tag and find fallback records are locked before capture. Public-empty +construction precedes private fields; no ordinary allocation fallback on denial. + +## Reached operations / Erreichte Operationen + +DE: Einzeldatei-, Top-Level-Mehrfach- und Ordnerprüfung sowie Größenabfrage +echter Quelldateien in walk.rs. Linux nutzt fstatat mit AT_SYMLINK_NOFOLLOW +und geliehenem geschütztem CStr; negativer nativer Größenwert wird abgewiesen. +EN: Windows retains zero-access metadata handles, normal sharing, reparse-point +opening and directory support. Reparse tags are queried only when indicated by +attributes, preserving ordinary FAT-file behavior. Name-surrogate links remain +links instead of being misclassified as ordinary files/directories. + +DE: Windows-Sharing-/Zugriffs-Fallback wie beim bestehenden std-Vertrag über +FindFirstFileExW, jedoch direkt ins geschützte SDK-Ziel. Keine Wildcard-Abfrage +durch den Fallback. Suchhandle sofort schließen; ursprünglichen Öffnungsfehler +bei fehlgeschlagener Suche erhalten. Ein direkter nur lesender Testfixture-Aufruf +prüft den Find-Pfad, ohne einen künstlich gewählten Fehler als native Verweigerung +auszugeben. Exklusiv geöffnete normale Dateien garantieren diesen Fehler nicht. +EN: Native metadata may be stale, as with the previous std operation. This does +not solve the separately open source-open/symlink race in338. read_dir, DirEntry, +native traversal/skip/output/report records remain separate real gaps. + +## Unsafe boundary / Unsafe-Grenze + +DE: Root-forbid bleibt. Plattformcode verwendet tatsächliche SDK-/libc-Typen, +keinen nachgebauten stat-ABI. Notwendige native Aufrufe prüfen lebende NUL-Pfade, +exklusive vollständige Ziele, Ausrichtung, Rückgaben und Handle-Eigentum. +Linux leiht MaybeUninit nur nach erfolgreichem fstatat aus; Fehler lesen keinen +teilinitialisierten Record. Gesamten MaybeUninit-Speicher volatil löschen. +EN: Windows typed SDK defaults and fieldwise volatile wiping avoid unnecessary +assume_init/raw-wipe blocks. Compile-time52/8/592-byte layout checks cover the +complete native/tag/find fields without padding; root SecretState additionally +wipes the full owning allocation and padding before unlock, including unwind. +There is no record Clone/Debug or whole-private-record conversion. + +DE: Vorhandene libc0.2.191 und zeroize werden wiederverwendet; nur Abhängigkeits- +kanten erweitert, keine Paketversion/Quelle installiert oder aktualisiert. +EN: No ACL, token, privilege, account, Registry, sandbox or host-policy mutation. + +## Verification / Prüfung + +DE: Entwickelt sind echte öffentliche Datei-/Verzeichnisreferenzen, Linux- +Dangling-Link, Fehlerklassen, konkrete Owner-/Windows-Seitenbeobachtung und +begrenztes eigenes Speicherfehler-/Unwind-Kind mit unverändertem Elternlimit. +Windows-Fälle für Datei-/Verzeichnis-/Dangling-Links, exklusiven Öffner und +echten direkten Find-Aufruf in vorab gesperrtes Caller-Ziel sind cross-kompiliert; +die tatsächliche native Ausführung steht noch aus. +DE: Lokaler source-metadata-v1-Checkpoint:886 unveränderte Rust-/Manifest-Hashes, +16 erfolgreiche Kommandos. Plattform-All-Feature-Lints auf Linux/Windows-GNU, +acht Plattformtests, vier strenge Root-Lints mit/ohne API auf beiden Zielen, +je92 Dateigruppen mit/ohne API,57 Integrationen. Elf ignorierte Kind-/Race- +Einstiege bleiben sichtbar; tatsächlicher Metadaten-Fehlerkindaufruf bestanden. +EN: Root/platform formatting, limits, strict vendor/matrix and diff checks pass. +Native Windows/ARM64 and usual final gates remain required. No complete metadata, +M1/M3, R7/R8 or147 acceptance is claimed by this document. + +Sources / Quellen: +- https://raw.githubusercontent.com/rust-lang/rust/1.88.0/library/std/src/sys/fs/windows.rs +- https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfileinformationbyhandleex +- https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_attribute_tag_info +- https://learn.microsoft.com/en-us/windows/win32/fileio/reparse-point-tags diff --git a/docs/security/SOURCE_RECORD_VALIDATION.md b/docs/security/SOURCE_RECORD_VALIDATION.md index 6c6358d..7c5c8ef 100644 --- a/docs/security/SOURCE_RECORD_VALIDATION.md +++ b/docs/security/SOURCE_RECORD_VALIDATION.md @@ -54,7 +54,7 @@ some growth copies already succeeded, previous-state preservation, unwind, nativ lock cleanup and unchanged parent limits. The source-record component passed the local checkpoint below and the native checkpoint recorded at the end. -DE: Weiter offen: read_dir-/DirEntry-/fs::Metadata-Zwischenwerte, gewöhnliche +DE: Weiter offen: read_dir-/DirEntry-Zwischenwerte, gewöhnliche native Traversierungspfade/-stapel und Skip-Records. Top-Level-Namensschutz und Unicode-Faltung werden in CONFIDENTIAL_NAME_FOLDING.md separat abgenommen. M3 umfasst weiterhin Ziel-/Temp-/Cleanup-/Publish-Pfade und die aus Main358 @@ -90,3 +90,8 @@ EN: All eight fuzz targets and the usual MSRV/audit/history/workflow/hardening gates pass. Explicit ignored child/race entrypoints remain visible; actual child invocation is checked separately. The owned Windows process-access probe still fails due to enabled debug privilege; this is no joint R7/R8 acceptance. + +DE/EN: Direkte Quellmetadaten-Adapter werden im selben gemeinsamen Draft +separat entwickelt/geprüft / direct source-metadata adapters are developed and +validated separately in the same joint draft. See SOURCE_METADATA_VALIDATION.md; +remaining DirEntry/traversal/output records are not thereby declared closed. diff --git a/platform/pqkeep-platform/Cargo.toml b/platform/pqkeep-platform/Cargo.toml index ef92fae..c0fcf12 100644 --- a/platform/pqkeep-platform/Cargo.toml +++ b/platform/pqkeep-platform/Cargo.toml @@ -7,13 +7,15 @@ license = "Apache-2.0" publish = false description = "Narrow synchronous platform adapters for PQKeep" +[target.'cfg(target_os = "linux")'.dependencies] +libc = "=0.2.191" + [target.'cfg(windows)'.dependencies] windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_Storage_FileSystem", "Win32_Security", "Win32_UI_Input_KeyboardAndMouse"] } -[target.'cfg(windows)'.dependencies.zeroize] +[dependencies.zeroize] version = "1.9.1" default-features = false -optional = true [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "=0.61.2", features = ["Win32_Security", "Win32_Security_Authorization"] } @@ -22,7 +24,9 @@ windows-sys = { version = "=0.61.2", features = ["Win32_Security", "Win32_Securi # DE/EN: Ausschließlich feste öffentliche Testereignisse / fixed public test events only. native-input-fixture = [] # DE/EN: Nur lesende eigene Seitensperrprobe / read-only own page-lock fixture only. -native-memory-fixture = ["dep:zeroize"] +native-memory-fixture = [] +# DE/EN: Nur lesende direkte Find-Metadatenprobe / read-only direct find-metadata fixture. +native-metadata-fixture = [] # DE/EN: Nur ausdrücklich gestartete öffentliche Prozessprobe / explicitly run public probe only. process-access-probe = [] diff --git a/platform/pqkeep-platform/src/lib.rs b/platform/pqkeep-platform/src/lib.rs index 227b8bf..d28a376 100644 --- a/platform/pqkeep-platform/src/lib.rs +++ b/platform/pqkeep-platform/src/lib.rs @@ -31,3 +31,8 @@ pub mod memory_fixture; mod path_windows; #[cfg(windows)] pub use path_windows::{absolute_path_into, open_file_read}; + +#[cfg(any(target_os = "linux", windows))] +mod source_metadata; +#[cfg(any(target_os = "linux", windows))] +pub use source_metadata::SourceMetadata; diff --git a/platform/pqkeep-platform/src/path_windows.rs b/platform/pqkeep-platform/src/path_windows.rs index e8452d6..94f4441 100644 --- a/platform/pqkeep-platform/src/path_windows.rs +++ b/platform/pqkeep-platform/src/path_windows.rs @@ -10,7 +10,7 @@ use windows_sys::Win32::{ }, }; -fn validate(path: &[u16]) -> io::Result<()> { +pub(crate) fn validate(path: &[u16]) -> io::Result<()> { if path.last() != Some(&0) || path[..path.len() - 1].contains(&0) { return Err(io::ErrorKind::InvalidInput.into()); } diff --git a/platform/pqkeep-platform/src/source_metadata.rs b/platform/pqkeep-platform/src/source_metadata.rs new file mode 100644 index 0000000..59ec59e --- /dev/null +++ b/platform/pqkeep-platform/src/source_metadata.rs @@ -0,0 +1,105 @@ +//! DE: Native Metadaten direkt im vorab geschützten Caller-Record erfassen. +//! EN: Capture native metadata directly in the caller's preprotected record. +use std::io; +#[cfg(target_os = "linux")] +use std::mem::MaybeUninit; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[cfg(target_os = "linux")] +type Native = libc::stat; +#[cfg(windows)] +type Native = windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION; +#[cfg(windows)] +use windows_sys::Win32::Storage::FileSystem::{FILE_ATTRIBUTE_TAG_INFO, WIN32_FIND_DATAW}; + +/// DE: Öffentlich leer erzeugen; vor capture stabil sperren. Keine Clone/Debug-Kopie. +/// EN: Construct public-empty; stably lock before capture. No Clone/Debug copy. +pub struct SourceMetadata { + #[cfg(target_os = "linux")] + native: MaybeUninit, + #[cfg(windows)] + native: Native, + #[cfg(windows)] + tag: FILE_ATTRIBUTE_TAG_INFO, + #[cfg(windows)] + find: WIN32_FIND_DATAW, + file: bool, + directory: bool, + symlink: bool, + bytes: u64, +} + +impl SourceMetadata { + /// DE/EN: Nur öffentliche Anfangswerte / public initial values only. + #[must_use] + pub fn empty() -> Self { + Self { + #[cfg(target_os = "linux")] + native: MaybeUninit::zeroed(), + #[cfg(windows)] + native: Native::default(), + #[cfg(windows)] + tag: FILE_ATTRIBUTE_TAG_INFO::default(), + #[cfg(windows)] + find: WIN32_FIND_DATAW::default(), + file: false, + directory: false, + symlink: false, + bytes: 0, + } + } + + /// DE/EN: Reguläre Datei / regular file. + #[must_use] + pub const fn is_file(&self) -> bool { + self.file + } + /// DE/EN: Verzeichnis / directory. + #[must_use] + pub const fn is_dir(&self) -> bool { + self.directory + } + /// DE/EN: Symbolischer Verweis, ohne Verfolgung / symlink without following. + #[must_use] + pub const fn is_symlink(&self) -> bool { + self.symlink + } + /// DE/EN: Dateigröße / file length. + #[must_use] + pub const fn bytes(&self) -> u64 { + self.bytes + } +} + +impl Zeroize for SourceMetadata { + fn zeroize(&mut self) { + #[cfg(target_os = "linux")] + self.native.zeroize(); + #[cfg(windows)] + self.wipe_windows(); + self.file.zeroize(); + self.directory.zeroize(); + self.symlink.zeroize(); + self.bytes.zeroize(); + } +} +impl Drop for SourceMetadata { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for SourceMetadata {} + +#[cfg(target_os = "linux")] +#[path = "source_metadata_linux.rs"] +mod linux; +#[cfg(windows)] +#[path = "source_metadata_windows.rs"] +mod windows; +#[cfg(windows)] +#[path = "source_metadata_windows_find.rs"] +mod windows_find; + +#[cfg(windows)] +#[path = "source_metadata_windows_clear.rs"] +mod windows_clear; diff --git a/platform/pqkeep-platform/src/source_metadata_linux.rs b/platform/pqkeep-platform/src/source_metadata_linux.rs new file mode 100644 index 0000000..d1ba456 --- /dev/null +++ b/platform/pqkeep-platform/src/source_metadata_linux.rs @@ -0,0 +1,37 @@ +//! DE: fstatat ohne Linkverfolgung in ein exklusives stabiles Ziel. +//! EN: fstatat without symlink following into exclusive stable storage. +use super::{SourceMetadata, Zeroize, io}; +use std::ffi::CStr; + +impl SourceMetadata { + /// DE: Metadaten ohne Linkverfolgung direkt erfassen; Caller schützt seinen Record. + /// EN: Capture metadata without following links; caller protects the record. + /// # Errors + /// DE/EN: Native Verweigerung oder negative Länge / native refusal or negative size. + pub fn capture(&mut self, path: &CStr) -> io::Result<()> { + self.zeroize(); + // DE: SDK-Typ statt Layoutnachbau; lebender NUL-Pfad und exklusives Ziel. + // SAFETY: CStr is terminated and live through this synchronous call. The + // actual libc::stat destination is aligned, exclusive and writable in full. + let result = unsafe { + libc::fstatat( + libc::AT_FDCWD, + path.as_ptr(), + self.native.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ) + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + // DE: Nur nach erfolgreicher vollständiger Initialisierung ausleihen. + // SAFETY: Successful fstatat initialized this actual stat object; no + // whole private record is copied, and this borrow cannot outlive self. + let native = unsafe { self.native.assume_init_ref() }; + self.bytes = u64::try_from(native.st_size).map_err(|_| io::ErrorKind::InvalidData)?; + self.file = native.st_mode & libc::S_IFMT == libc::S_IFREG; + self.directory = native.st_mode & libc::S_IFMT == libc::S_IFDIR; + self.symlink = native.st_mode & libc::S_IFMT == libc::S_IFLNK; + Ok(()) + } +} diff --git a/platform/pqkeep-platform/src/source_metadata_windows.rs b/platform/pqkeep-platform/src/source_metadata_windows.rs new file mode 100644 index 0000000..e072860 --- /dev/null +++ b/platform/pqkeep-platform/src/source_metadata_windows.rs @@ -0,0 +1,101 @@ +//! DE: Reparse-Punkte nicht verfolgen; SDK-Records im geschützten Caller befüllen. +//! EN: Do not follow reparse points; fill SDK records in the protected caller. +use super::{SourceMetadata, Zeroize, io}; +use std::{ + fs::File, + os::windows::io::{AsRawHandle, FromRawHandle}, + ptr, +}; +use windows_sys::Win32::{ + Foundation::{ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, INVALID_HANDLE_VALUE}, + Storage::FileSystem::{ + CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, + FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, + FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileAttributeTagInfo, + GetFileInformationByHandle, GetFileInformationByHandleEx, OPEN_EXISTING, + }, +}; + +fn open(path: &[u16]) -> io::Result { + if path.last() != Some(&0) || path[..path.len() - 1].contains(&0) { + return Err(io::ErrorKind::InvalidInput.into()); + } + // DE: Lebender NUL-Pfad; nur Attribute lesen, keine Vererbung/Security-Mutation. + // SAFETY: Terminated live path; documented flags open the reparse point itself. + // Null security/template pointers are permitted; this creates one owned handle. + let handle = unsafe { + CreateFileW( + path.as_ptr(), + 0, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error()); + } + // DE: Eigentum genau einmal übertragen, auch Fehlerpfade schließen den Handle. + // SAFETY: Successful CreateFileW returned a fresh owned handle transferred once. + Ok(unsafe { File::from_raw_handle(handle.cast()) }) +} + +impl SourceMetadata { + /// DE: Native Records direkt erfassen; vor Aufruf stabil im Caller sperren. + /// EN: Capture native records directly; stably protect them before calling. + /// # Errors + /// DE/EN: Ungültiger Pfad oder native Verweigerung / invalid path or native refusal. + pub fn capture(&mut self, path: &[u16]) -> io::Result<()> { + self.zeroize(); + let file = match open(path) { + Ok(file) => file, + Err(error) + if [ + i32::try_from(ERROR_ACCESS_DENIED).ok(), + i32::try_from(ERROR_SHARING_VIOLATION).ok(), + ] + .contains(&error.raw_os_error()) => + { + return self.capture_find(path, error); + } + Err(error) => return Err(error), + }; + // DE: Echtes SDK-Ziel ist ausgerichtet und exklusiv; API behält keinen Pointer. + // SAFETY: File owns a valid handle through this synchronous call; native + // is aligned and writable for the actual BY_HANDLE_FILE_INFORMATION type. + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &raw mut self.native) } == 0 { + return Err(io::Error::last_os_error()); + } + // DE/EN: Initialisiertes SDK-Ziel ausschließlich leihen / borrow the initialized SDK target. + let native = &self.native; + if native.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + self.symlink = capture_tag(&file, &mut self.tag)?; + } + self.file = !self.symlink && native.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0; + self.directory = !self.symlink && native.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0; + self.bytes = (u64::from(native.nFileSizeHigh) << 32) | u64::from(native.nFileSizeLow); + Ok(()) + } +} + +fn capture_tag(file: &File, tag: &mut FILE_ATTRIBUTE_TAG_INFO) -> io::Result { + // DE: Nur bei Reparse-Attribut abfragen; normale FAT-Dateien benötigen diese Klasse nicht. + // SAFETY: Owned live handle; exclusive aligned actual SDK tag record of + // the specified complete size. The API does not retain its output pointer. + if unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle(), + FileAttributeTagInfo, + std::ptr::from_mut(tag).cast(), + u32::try_from(size_of::()) + .map_err(|_| io::ErrorKind::InvalidInput)?, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // DE/EN: Namensumleitende Tags wie std behandeln / match std name-surrogate tags. + Ok(tag.ReparseTag & 0x2000_0000 != 0) +} diff --git a/platform/pqkeep-platform/src/source_metadata_windows_clear.rs b/platform/pqkeep-platform/src/source_metadata_windows_clear.rs new file mode 100644 index 0000000..fd66dd4 --- /dev/null +++ b/platform/pqkeep-platform/src/source_metadata_windows_clear.rs @@ -0,0 +1,46 @@ +//! DE: SDK-Felder ohne private Record-Kopie und ohne eigene Raw-Wipe-FFI löschen. +//! EN: Wipe SDK fields without private record copies or our own raw-wipe FFI. +use super::SourceMetadata; +use windows_sys::Win32::{ + Foundation::FILETIME, + Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_TAG_INFO, WIN32_FIND_DATAW}, +}; +use zeroize::Zeroize; + +// DE: Vollständige Feldgeometrie ohne Padding; SDK-Änderungen sichtbar verweigern. +// EN: Complete field geometry without padding; visibly reject SDK layout changes. +const _: () = assert!(size_of::() == 52); +const _: () = assert!(size_of::() == 8); +const _: () = assert!(size_of::() == 592); + +fn time(value: &mut FILETIME) { + value.dwLowDateTime.zeroize(); + value.dwHighDateTime.zeroize(); +} + +impl SourceMetadata { + pub(super) fn wipe_windows(&mut self) { + self.native.dwFileAttributes.zeroize(); + time(&mut self.native.ftCreationTime); + time(&mut self.native.ftLastAccessTime); + time(&mut self.native.ftLastWriteTime); + self.native.dwVolumeSerialNumber.zeroize(); + self.native.nFileSizeHigh.zeroize(); + self.native.nFileSizeLow.zeroize(); + self.native.nNumberOfLinks.zeroize(); + self.native.nFileIndexHigh.zeroize(); + self.native.nFileIndexLow.zeroize(); + self.tag.FileAttributes.zeroize(); + self.tag.ReparseTag.zeroize(); + self.find.dwFileAttributes.zeroize(); + time(&mut self.find.ftCreationTime); + time(&mut self.find.ftLastAccessTime); + time(&mut self.find.ftLastWriteTime); + self.find.nFileSizeHigh.zeroize(); + self.find.nFileSizeLow.zeroize(); + self.find.dwReserved0.zeroize(); + self.find.dwReserved1.zeroize(); + self.find.cFileName.zeroize(); + self.find.cAlternateFileName.zeroize(); + } +} diff --git a/platform/pqkeep-platform/src/source_metadata_windows_find.rs b/platform/pqkeep-platform/src/source_metadata_windows_find.rs new file mode 100644 index 0000000..abf5c43 --- /dev/null +++ b/platform/pqkeep-platform/src/source_metadata_windows_find.rs @@ -0,0 +1,68 @@ +//! DE: Metadaten-Fallback bei Sharing-/Zugriffsfehlern ohne gewöhnlichen Find-Record. +//! EN: Sharing/access-error metadata fallback without an ordinary find record. +use super::{SourceMetadata, io}; +use std::ptr; +use windows_sys::Win32::{ + Foundation::INVALID_HANDLE_VALUE, + Storage::FileSystem::{ + FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, FindClose, FindExInfoBasic, + FindExSearchNameMatch, FindFirstFileExW, + }, +}; + +impl SourceMetadata { + /// DE: Nur explizite Testfixture; echten Find-Aufruf auf Caller-Ziel prüfen. + /// EN: Explicit fixture only; test the actual find call on caller-owned storage. + /// # Errors + /// DE/EN: Ungültiger Pfad oder nativer Find-Fehler / invalid path or native find failure. + #[cfg(feature = "native-metadata-fixture")] + pub fn capture_find_fixture(&mut self, path: &[u16]) -> io::Result<()> { + use zeroize::Zeroize; + self.zeroize(); + crate::path_windows::validate(path)?; + self.capture_find(path, io::ErrorKind::PermissionDenied.into()) + } + + pub(super) fn capture_find(&mut self, path: &[u16], original: io::Error) -> io::Result<()> { + // DE: Keine Wildcard-Abfrage durch den Fallback; Verbatim-Präfix ist kein Dateiname. + // EN: Never turn the fallback into a wildcard query; verbatim prefix is not a name. + let tail = if path.starts_with(&[92, 92, 63, 92]) { + &path[4..] + } else { + path + }; + if tail.iter().any(|&unit| unit == 42 || unit == 63) { + return Err(original); + } + // DE: capture hat NUL-Geometrie über open validiert; tatsächliches SDK-Ziel bleibt exklusiv. + // SAFETY: Called only after validated open failed; path is terminated and + // live. The actual WIN32_FIND_DATAW target is aligned, exclusive and complete. + let handle = unsafe { + FindFirstFileExW( + path.as_ptr(), + FindExInfoBasic, + std::ptr::from_mut(&mut self.find).cast(), + FindExSearchNameMatch, + ptr::null(), + 0, + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(original); + } + // DE: Sofort schließen, keine fallible Arbeit oder Unwindstelle dazwischen. + // SAFETY: Successful FindFirstFileExW returned this fresh owned search + // handle; close exactly once before decoding the retained protected record. + if unsafe { FindClose(handle) } == 0 { + return Err(io::Error::last_os_error()); + } + // DE/EN: Caller-Record nach FindClose ausschließlich leihen / borrow caller record after close. + let native = &self.find; + self.symlink = native.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 + && native.dwReserved0 & 0x2000_0000 != 0; + self.directory = !self.symlink && native.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0; + self.file = !self.symlink && !self.directory; + self.bytes = (u64::from(native.nFileSizeHigh) << 32) | u64::from(native.nFileSizeLow); + Ok(()) + } +} diff --git a/src/files/mod.rs b/src/files/mod.rs index 6807f15..7ebebe1 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -50,6 +50,7 @@ mod signer_v3; mod slot_v2; mod source_entries; mod source_entry; +mod source_metadata; mod stream_v4; mod tail_v4; mod tail_v4_drain; diff --git a/src/files/native_path.rs b/src/files/native_path.rs index fa24451..ab3d45c 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -104,6 +104,18 @@ impl NativePath { std::ffi::CStr::from_bytes_with_nul(self.encoded()?).map_err(|_| Error::Crypto) } + #[cfg(any(target_os = "linux", windows))] + pub(super) fn metadata_into(&self, output: &mut pqkeep_platform::SourceMetadata) -> Result<()> { + #[cfg(target_os = "linux")] + output.capture(self.c_str()?)?; + #[cfg(windows)] + { + let converted = windows::for_open(self)?; + output.capture(converted.as_ref().unwrap_or(self).encoded()?)?; + } + Ok(()) + } + pub(super) fn try_duplicate(&self) -> Result { let units = self.encoded()?; Self::from_native(&units[..units.len() - 1]) diff --git a/src/files/source_metadata.rs b/src/files/source_metadata.rs new file mode 100644 index 0000000..2c5c4db --- /dev/null +++ b/src/files/source_metadata.rs @@ -0,0 +1,35 @@ +//! DE: Tatsächliche native Metadaten vor Kernel-Ausgabe stabil sperren. +//! EN: Stably lock actual native metadata before kernel output. +use super::native_path::NativePath; +use crate::{Error, Result, crypto::secret_state::SecretState}; +use std::path::Path; + +pub(super) struct Metadata(SecretState); + +impl Metadata { + pub(super) fn read(path: &Path) -> Result { + let mut output = Self(SecretState::new(pqkeep_platform::SourceMetadata::empty())?); + let path = NativePath::from_path(path).map_err(|error| match error { + Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), + other => other, + })?; + path.metadata_into(output.0.get_mut())?; + Ok(output) + } + pub(super) fn is_file(&self) -> bool { + self.0.get().is_file() + } + pub(super) fn is_dir(&self) -> bool { + self.0.get().is_dir() + } + pub(super) fn is_symlink(&self) -> bool { + self.0.get().is_symlink() + } + pub(super) fn bytes(&self) -> u64 { + self.0.get().bytes() + } +} + +#[cfg(test)] +#[path = "source_metadata_tests.rs"] +mod tests; diff --git a/src/files/source_metadata_tests.rs b/src/files/source_metadata_tests.rs new file mode 100644 index 0000000..6b1a548 --- /dev/null +++ b/src/files/source_metadata_tests.rs @@ -0,0 +1,179 @@ +//! DE: Tatsächliche native Records, No-Follow, Fehler und Sperrverweigerung. +//! EN: Actual native records, no-follow, errors and lock refusal. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::Error; +#[cfg(target_os = "linux")] +use crate::hardening::memlock; + +fn locked(metadata: &Metadata) { + let record = metadata.0.get(); + crate::locked_owner_test_support::locked(record); + #[cfg(windows)] + { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(record).addr(); + assert!(query.get_mut().is_locked(start).unwrap()); + assert!( + query + .get_mut() + .is_locked(start + size_of_val(record) - 1) + .unwrap() + ); + } +} + +#[test] +fn actual_native_records_match_public_files_and_directory_reference() { + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("public-ä-日本語"); + std::fs::write(&file, b"public metadata fixture").unwrap(); + for path in [&file, &root.path().to_path_buf()] { + let native = Metadata::read(path).unwrap(); + locked(&native); + let reference = std::fs::symlink_metadata(path).unwrap(); + assert_eq!(native.is_file(), reference.is_file()); + assert_eq!(native.is_dir(), reference.is_dir()); + assert_eq!(native.is_symlink(), reference.file_type().is_symlink()); + assert_eq!(native.bytes(), reference.len()); + locked(&native); + } +} + +#[test] +fn missing_and_nul_paths_keep_native_io_error_classes() { + let root = tempfile::tempdir().unwrap(); + assert!(matches!( + Metadata::read(&root.path().join("missing")), + Err(Error::Io(std::io::ErrorKind::NotFound)) + )); + assert!(matches!( + Metadata::read(Path::new("bad\0name")), + Err(Error::Io(std::io::ErrorKind::InvalidInput)) + )); +} + +#[cfg(unix)] +#[test] +fn dangling_symlink_is_not_followed_or_misclassified() { + let root = tempfile::tempdir().unwrap(); + let link = root.path().join("link"); + std::os::unix::fs::symlink(root.path().join("missing-target"), &link).unwrap(); + let metadata = Metadata::read(&link).unwrap(); + locked(&metadata); + assert!(metadata.is_symlink()); + assert!(!metadata.is_file()); + assert!(!metadata.is_dir()); + assert_eq!( + metadata.bytes(), + std::fs::symlink_metadata(&link).unwrap().len() + ); +} + +#[cfg(windows)] +#[test] +fn native_metadata_matches_std_while_a_file_is_open_without_sharing() { + use std::os::windows::fs::OpenOptionsExt; + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("held-public-file"); + std::fs::write(&path, b"public sharing fixture").unwrap(); + let _held = std::fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&path) + .unwrap(); + let metadata = Metadata::read(&path).unwrap(); + locked(&metadata); + assert!(metadata.is_file()); + assert_eq!( + metadata.bytes(), + std::fs::symlink_metadata(&path).unwrap().len() + ); +} + +#[cfg(target_os = "linux")] +#[test] +fn actual_metadata_denial_and_unwind_leave_parent_limits_unchanged() { + use rustix::process::{Resource, getrlimit}; + let baseline = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::source_metadata::tests::metadata_denial_child", + "PQKEEP_SOURCE_METADATA_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), baseline); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn metadata_denial_child() { + use rustix::process::{Resource, getrlimit, setrlimit}; + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("public-file"); + std::fs::write(&file, b"public fixture").unwrap(); + let baseline = memlock::stats().locked_pages; + let caught = std::panic::catch_unwind(|| { + let metadata = Metadata::read(&file).unwrap(); + locked(&metadata); + std::panic::resume_unwind(Box::new(())); + }); + assert!(caught.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert!(matches!(Metadata::read(&file), Err(Error::MemoryLock))); + assert_eq!(memlock::stats().locked_pages, baseline); +} + +#[cfg(windows)] +#[test] +fn direct_find_fixture_writes_actual_sdk_record_into_prelocked_caller() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("public-find-ä"); + std::fs::write(&path, b"public find fixture").unwrap(); + let encoded = NativePath::from_path(&path).unwrap(); + let mut metadata = + Metadata(SecretState::new(pqkeep_platform::SourceMetadata::empty()).unwrap()); + locked(&metadata); + metadata + .0 + .get_mut() + .capture_find_fixture(encoded.encoded().unwrap()) + .unwrap(); + locked(&metadata); + assert!(metadata.is_file()); + assert!(!metadata.is_symlink()); + assert_eq!( + metadata.bytes(), + std::fs::symlink_metadata(&path).unwrap().len() + ); +} + +#[cfg(windows)] +#[test] +fn windows_file_directory_and_dangling_symlinks_keep_no_follow_semantics() { + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("target-file"); + let directory = root.path().join("target-directory"); + std::fs::write(&file, b"public symlink fixture").unwrap(); + std::fs::create_dir(&directory).unwrap(); + let file_link = root.path().join("file-link"); + let dir_link = root.path().join("directory-link"); + let dangling = root.path().join("dangling"); + std::os::windows::fs::symlink_file(&file, &file_link).unwrap(); + std::os::windows::fs::symlink_dir(&directory, &dir_link).unwrap(); + std::os::windows::fs::symlink_file(root.path().join("missing"), &dangling).unwrap(); + for path in [&file_link, &dir_link, &dangling] { + let metadata = Metadata::read(path).unwrap(); + locked(&metadata); + assert!(metadata.is_symlink()); + assert!(!metadata.is_file()); + assert!(!metadata.is_dir()); + assert_eq!( + metadata.bytes(), + std::fs::symlink_metadata(path).unwrap().len() + ); + } +} diff --git a/src/files/walk.rs b/src/files/walk.rs index e048910..5c9cd01 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -47,8 +47,8 @@ pub(crate) fn collect_file(path: &Path) -> Result { } fn collect_file_into(path: &Path, entries: &mut SourceEntries) -> Result<()> { - let meta = fs::symlink_metadata(path)?; - if !meta.file_type().is_file() { + let meta = super::source_metadata::Metadata::read(path)?; + if !meta.is_file() { return Err(Error::InvalidInput { field: "source" }); } let name = path @@ -56,7 +56,7 @@ fn collect_file_into(path: &Path, entries: &mut SourceEntries) -> Result<()> { .and_then(|n| n.to_str()) .ok_or(Error::InvalidInput { field: "path" })?; paths::validate_only(name)?; - entries.push(name, path, false, meta.len()) + entries.push(name, path, false, meta.bytes()) } /// DE: Ordner rekursiv; der Ordner selbst ist nicht Teil des Archivs. @@ -92,7 +92,7 @@ pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, Vec other, }); } - let kind = fs::symlink_metadata(src)?.file_type(); + let kind = super::source_metadata::Metadata::read(src)?; if kind.is_symlink() { skipped.push(Skipped { path: name.to_owned(), @@ -135,7 +135,7 @@ fn collect_tree( entries: &mut SourceEntries, skipped: &mut Vec, ) -> Result<()> { - if !fs::symlink_metadata(root)?.file_type().is_dir() { + if !super::source_metadata::Metadata::read(root)?.is_dir() { return Err(Error::InvalidInput { field: "source" }); } let mut stack = vec![(root.to_path_buf(), ConfidentialText::from_text(base)?)]; @@ -187,7 +187,7 @@ fn visit( subdirs.push((abs.clone(), ConfidentialText::joined(rel.expose()?, "/")?)); entries.push(rel.expose()?, &abs, true, 0)?; } else if file_type.is_file() { - let size = fs::symlink_metadata(&abs)?.len(); + let size = super::source_metadata::Metadata::read(&abs)?.bytes(); entries.push(rel.expose()?, &abs, false, size)?; } else { return skip(SkipReason::Special); From fc26cc969251a2226c30b10f88bdbe798eb39600 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:05:31 +0100 Subject: [PATCH 16/26] Fail closed on unverified Linux CLI startup protection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Core-Limit-Rücklesung fallibel prüfen und Linux-CLI vor argv/Secrets bei nicht nachgewiesenem Schutz verweigern. Echte begrenzte Syscall-Verweigerungen und beide Featurekonfigurationen geprüft. EN: Checked native getter, mandatory pre-ingress gate and actual denial tests; joint R7/R8 remains in progress, no partial merge. --- docs/ROADMAP.md | 6 + docs/SPEC.en.md | 5 + docs/SPEC.md | 5 + docs/security/LINUX_STARTUP_CAPABILITY.md | 51 ++++++ .../pqkeep-platform/src/core_limits_linux.rs | 22 +++ platform/pqkeep-platform/src/lib.rs | 5 + src/cli/mod.rs | 7 + src/hardening/mod.rs | 6 +- tests/hardening_cli_gate.rs | 159 ++++++++++++++++++ 9 files changed, 262 insertions(+), 4 deletions(-) create mode 100644 docs/security/LINUX_STARTUP_CAPABILITY.md create mode 100644 platform/pqkeep-platform/src/core_limits_linux.rs create mode 100644 tests/hardening_cli_gate.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 10897ca..4f75fc7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -206,3 +206,9 @@ DE/EN: R7/R8 weiterhin in Arbeit: native Quellmetadaten direkt vorab gesperrt lokal entwickelt / prelocked native source metadata locally developed; Abnahme läuft / validation running. DirEntry/Traversierung/Skip/Output/Reports und Prozess-/Helper-Verträge bleiben offen / remain open. + +DE/EN: R7/R8 in progress: fallible Linux-Core-Rücklesung und zwingende CLI- +Startprüfung vor argv lokal implementiert / fallible Linux core readback and +mandatory pre-argv CLI startup check locally implemented. Echte drei negative +Syscall-Pfade und normaler Start bestanden / three actual refusal paths and +normal startup passed; integrierte/native Abnahme läuft / acceptance running. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 2b8af6f..52be8f4 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -586,3 +586,8 @@ EN: R7/R8 source collection captures native metadata directly in prelocked libc/SDK records without private std::fs::Metadata return values. No-follow and Windows reparse/sharing semantics stay explicit. Full local/native acceptance pending; see security/SOURCE_METADATA_VALIDATION.md for the actual boundary. + +EN: R7 Linux CLI must establish/read back core limits and dumpability before +argv/secret ingress. Native core readback is fallible; unknown/refused queries +confirm no capability. Static bilingual startup failure replaces panic. +Windows/host/helper acceptance remains open: security/LINUX_STARTUP_CAPABILITY.md. diff --git a/docs/SPEC.md b/docs/SPEC.md index 37e63ac..10cf5f8 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -593,3 +593,8 @@ DE: R7/R8-Quellsammlung erfasst native Metadaten direkt in vorab gesperrten libc-/SDK-Records, ohne privaten std::fs::Metadata-Rückgabewert. No-Follow- Semantik und Windows-Reparse-/Sharing-Vertrag bleiben explizit. Lokale/native Vollabnahme offen; security/SOURCE_METADATA_VALIDATION.md beschreibt die Grenze. + +DE: R7-Linux-CLI setzt/prüft Core-Limits und Dumpable vor argv-/Secret-Eintritt +zwingend. Native Core-Rücklesung ist fallibel, unbekannte/verweigerte Abfragen +bestätigen keine Fähigkeit; statischer zweisprachiger Startfehler statt Panic. +Windows-/Host-/Helper-Abnahme offen: security/LINUX_STARTUP_CAPABILITY.md. diff --git a/docs/security/LINUX_STARTUP_CAPABILITY.md b/docs/security/LINUX_STARTUP_CAPABILITY.md new file mode 100644 index 0000000..b3b2d68 --- /dev/null +++ b/docs/security/LINUX_STARTUP_CAPABILITY.md @@ -0,0 +1,51 @@ +# Checked Linux startup / Geprüfter Linux-Start + +DE: R7-Teil im gemeinsamen Draft355. Eigene begrenzte Seccomp-Probe hat den +bisherigen Fehler tatsächlich reproduziert: Verweigerte Core-Limit-Rücklesung +führt bei der bisherigen rustix-getrlimit-Verwendung zu Panic101. Der unveränderte +CLI-Binaryhash und alle verwendeten rlib-/Quellhashes sind im lokalen Baseline- +Nachweis erfasst. Kein erfolgreicher Verweigerungsschutz aus diesem Fehler abgeleitet. +EN: The failed reproduction is retained. The baseline executable and dependency +artifacts remained byte-identical; probe compilation wrote separate evidence only. + +## Implementation / Umsetzung + +DE: Linux-Observe verwendet eine fallible libc-getrlimit-Abfrage mit geprüftem +Rückgabewert und echtem SDK-Typ. Initialisierte öffentliche Policy-Daten sind +keine privaten Anwendungsdaten. Ein notwendiger FFI-Aufruf bleibt ausschließlich +im Plattformmodul; Root-forbid unverändert. Fehler/Unbekannt bestätigt kein Flag. +EN: Direct library observation remains read-only. No implicit host-policy mutation +is added. Existing permitted IPC_LOCK handling is unchanged; no new privilege or +capability expansion. Core-limit and dumpability capabilities remain separate +from the explicitly partial Windows WER observation. + +DE: Linux-CLI verweigert jetzt zwingend vor argv-Sammlung, Dialogen oder Secret- +Verarbeitung, wenn der eigene Startschutz beide Core-Limits auf0 und NotDumpable +nicht tatsächlich setzt und zurückliest. Kein reiner Warnpfad und kein +--no-sandbox-Bypass. Statischer zweisprachiger Fehler auf stderr, Exit1; keine +Argumente nur für die Fehlerformatierung einlesen, keine Teilausgabe. +EN: This includes help/version under an unverified Linux startup because private +arguments must not be collected first to select an exemption. Successful CLI/JSON +behavior is retained. Windows flows stay available while verified Windows/native +helper support is still being developed; this is not a Windows capability claim. + +## Actual tests / Tatsächliche Tests + +DE: Je ein eigener exec-Prozess verweigert PR_SET_DUMPABLE, PR_GET_DUMPABLE oder +die lesende Core-prlimit64-Abfrage mit echtem EPERM. Keine simulierten Rückgaben. +Die CLI muss sichtbar vor Eingabe/Zielausgabe abbrechen, ohne Panic; Elternlimits +und Dumpable-Zustand bleiben unverändert. Timeout beendet/wartet nur das eigene +Kind. exec ersetzt den Probeprozess, sodass kein Enkel zurückbleibt. +EN: Test restrictions apply only to the own short-lived probe thread/process; +no host policy, account, Registry or unrelated process is changed. Normal actual +process hardening/idempotence remains tested. Initial source-bound runtime check +passed all three refusal modes and the normal case on881 unchanged sources. + +DE: Finaler integrierter Checkpoint linux-cli-gate-v3:888 Rust-/Manifest-Hashes +über14 erfolgreiche Prüfungen unverändert. Vier strenge Root-Lints (Linux/Windows, +API/ohne API), zwei Plattform-Lints sowie je22 CLI-/Hardening-Integrationstests +pro Featurekonfiguration bestanden. Alle drei echten Verweigerungen ausgeführt. +EN: Native metadata integration is included. Format, source limits and unchanged +provider inventory/matrix gates pass. Native Linux/ARM startup acceptance pending. Library-host capability contracts, verified Windows process support, +native password helpers and all remaining R8 metadata remain open. No complete +P1–P5/R7/R8/147 acceptance and no partial Main merge. diff --git a/platform/pqkeep-platform/src/core_limits_linux.rs b/platform/pqkeep-platform/src/core_limits_linux.rs new file mode 100644 index 0000000..6938b3a --- /dev/null +++ b/platform/pqkeep-platform/src/core_limits_linux.rs @@ -0,0 +1,22 @@ +//! DE: Kernel-Limitabfrage mit echter Fehlerprüfung statt Unfehlbarkeitsannahme. +//! EN: Check actual kernel-query failure instead of assuming infallibility. +use std::io; + +/// DE: Aktuelles Core-Limit dieses Prozesses ohne Policy-Änderung prüfen. +/// EN: Check this process's current core limits without changing policy. +/// # Errors +/// DE/EN: Native Verweigerung, etwa Seccomp / native refusal, including seccomp. +pub fn core_limits_disabled() -> io::Result { + // DE/EN: Öffentliche Policy-Diagnose, keine privaten Anwendungsdaten / public policy diagnostic only. + let mut limits = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + // DE: Tatsächlicher libc-Typ, vollständig initialisiertes exklusives Ziel. + // SAFETY: RLIMIT_CORE is valid; limits has the actual SDK layout/alignment + // and remains writable/exclusive for the synchronous call. No pointer is retained. + if unsafe { libc::getrlimit(libc::RLIMIT_CORE, &raw mut limits) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(limits.rlim_cur == 0 && limits.rlim_max == 0) +} diff --git a/platform/pqkeep-platform/src/lib.rs b/platform/pqkeep-platform/src/lib.rs index d28a376..ec98787 100644 --- a/platform/pqkeep-platform/src/lib.rs +++ b/platform/pqkeep-platform/src/lib.rs @@ -36,3 +36,8 @@ pub use path_windows::{absolute_path_into, open_file_read}; mod source_metadata; #[cfg(any(target_os = "linux", windows))] pub use source_metadata::SourceMetadata; + +#[cfg(target_os = "linux")] +mod core_limits_linux; +#[cfg(target_os = "linux")] +pub use core_limits_linux::core_limits_disabled; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index a74f2e3..c6d0918 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -91,6 +91,13 @@ use self::text::{Texts, texts}; /// DE: Einstiegspunkt der CLI. EN: CLI entry point. pub fn run() -> ExitCode { let report = hardening::harden_process(); + #[cfg(target_os = "linux")] + if !report.complete() { + // DE: Vor argv-/Dialog-/Secret-Eintritt verweigern, nicht bloß warnen. + // EN: Refuse before argv/dialog/secret ingress instead of merely warning. + eprintln!("Prozessschutz nicht nachgewiesen / process protection unavailable"); + return ExitCode::FAILURE; + } let argv: Vec = std::env::args().collect(); let lang = args::detect_lang(&argv); let t = texts(lang); diff --git a/src/hardening/mod.rs b/src/hardening/mod.rs index 59aaf0a..a3d5b17 100644 --- a/src/hardening/mod.rs +++ b/src/hardening/mod.rs @@ -64,8 +64,7 @@ pub fn observe_process() -> HardeningReport { #[cfg(target_os = "linux")] mod platform { use rustix::process::{ - DumpableBehavior, Resource, Rlimit, dumpable_behavior, getrlimit, set_dumpable_behavior, - setrlimit, + DumpableBehavior, Resource, Rlimit, dumpable_behavior, set_dumpable_behavior, setrlimit, }; use super::HardeningReport; @@ -87,9 +86,8 @@ mod platform { } pub(super) fn observe() -> HardeningReport { - let core = getrlimit(Resource::Core); HardeningReport { - core_dumps_disabled: core.current == Some(0) && core.maximum == Some(0), + core_dumps_disabled: pqkeep_platform::core_limits_disabled().unwrap_or(false), not_dumpable: matches!(dumpable_behavior(), Ok(DumpableBehavior::NotDumpable)), wer_heap_reporting_disabled: false, } diff --git a/tests/hardening_cli_gate.rs b/tests/hardening_cli_gate.rs new file mode 100644 index 0000000..147c32e --- /dev/null +++ b/tests/hardening_cli_gate.rs @@ -0,0 +1,159 @@ +//! DE: Eigene begrenzte CLI-Prozesse bei echter Syscall-Verweigerung prüfen. +//! EN: Test bounded own CLI processes under actual syscall refusal. +#![cfg(target_os = "linux")] +#![allow(clippy::unwrap_used)] + +use seccompiler::{ + BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, + SeccompRule, TargetArch, +}; +use std::{ + collections::BTreeMap, + io::Read, + process::{Child, Command, Stdio}, + time::{Duration, Instant}, +}; + +struct Owned(Child); +impl Drop for Owned { + fn drop(&mut self) { + if matches!(self.0.try_wait(), Ok(None)) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } +} + +#[test] +fn actual_cli_refuses_before_input_or_output_on_missing_linux_capability() { + use rustix::process::{Resource, dumpable_behavior, getrlimit}; + let before = (getrlimit(Resource::Core), dumpable_behavior()); + for mode in ["read-core", "set-dumpable", "read-dumpable"] { + let root = tempfile::tempdir().unwrap(); + let mut child = probe(mode, root.path()); + let (status, stdout, stderr) = child.output(); + assert_eq!(status.code(), Some(1), "{mode}: {stderr}"); + assert!( + stderr.contains("process protection unavailable"), + "{mode}: {stderr}" + ); + assert!(!stderr.contains("panicked")); + assert!(!root.path().join("must-not-exist.json").exists()); + // DE/EN: libtest schreibt vor exec öffentliche Startzeilen / public libtest startup before exec. + assert!(!stdout.contains("key") && !stdout.contains("Schlüssel")); + } + assert_eq!((getrlimit(Resource::Core), dumpable_behavior()), before); +} + +fn probe(mode: &str, root: &std::path::Path) -> Owned { + Owned( + Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "denied_cli_entry", + "--ignored", + "--test-threads=1", + ]) + .env("PQKEEP_GATE_DENIAL", mode) + .env("PQKEEP_GATE_ROOT", root) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(), + ) +} + +impl Owned { + fn output(&mut self) -> (std::process::ExitStatus, String, String) { + let deadline = Instant::now() + Duration::from_secs(30); + let status = loop { + if let Some(status) = self.0.try_wait().unwrap() { + break status; + } + assert!(Instant::now() < deadline, "own CLI probe timed out"); + std::thread::sleep(Duration::from_millis(10)); + }; + let mut stdout = String::new(); + let mut stderr = String::new(); + self.0 + .stdout + .take() + .unwrap() + .read_to_string(&mut stdout) + .unwrap(); + self.0 + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + (status, stdout, stderr) + } +} + +fn condition(arg: u8, value: u64) -> SeccompCondition { + SeccompCondition::new(arg, SeccompCmpArgLen::Qword, SeccompCmpOp::Eq, value).unwrap() +} + +fn denial(mode: &str) -> BpfProgram { + let mut rules = BTreeMap::new(); + if mode == "read-core" { + rules.insert( + libc::SYS_prlimit64, + vec![ + SeccompRule::new(vec![ + condition(1, u64::from(libc::RLIMIT_CORE)), + condition(2, 0), + ]) + .unwrap(), + ], + ); + } else { + let operation = if mode == "set-dumpable" { + libc::PR_SET_DUMPABLE + } else { + libc::PR_GET_DUMPABLE + }; + rules.insert( + libc::SYS_prctl, + vec![SeccompRule::new(vec![condition(0, u64::try_from(operation).unwrap())]).unwrap()], + ); + } + BpfProgram::try_from( + SeccompFilter::new( + rules, + SeccompAction::Allow, + SeccompAction::Errno(u32::try_from(libc::EPERM).unwrap()), + TargetArch::try_from(std::env::consts::ARCH).unwrap(), + ) + .unwrap(), + ) + .unwrap() +} + +#[test] +#[ignore = "DE/EN: Nur eigener begrenzter exec-Prozess / bounded own exec process only"] +fn denied_cli_entry() { + use std::os::unix::process::CommandExt; + let mode = std::env::var("PQKEEP_GATE_DENIAL").unwrap(); + let root = std::env::var_os("PQKEEP_GATE_ROOT").unwrap(); + seccompiler::apply_filter(&denial(&mode)).unwrap(); + // DE: exec ersetzt nur diesen eigenen Prozess; kein Enkel bleibt bei Timeout zurück. + // EN: exec replaces only this own process; timeout leaves no grandchild behind. + let error = Command::new(env!("CARGO_BIN_EXE_pqkeep")) + .args([ + "generate", + "--name", + "public-gate-fixture", + "--algorithm", + "ml-dsa-65", + "--out", + "must-not-exist.json", + "--passphrase-stdin", + ]) + .current_dir(root) + .stdin(Stdio::null()) + .exec(); + eprintln!("own fixture exec failed: {}", error.kind()); + std::process::exit(90); +} From d5642d9ce413a06ac0354610e0017fd2804651e7 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:35:26 +0100 Subject: [PATCH 17/26] Verify own Windows process ACL from a reduced inspector thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Konkret freigegebene CI-Probe senkt Privilegien nur im eigenen Token-Duplikat und Inspector-Thread; unveränderte sieben Zugriffsverweigerungen und vollständigen Primärprivileg-Zustand prüfen. EN: Scoped approved experiment, no memory reads or host changes; privileged bypass retained explicitly, no complete R7 acceptance. --- .../WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md | 14 +- .../examples/process_access_probe.rs | 29 +++++ .../process_access_probe/privileges.rs | 30 ++++- .../process_access_probe/restricted.rs | 121 ++++++++++++++++++ scripts/test_process_access_probe.ps1 | 6 +- 5 files changed, 190 insertions(+), 10 deletions(-) create mode 100644 platform/pqkeep-platform/examples/process_access_probe/restricted.rs diff --git a/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md index 44e211a..8e4b3be 100644 --- a/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md +++ b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md @@ -1,9 +1,10 @@ # Restricted CI inspector / Reduzierter CI-Inspector DE: Konkreter Folgeversuch zu P2 des freigegebenen gemeinsamen R7/R8-Plans. -Noch nicht zur Ausführung freigegeben. Bisherige Freigabe galt nur der eigenen -Prozess-DACL und Zugriffsprobe, ausdrücklich ohne Token-/Threadänderungen. -EN: Locally developed and cross-checked only until additional concrete approval. +Am28.11.2026 ausdrücklich für diese eigene reduzierte Windows-CI-Probe freigegeben. +Die frühere DACL-Freigabe wurde dabei nicht pauschal auf Tokenänderungen erweitert. +EN: Explicit scoped owner approval recorded; implementation/cross-checks pass, +native execution is still required. This is a test, not production protection. ## Observed failure / Beobachteter Fehler @@ -30,7 +31,8 @@ DE: Nur im bereits eigenen kurzlebigen Inspector-Hauptthread: Privilegien zulassen. Keine Veränderung des ursprünglichen Primärtokens. 5. Dieselben sieben sensiblen OpenProcess-Rechte müssen AccessDenied liefern; QueryLimited/Synchronize müssen weiterhin funktionieren. Zustand des ursprünglichen - Primärtokens vor/nachher muss gleich sein. Kein Skip/abgeschwächter Rechteumfang. + Primärtokens vor/nachher muss gleich sein (sämtliche Privileg-IDs und Flags, +nicht nur das Debugflag; keine Werte protokollieren). Kein Skip/abgeschwächter Rechteumfang. EN: Before reduction, if actual debug privilege is enabled, open and immediately close one VM_READ control handle to the same owned target without reading memory. @@ -50,8 +52,8 @@ administrators. No production helper/CLI policy is installed by this experiment. DE: Beispiele process_access_probe.rs und process_access_probe/{privileges, restricted}.rs sowie eine konkrete Änderung des vorhandenen PowerShell-Harness: Argument inspect-restricted statt inspect; feste öffentliche Kontroll-/Readback- -Diagnose auch bei Erfolg festhalten. Geplanter Harness liegt vor Freigabe nur -in der geschützten Analyseablage; bestehender Workflow führt ihn noch nicht aus. +Diagnose auch bei Erfolg festhalten. Der genehmigte Harness verwendet +jetzt inspect-restricted; native Ergebnisse werden separat dokumentiert. EN: Same two owned children, same own Process/PID tracking, same bounded10-second startup/inspection/exit and kill/wait cleanup; no unknown processes or shared endpoint. diff --git a/platform/pqkeep-platform/examples/process_access_probe.rs b/platform/pqkeep-platform/examples/process_access_probe.rs index 005a903..410d58a 100644 --- a/platform/pqkeep-platform/examples/process_access_probe.rs +++ b/platform/pqkeep-platform/examples/process_access_probe.rs @@ -6,6 +6,9 @@ #[cfg(windows)] #[path = "process_access_probe/privileges.rs"] mod privileges; +#[cfg(windows)] +#[path = "process_access_probe/restricted.rs"] +mod restricted; #[cfg(windows)] mod windows { @@ -132,6 +135,10 @@ mod windows { "INSPECTOR debug_privilege_enabled={}", super::privileges::debug_enabled()? ); + check_access(pid) + } + + fn check_access(pid: u32) -> io::Result<()> { for rights in [0x10, 0x20, 0x08, 0x40, 0x02, WRITE_DAC, 0x80000] { match open(pid, rights) { Ok(_) => { @@ -152,6 +159,24 @@ mod windows { Ok(()) } + fn inspect_restricted(pid: u32) -> io::Result<()> { + let primary_before = super::privileges::primary_snapshot()?; + if super::privileges::debug_enabled()? { + // DE: Privilegierte Kontrolle schließen, bevor der Thread reduziert wird. + // EN: Close the privileged control handle before reducing the thread. + drop(open(pid, 0x10)?); + eprintln!("CONTROL: privileged VM_READ handle allowed and closed"); + } + let _duplicate = super::restricted::own_thread()?; + eprintln!("INSPECTOR effective_thread_privileges_enabled=false"); + check_access(pid)?; + if super::privileges::primary_snapshot()? != primary_before { + return Err(io::Error::other("original primary privilege state changed")); + } + eprintln!("PASS: original primary privilege state unchanged"); + Ok(()) + } + pub(super) fn run() -> io::Result<()> { let mut args = std::env::args().skip(1); match (args.next().as_deref(), args.next()) { @@ -160,6 +185,10 @@ mod windows { pid.parse() .map_err(|_| io::Error::other("invalid process ID"))?, ), + (Some("inspect-restricted"), Some(pid)) if args.next().is_none() => inspect_restricted( + pid.parse() + .map_err(|_| io::Error::other("invalid process ID"))?, + ), _ => Err(io::Error::other("invalid public probe arguments")), } } diff --git a/platform/pqkeep-platform/examples/process_access_probe/privileges.rs b/platform/pqkeep-platform/examples/process_access_probe/privileges.rs index d7c6b19..3b84456 100644 --- a/platform/pqkeep-platform/examples/process_access_probe/privileges.rs +++ b/platform/pqkeep-platform/examples/process_access_probe/privileges.rs @@ -31,6 +31,34 @@ fn own_token() -> io::Result { pub(super) fn debug_enabled() -> io::Result { let token = own_token()?; + query(&token, enabled) +} + +// DE: Alle ursprünglichen Privileg-IDs/-Flags vergleichen, keine Werte protokollieren. +// EN: Compare every original privilege ID/flag without logging the values. +pub(super) fn primary_snapshot() -> io::Result> { + query(&own_token()?, |values| { + let mut snapshot: Vec<_> = values + .iter() + .map(|v| (v.Luid.HighPart, v.Luid.LowPart, v.Attributes)) + .collect(); + snapshot.sort_unstable(); + Ok(snapshot) + }) +} + +pub(super) fn any_enabled(token: &OwnedHandle) -> io::Result { + query(token, |values| { + Ok(values + .iter() + .any(|value| value.Attributes & SE_PRIVILEGE_ENABLED != 0)) + }) +} + +fn query( + token: &OwnedHandle, + inspect: impl FnOnce(&[LUID_AND_ATTRIBUTES]) -> io::Result, +) -> io::Result { let (mut buffer, mut needed) = ([0u32; 512], 0); // SAFETY: Live own TOKEN_QUERY handle; initialized aligned2048byte buffer; // exact capacity passed and exclusive output count. No token writes. @@ -66,7 +94,7 @@ pub(super) fn debug_enabled() -> io::Result { count, ) }; - enabled(values) + inspect(values) } fn enabled(values: &[LUID_AND_ATTRIBUTES]) -> io::Result { diff --git a/platform/pqkeep-platform/examples/process_access_probe/restricted.rs b/platform/pqkeep-platform/examples/process_access_probe/restricted.rs new file mode 100644 index 0000000..4d39000 --- /dev/null +++ b/platform/pqkeep-platform/examples/process_access_probe/restricted.rs @@ -0,0 +1,121 @@ +//! DE: Ausdrücklich freigegebene eigene CI-Threadprobe, kein Produktionspfad. +//! Primärtoken nur lesen/duplizieren, Privilegien ausschließlich im Duplikat senken. +//! EN: Explicitly approved own CI thread experiment, not a production path. +//! Read/duplicate primary token only; lower privileges exclusively on the duplicate. + +use std::{ + io, + os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}, +}; +use windows_sys::Win32::{ + Security::{ + AdjustTokenPrivileges, DuplicateTokenEx, SecurityImpersonation, TOKEN_ADJUST_PRIVILEGES, + TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY, TokenImpersonation, + }, + System::Threading::{ + GetCurrentProcess, GetCurrentThread, OpenProcessToken, OpenThreadToken, SetThreadToken, + }, +}; + +fn duplicate_primary() -> io::Result { + let mut original = std::ptr::null_mut(); + // SAFETY: Borrow current-process pseudo handle, request only query/duplicate; + // initialized exclusive output. No adjustment access on the original token. + if unsafe { + OpenProcessToken( + GetCurrentProcess(), + TOKEN_QUERY | TOKEN_DUPLICATE, + &raw mut original, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + if original.is_null() { + return Err(io::Error::other("missing own source token")); + } + // SAFETY: New uniquely owned real handle from successful OpenProcessToken. + let original = unsafe { OwnedHandle::from_raw_handle(original) }; + let mut copy = std::ptr::null_mut(); + let rights = TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE; + // SAFETY: Live query/duplicate handle; null attributes prohibit inheritance. + // Creates a distinct owned impersonation token, never adjusts the original. + if unsafe { + DuplicateTokenEx( + original.as_raw_handle(), + rights, + std::ptr::null(), + SecurityImpersonation, + TokenImpersonation, + &raw mut copy, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + if copy.is_null() { + return Err(io::Error::other("missing own duplicate token")); + } + // SAFETY: Successful duplication returned one new real handle, owned once. + Ok(unsafe { OwnedHandle::from_raw_handle(copy) }) +} + +fn thread_token() -> io::Result> { + let mut token = std::ptr::null_mut(); + // SAFETY: Current-thread pseudo handle, query only, initialized exclusive + // output; OpenAsSelf checks access, it does not change the token or identity. + if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &raw mut token) } == 0 { + let error = io::Error::last_os_error(); + return if error.raw_os_error() == Some(1008) { + Ok(None) + } else { + Err(error) + }; + } + if token.is_null() { + return Err(io::Error::other("missing own thread query token")); + } + // SAFETY: Successful open returned a new uniquely owned real query handle. + Ok(Some(unsafe { OwnedHandle::from_raw_handle(token) })) +} + +pub(super) fn own_thread() -> io::Result { + if thread_token()?.is_some() { + return Err(io::Error::other( + "unexpected preexisting thread impersonation", + )); + } + let token = duplicate_primary()?; + // SAFETY: Live uniquely owned DUPLICATE token with adjustment access; + // TRUE disables every privilege, other parameters are documented ignored/null. + // Neither original primary token nor account privileges are adjusted. + if unsafe { + AdjustTokenPrivileges( + token.as_raw_handle(), + 1, + std::ptr::null(), + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + if super::privileges::any_enabled(&token)? { + return Err(io::Error::other("duplicate privileges remain enabled")); + } + // SAFETY: NULL selects only the calling test thread. Live duplicate is an + // impersonation token at SecurityImpersonation level with TOKEN_IMPERSONATE. + // Never restore/enable privileges; this owned ephemeral thread exits afterward. + if unsafe { SetThreadToken(std::ptr::null(), token.as_raw_handle()) } == 0 { + return Err(io::Error::last_os_error()); + } + let actual = thread_token()?.ok_or_else(|| io::Error::other("missing applied thread token"))?; + if super::privileges::any_enabled(&actual)? { + return Err(io::Error::other( + "effective thread privileges remain enabled", + )); + } + Ok(token) +} diff --git a/scripts/test_process_access_probe.ps1 b/scripts/test_process_access_probe.ps1 index 79e60ed..ac0406e 100644 --- a/scripts/test_process_access_probe.ps1 +++ b/scripts/test_process_access_probe.ps1 @@ -33,13 +33,13 @@ try { $ready = $target.StandardOutput.ReadLineAsync() if (-not $ready.Wait(10000)) { throw 'Own target readiness timeout' } if ($ready.Result -cne "READY $($target.Id)") { throw 'Own target identity mismatch' } - $inspector = New-Probe -Arguments @('inspect', [string]$target.Id) + $inspector = New-Probe -Arguments @('inspect-restricted', [string]$target.Id) $inspector.StandardInput.Close() if (-not $inspector.WaitForExit(10000)) { throw 'Own inspector timeout' } $result = $inspector.StandardOutput.ReadToEnd() + # DE/EN: Ausschließlich öffentliche Probenkontrolle / public probe control only. + Write-Output ($inspector.StandardError.ReadToEnd().Trim()) if ($inspector.ExitCode -ne 0 -or -not $result.StartsWith('PASS:')) { - # DE/EN: Nur feste öffentliche Probenfehler, keine Geheimwerte / public probe errors only. - Write-Output ($inspector.StandardError.ReadToEnd()) throw 'Own inspector rejected process access policy' } $target.StandardInput.Close() From bd8dfc519af28fd779cb0977ea63ee2c622e8549 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:01:05 +0100 Subject: [PATCH 18/26] Prelock skipped records and concrete OS-name conversion state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Skip-Records, Arena-/Wachstumszustand und konkreten Iterator vor Befüllung sperren; fallible Borrow-Aufrufer gemeinsam migrieren. UTF8/UTF16-Ersatz direkt gesperrt, konkreter Windows-Encoder samt pending surrogate geschützt. EN: Source-bound16-command/899-source acceptance, real resource denial/unwind and69 selected integrations pass; native acceptance pending, remaining joint R7/R8 scope stays open. --- docs/ROADMAP.md | 4 + docs/SPEC.en.md | 4 + docs/SPEC.md | 4 + docs/security/LINUX_STARTUP_CAPABILITY.md | 4 +- docs/security/SKIPPED_RECORD_VALIDATION.md | 48 +++++ docs/security/SOURCE_METADATA_VALIDATION.md | 6 +- .../WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md | 14 +- src/cli/files_cmd.rs | 26 +-- src/cli/files_many.rs | 8 +- src/cli/mod.rs | 1 + src/cli/report.rs | 52 ++++++ src/cli/stream_cmd.rs | 2 +- src/files/confidential_os_text.rs | 91 ++++++++++ src/files/confidential_os_text_tests.rs | 65 +++++++ src/files/confidential_os_text_windows.rs | 44 +++++ src/files/encrypt.rs | 8 +- src/files/locked_wide.rs | 65 +++++++ src/files/locked_wide_tests.rs | 35 ++++ src/files/mod.rs | 19 +- src/files/native_path.rs | 12 +- src/files/skipped.rs | 57 ++++++ src/files/skipped_entries.rs | 125 +++++++++++++ src/files/skipped_entries_iter.rs | 52 ++++++ src/files/skipped_entries_tests.rs | 171 ++++++++++++++++++ src/files/walk.rs | 36 ++-- tests/files_many.rs | 2 +- tests/files_output.rs | 8 +- tests/files_roundtrip.rs | 2 +- 28 files changed, 896 insertions(+), 69 deletions(-) create mode 100644 docs/security/SKIPPED_RECORD_VALIDATION.md create mode 100644 src/cli/report.rs create mode 100644 src/files/confidential_os_text.rs create mode 100644 src/files/confidential_os_text_tests.rs create mode 100644 src/files/confidential_os_text_windows.rs create mode 100644 src/files/locked_wide.rs create mode 100644 src/files/locked_wide_tests.rs create mode 100644 src/files/skipped.rs create mode 100644 src/files/skipped_entries.rs create mode 100644 src/files/skipped_entries_iter.rs create mode 100644 src/files/skipped_entries_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 4f75fc7..3dcb057 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -212,3 +212,7 @@ Startprüfung vor argv lokal implementiert / fallible Linux core readback and mandatory pre-argv CLI startup check locally implemented. Echte drei negative Syscall-Pfade und normaler Start bestanden / three actual refusal paths and normal startup passed; integrierte/native Abnahme läuft / acceptance running. + + +DE: R7/R8 weiterhin In progress in Draft355: native Quellmetadaten8ea8 und Linux-Startgatefc26 vollständig nativ geprüft. Ausdrücklich freigegebene reduzierte Windows-CI-Probed564 erfolgreich, keine vollständige Prozessgarantie. Nächster Teil schützt Skip-Records/UTF-Namenskonvertierung; komplette native Traversierung, Ziel-/Report-/Helper-/Host-Verträge bleiben offen. +EN: Same joint PR, no partial Main merge or whole-issue closure; skipped-record source-bound/native acceptance pending. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 52be8f4..0b89cf6 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -591,3 +591,7 @@ EN: R7 Linux CLI must establish/read back core limits and dumpability before argv/secret ingress. Native core readback is fallible; unknown/refused queries confirm no capability. Static bilingual startup failure replaces panic. Windows/host/helper acceptance remains open: security/LINUX_STARTUP_CAPABILITY.md. + + +EN: R8 skipped records use a prelocked arena, growth state and concrete iterator instead of Vec/String. path()/reason()/try_iter() are fallible borrow APIs; Skipped/Report Debug is redacted. Lossy OS-name conversion writes directly to locked output, including prelocked concrete Windows UTF16 iterator state. Scope and acceptance: security/SKIPPED_RECORD_VALIDATION.md. +DE: Gesperrte Skip-Retention und explizite fallible Ausgabe; übrige R7/R8-Verträge bleiben erforderlich. diff --git a/docs/SPEC.md b/docs/SPEC.md index 10cf5f8..d87d443 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -598,3 +598,7 @@ DE: R7-Linux-CLI setzt/prüft Core-Limits und Dumpable vor argv-/Secret-Eintritt zwingend. Native Core-Rücklesung ist fallibel, unbekannte/verweigerte Abfragen bestätigen keine Fähigkeit; statischer zweisprachiger Startfehler statt Panic. Windows-/Host-/Helper-Abnahme offen: security/LINUX_STARTUP_CAPABILITY.md. + + +DE: R8-Skip-Records verwenden eine vor Befüllung gesperrte Arena samt Wachstum und konkretem Iterator statt Vec/String. path()/reason()/try_iter() sind fallible Borrow-APIs; Debug von Skipped/Report bleibt redigiert. Verlustbehaftete OS-Namen direkt gesperrt konvertieren, unter Windows auch den konkreten UTF16-Iterator vor Nutzung sperren. Aktuelle Grenzen und Abnahme: security/SKIPPED_RECORD_VALIDATION.md. +EN: Protected skipped-record retention and explicit fallible disclosure; file/CLI compatibility and all remaining R7/R8 obligations remain required. diff --git a/docs/security/LINUX_STARTUP_CAPABILITY.md b/docs/security/LINUX_STARTUP_CAPABILITY.md index b3b2d68..ad913b1 100644 --- a/docs/security/LINUX_STARTUP_CAPABILITY.md +++ b/docs/security/LINUX_STARTUP_CAPABILITY.md @@ -46,6 +46,8 @@ DE: Finaler integrierter Checkpoint linux-cli-gate-v3:888 Rust-/Manifest-Hashes API/ohne API), zwei Plattform-Lints sowie je22 CLI-/Hardening-Integrationstests pro Featurekonfiguration bestanden. Alle drei echten Verweigerungen ausgeführt. EN: Native metadata integration is included. Format, source limits and unchanged -provider inventory/matrix gates pass. Native Linux/ARM startup acceptance pending. Library-host capability contracts, verified Windows process support, +provider inventory/matrix gates pass. Nativefc26cc9 accepted: Linux22/ARM973tests each, latest1867, Windows1686, +zero failures. Actual pre-ingress denial parent runs in both Linux architectures; +full logs and source hashes retained. Windows is a compatibility result only. Library-host capability contracts, verified Windows process support, native password helpers and all remaining R8 metadata remain open. No complete P1–P5/R7/R8/147 acceptance and no partial Main merge. diff --git a/docs/security/SKIPPED_RECORD_VALIDATION.md b/docs/security/SKIPPED_RECORD_VALIDATION.md new file mode 100644 index 0000000..e9e68b7 --- /dev/null +++ b/docs/security/SKIPPED_RECORD_VALIDATION.md @@ -0,0 +1,48 @@ +# Protected skipped records / Geschützte Skip-Records + +DE: M1/M5-Teil im gemeinsamen R7/R8-Draft355, kein Abschluss der gesamten Zeilen. +Gewöhnliche Vec-Records und path:String durch begrenzte gesperrte Arena +ersetzen. Konkreter Arenaowner, verwendete Länge, Wachstumscursor und tatsächlicher +Iterator vor privater Befüllung sperren; Pfade sind ConfidentialText. Feldweise +fallible Wachstumskopien zwischen gesperrten Zielen; Fehler erhalten alte Records. +Record/Arenapadding und Cursor vor Unlock löschen, auch bei Fehler/Unwind. +EN: No populated whole-record move, infallible clone, default Serialize or private +Debug. Report Debug is redacted. Existing summary counters and transports still +need separate protection; redaction alone is not complete M5 acceptance. + +DE: Ungültige native Namen ohne Cow/String/format!-Zwischenspeicher direkt in +SecretBytes konvertieren. UTF8-Ersatzgrenzen wie std; Windows-Unpaired-Surrogates +wie OsStr::to_string_lossy, nicht wie ungültige UTF8-Bytes. Konkreter EncodeWide- +Iterator samt pending low surrogate vor dem ersten next sperren. Kein privater +decode_utf16-Zwischeniterator. NativePath verwendet denselben gesperrten Encoder. +EN: Valid original bytes, lossy replacement semantics, ordering and skip reasons +stay compatible. std read_dir/DirEntry/file_name/PathBuf and traversal stacks are +still actual internal ordinary buffers; this change does not relabel them external. + +## Rust migration / Rust-Migration + +DE: Report.skipped ist SkippedEntries statt Vec. len()/is_empty() bleiben; +get(index) und try_iter() liefern Result. Iterator-Items sind Result<&Skipped>; +path() leiht Result<&str>, reason() liefert Result. Kein Indexzugriff, +Clone oder frei kopierbares path-Feld. CLI-Caller prüfen Records vor erster +Berichtsausgabe und verwenden den bereits gesperrten Cursor nochmals per rewind. +EN: Propagate memory/index/internal errors rather than silently truncate. Tests +copy only public fixture output explicitly. File formats and JSON schemas remain +unchanged. Terminal control escaping and all plain report/stdio/JSON workspaces +remain separate open M5 work; output() is an explicit disclosure, not a claim +that downstream application or OS buffers are locked. + +## Verification / Prüfung + +DE: Tatsächliches Wachstum über mehrere Arenen, Reihenfolge/rewind, lebende +Record-/Leaf-/Cursor-Sperren und reale Dateisystem-Skips. Linux-Kind verweigert +Wachstum und Iterator-Allokation bei echtem Nullbudget; alte Records erhalten, +Elternlimit unverändert, Registry- und Kernel-VmLck-Baseline nach Unwind exakt. +Windows-SDK-Seitenprüfung beobachtet Arena/Cursor und echten pending surrogate. +EN: Public std oracles cover every byte, malformed/truncated UTF8, deterministic +mixed byte sequences, all unpaired UTF16 surrogate units and actual pairs. +Source-bound skipped-records-v1:16 commands and899 unchanged Rust/manifest hashes +pass. Four strict root and two platform lints;97 file groups per feature config, +69 actual selected integration cases. Native acceptance remains pending; no new unsafe or +package dependency. Mandatory root-forbid, authentication-before-output, +resource limits and previous accepted provider behavior stay intact. diff --git a/docs/security/SOURCE_METADATA_VALIDATION.md b/docs/security/SOURCE_METADATA_VALIDATION.md index 227a879..4edf374 100644 --- a/docs/security/SOURCE_METADATA_VALIDATION.md +++ b/docs/security/SOURCE_METADATA_VALIDATION.md @@ -52,14 +52,16 @@ Dangling-Link, Fehlerklassen, konkrete Owner-/Windows-Seitenbeobachtung und begrenztes eigenes Speicherfehler-/Unwind-Kind mit unverändertem Elternlimit. Windows-Fälle für Datei-/Verzeichnis-/Dangling-Links, exklusiven Öffner und echten direkten Find-Aufruf in vorab gesperrtes Caller-Ziel sind cross-kompiliert; -die tatsächliche native Ausführung steht noch aus. +die tatsächliche native Ausführung ist am signierten8ea8d76 bestanden. DE: Lokaler source-metadata-v1-Checkpoint:886 unveränderte Rust-/Manifest-Hashes, 16 erfolgreiche Kommandos. Plattform-All-Feature-Lints auf Linux/Windows-GNU, acht Plattformtests, vier strenge Root-Lints mit/ohne API auf beiden Zielen, je92 Dateigruppen mit/ohne API,57 Integrationen. Elf ignorierte Kind-/Race- Einstiege bleiben sichtbar; tatsächlicher Metadaten-Fehlerkindaufruf bestanden. EN: Root/platform formatting, limits, strict vendor/matrix and diff checks pass. -Native Windows/ARM64 and usual final gates remain required. No complete metadata, +Native8ea8d76 full Rust logs pass: Linux22/ARM972tests each, latest1865, +Windows1686; zero failures. Actual SDK/Find/sharing/symlink cases execute; +source-bound logs/hashes retained. Final integrated gates remain required. No complete metadata, M1/M3, R7/R8 or147 acceptance is claimed by this document. Sources / Quellen: diff --git a/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md index 8e4b3be..c4d9fa7 100644 --- a/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md +++ b/docs/security/WINDOWS_RESTRICTED_INSPECTOR_PROPOSAL.md @@ -4,7 +4,7 @@ DE: Konkreter Folgeversuch zu P2 des freigegebenen gemeinsamen R7/R8-Plans. Am28.11.2026 ausdrücklich für diese eigene reduzierte Windows-CI-Probe freigegeben. Die frühere DACL-Freigabe wurde dabei nicht pauschal auf Tokenänderungen erweitert. EN: Explicit scoped owner approval recorded; implementation/cross-checks pass, -native execution is still required. This is a test, not production protection. +native Windows job141011002581 passes atd5642d9. This is a test, not production protection. ## Observed failure / Beobachteter Fehler @@ -69,3 +69,15 @@ Sources / Quellen: - https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-duplicatetokenex - https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges - https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadtoken + +## Actual acceptance / Tatsächliche Abnahme + +DE: Genehmigter Windows-Job am signiertend5642d9 erfolgreich: privilegierter +VM_READ-Kontrollhandle geöffnet und sofort geschlossen; effektives Threadtoken +hat keine aktivierten Privilegien. Alle sieben unveränderten sensiblen Rechte +verweigert, LimitedQuery/Synchronize erlaubt. Sämtliche ursprünglichen Primär- +privileg-IDs/-Flags unverändert; beide eigenen Kinder beendet. Kein Speicherlesen. +EN: Exact head and five control/success markers verified in the complete hashed +native log. Both strict platform lints and format/limits/diff pass. The historical +privileged bypass is preserved. This does not establish protection from admin, +thread objects, inherited handles, local dump policy, or complete P2/R7 support. diff --git a/src/cli/files_cmd.rs b/src/cli/files_cmd.rs index 937a25f..c29ab08 100644 --- a/src/cli/files_cmd.rs +++ b/src/cli/files_cmd.rs @@ -8,7 +8,7 @@ use clap::ArgMatches; use pqkeep::crypto::factor::Factor; use pqkeep::crypto::kdf::{KdfParams, KdfProfile}; use pqkeep::envelope; -use pqkeep::files::{self, PassphraseAccess, Protection, Report, SkipReason}; +use pqkeep::files::{self, PassphraseAccess, Protection, Report}; use pqkeep::security::{Lang, StrongPassphrase}; use super::io::{CliResult, Failure, code, read_confirmed_stdin, read_passphrase}; @@ -206,23 +206,7 @@ pub(super) fn shown(path: &Path) -> String { out } -pub(super) fn print_report(t: &Texts, lang: Lang, verb: &str, out: &Path, report: &Report) { - println!("{verb}: {}", shown(out)); - println!( - "{}: {} / {} / {}", - t.msg_summary, report.files, report.directories, report.bytes - ); - for skipped in &report.skipped { - let reason = match skipped.reason { - SkipReason::Symlink => t.skip_symlink, - SkipReason::Special => t.skip_special, - SkipReason::NonUtf8Name => t.skip_non_utf8, - _ => t.skip_invalid, - }; - eprintln!("{}: {} ({reason})", t.msg_skipped, skipped.path); - } - super::signing::print(lang, report.signer.as_ref()); -} +pub(super) use super::report::print_report; /// DE: Verstecktes `--temp-tag` (vom Kontextmenü) an die Bibliothek geben. /// EN: Pass the hidden `--temp-tag` (from the context menu) to the library. @@ -256,7 +240,7 @@ pub fn encrypt(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult { t.msg_encrypted, out.as_deref().unwrap_or(&src), &report, - ); + )?; return Ok(()); } let out = target(t, m, default_for(m, default_encrypted(&src)))?; @@ -264,7 +248,7 @@ pub fn encrypt(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult { let report = protection .encrypt(&src, &out) .map_err(|e| Failure::from_error(&e, lang))?; - print_report(t, lang, t.msg_encrypted, &out, &report); + print_report(t, lang, t.msg_encrypted, &out, &report)?; Ok(()) } @@ -295,6 +279,6 @@ pub fn decrypt(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult { (out.unwrap_or_default(), r.map_err(fail)?) }; drop(opened); - print_report(t, lang, t.msg_decrypted, &out, &report); + print_report(t, lang, t.msg_decrypted, &out, &report)?; Ok(()) } diff --git a/src/cli/files_many.rs b/src/cli/files_many.rs index 50722e8..ac73ecf 100644 --- a/src/cli/files_many.rs +++ b/src/cli/files_many.rs @@ -58,8 +58,12 @@ impl<'a> Tally<'a> { self.total += 1; match r { Ok((verb, report)) => { + if let Err(failure) = print_report(t, lang, verb, out, &report) { + eprintln!("{}: {}", self.s.failed, failure.message); + self.first_error.get_or_insert(failure.code); + return; + } self.ok += 1; - print_report(t, lang, verb, out, &report); if self.progress.is_some() && let Some(name) = out.file_name() { @@ -105,7 +109,7 @@ pub fn encrypt(t: &Texts, lang: Lang, m: &ArgMatches, sources: &[PathBuf]) -> Cl protection.encrypt_many(&list, out).map_err(fail)?, ) }; - print_report(t, lang, t.msg_encrypted, &out, &report); + print_report(t, lang, t.msg_encrypted, &out, &report)?; return Ok(()); } super::privacy::check_out(m, false, lang)?; diff --git a/src/cli/mod.rs b/src/cli/mod.rs index c6d0918..345671b 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -47,6 +47,7 @@ mod recipients_ui; mod rekey_cmd; mod rekey_input; mod rekey_text; +mod report; mod sandbox; mod secret_input; #[cfg(feature = "api")] diff --git a/src/cli/report.rs b/src/cli/report.rs new file mode 100644 index 0000000..463dccf --- /dev/null +++ b/src/cli/report.rs @@ -0,0 +1,52 @@ +//! DE: Vertrauliche Skip-Records bewusst für den CLI-Bericht ausleihen. +//! EN: Explicitly borrow confidential skip records for CLI report disclosure. +use super::{ + files_cmd::shown, + io::{CliResult, Failure}, + text::Texts, +}; +use pqkeep::{ + files::{Report, SkipReason}, + security::Lang, +}; +use std::path::Path; + +pub(super) fn print_report( + t: &Texts, + lang: Lang, + verb: &str, + out: &Path, + report: &Report, +) -> CliResult { + let fail = |error: pqkeep::Error| Failure::from_error(&error, lang); + let mut entries = report.skipped.try_iter().map_err(fail)?; + // DE: Alle Records vor der ersten Berichtsausgabe prüfen; Cursor ohne Allokation zurücksetzen. + // EN: Validate every record before the first report output; rewind without allocating. + for entry in entries.by_ref() { + let entry = entry.map_err(fail)?; + entry.path().map_err(fail)?; + entry.reason().map_err(fail)?; + } + entries.rewind(); + println!("{verb}: {}", shown(out)); + println!( + "{}: {} / {} / {}", + t.msg_summary, report.files, report.directories, report.bytes + ); + for skipped in entries { + let skipped = skipped.map_err(fail)?; + let reason = match skipped.reason().map_err(fail)? { + SkipReason::Symlink => t.skip_symlink, + SkipReason::Special => t.skip_special, + SkipReason::NonUtf8Name => t.skip_non_utf8, + _ => t.skip_invalid, + }; + eprintln!( + "{}: {} ({reason})", + t.msg_skipped, + skipped.path().map_err(fail)? + ); + } + super::signing::print(lang, report.signer.as_ref()); + Ok(()) +} diff --git a/src/cli/stream_cmd.rs b/src/cli/stream_cmd.rs index 034a0bb..9424ccc 100644 --- a/src/cli/stream_cmd.rs +++ b/src/cli/stream_cmd.rs @@ -134,7 +134,7 @@ pub fn encrypt(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult { let protection = read_protection(t, lang, m)?; let (out, report) = run(&protection, m).map_err(|e| Failure::from_error(&e, lang))?; match out { - Some(out) => print_report(t, lang, t.msg_encrypted, &out, &report), + Some(out) => print_report(t, lang, t.msg_encrypted, &out, &report)?, None => report_stderr(t.msg_encrypted, t.msg_summary, &report), } Ok(()) diff --git a/src/files/confidential_os_text.rs b/src/files/confidential_os_text.rs new file mode 100644 index 0000000..687363a --- /dev/null +++ b/src/files/confidential_os_text.rs @@ -0,0 +1,91 @@ +//! DE: Verlustbehaftete Namen direkt gesperrt zusammensetzen, ohne Cow/String-Staging. +//! EN: Assemble lossy names directly in locked storage without Cow/String staging. +use super::ConfidentialText; +use crate::{ + Error, Result, + crypto::{SecretBytes, secret_state::SecretState}, +}; +use std::ffi::OsStr; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct Position { + read: usize, + write: usize, + valid: usize, + skip: usize, + pending: Option, +} +impl Drop for Position { + fn drop(&mut self) { + self.read.zeroize(); + self.write.zeroize(); + self.valid.zeroize(); + self.skip.zeroize(); + self.pending.zeroize(); + } +} +impl ZeroizeOnDrop for Position {} + +pub(super) fn joined_lossy(prefix: &str, name: &OsStr) -> Result { + if let Some(valid) = name.to_str() { + return ConfidentialText::joined(prefix, valid); + } + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + bytes_lossy(prefix, name.as_bytes()) + } + #[cfg(windows)] + windows::wide_lossy(prefix, name) +} + +fn output(prefix: &str, units: usize) -> Result { + let len = units + .checked_mul(3) + .and_then(|n| n.checked_add(prefix.len())) + .ok_or(Error::MemoryLock)?; + let mut out = SecretBytes::zeroed(len)?; + out.expose_mut()[..prefix.len()].copy_from_slice(prefix.as_bytes()); + Ok(out) +} + +#[cfg(unix)] +fn bytes_lossy(prefix: &str, bytes: &[u8]) -> Result { + let mut position = SecretState::new(Position::default())?; + let state = position.get_mut(); + let mut out = output(prefix, bytes.len())?; + state.write = prefix.len(); + while state.read < bytes.len() { + let remaining = &bytes[state.read..]; + match std::str::from_utf8(remaining) { + Ok(valid) => { + state.valid = valid.len(); + state.skip = 0; + } + Err(error) => { + state.valid = error.valid_up_to(); + state.skip = error.error_len().unwrap_or(remaining.len() - state.valid); + } + } + out.expose_mut()[state.write..state.write + state.valid] + .copy_from_slice(&remaining[..state.valid]); + state.read += state.valid; + state.write += state.valid; + if state.skip > 0 { + out.expose_mut()[state.write..state.write + 3].copy_from_slice("�".as_bytes()); + state.write += 3; + state.read += state.skip; + } + } + out.truncate(state.write); + ConfidentialText::from_locked(out) +} + +#[cfg(windows)] +#[path = "confidential_os_text_windows.rs"] +mod windows; + +#[cfg(test)] +#[path = "confidential_os_text_tests.rs"] +mod tests; diff --git a/src/files/confidential_os_text_tests.rs b/src/files/confidential_os_text_tests.rs new file mode 100644 index 0000000..14d5aa7 --- /dev/null +++ b/src/files/confidential_os_text_tests.rs @@ -0,0 +1,65 @@ +//! DE: Verlustbehaftete Ausgabe mit öffentlicher std-Referenz vergleichen. +//! EN: Compare lossy output against a public std oracle. +#![allow(clippy::unwrap_used)] +use super::*; + +fn check(name: &OsStr) { + let expected = format!("prefix/{}", name.to_string_lossy()); + let actual = joined_lossy("prefix/", name).unwrap(); + actual.assert_owner_locked(); + let equal = actual.expose().unwrap() == expected; + assert!(equal); +} + +#[test] +fn valid_unicode_and_empty_names_keep_original_bytes() { + for name in ["", "plain", "ä日本語", "😀", "line\ncontrol", "\0"] { + check(OsStr::new(name)); + } +} + +#[cfg(unix)] +#[test] +fn every_byte_and_malformed_sequence_matches_std_lossy_boundaries() { + use std::os::unix::ffi::OsStrExt; + for value in 0..=u8::MAX { + check(OsStr::from_bytes(&[value])); + } + for bytes in [ + &b"a\xffb\xc3"[..], + &b"\xe2\x82\xac\xe2\x82"[..], + &b"\xed\xa0\x80\xf0\x9f\x98\x80"[..], + &b"\xf4\x90\x80\x80"[..], + &b"\xc0\x80\xe0\x80\x80"[..], + ] { + check(OsStr::from_bytes(bytes)); + } + let mut seed = 1_u32; + for length in 0..128 { + let bytes: Vec<_> = (0..length) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + seed.to_le_bytes()[0] + }) + .collect(); + check(OsStr::from_bytes(&bytes)); + } +} + +#[cfg(windows)] +#[test] +fn unpaired_and_paired_surrogates_match_os_lossy_not_utf8_byte_replacement() { + use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + for units in [ + &[0xd800][..], + &[0xdc00][..], + &[0xd800, 0xdc00][..], + &[0xd800, 65, 0xdbff, 0xdfff, 0xdc00][..], + &[0xd800, 0xd800, 0xdc00, 0xdc00][..], + ] { + check(&OsString::from_wide(units)); + } + for unit in 0xd800..=0xdfff { + check(&OsString::from_wide(&[65, unit, 66])); + } +} diff --git a/src/files/confidential_os_text_windows.rs b/src/files/confidential_os_text_windows.rs new file mode 100644 index 0000000..41899d1 --- /dev/null +++ b/src/files/confidential_os_text_windows.rs @@ -0,0 +1,44 @@ +//! DE: UTF16-Ersatzzeichen ohne privaten decode_utf16-Zwischeniterator. +//! EN: UTF16 replacement without a private `decode_utf16` intermediate iterator. +use super::{ConfidentialText, Error, OsStr, Position, Result, SecretState, output}; +use crate::files::locked_wide::LockedWide; + +pub(super) fn wide_lossy(prefix: &str, name: &OsStr) -> Result { + let mut source = LockedWide::new(name)?; + let mut position = SecretState::new(Position::default())?; + let state = position.get_mut(); + let mut out = output(prefix, source.len())?; + state.write = prefix.len(); + while let Some(c) = next_scalar(&mut source, state)? { + state.write += c.encode_utf8(&mut out.expose_mut()[state.write..]).len(); + } + out.truncate(state.write); + ConfidentialText::from_locked(out) +} + +fn next_scalar(source: &mut LockedWide<'_>, state: &mut Position) -> Result> { + let first = match state.pending.take() { + Some(unit) => Some(unit), + None => source.next_unit()?, + }; + let Some(first) = first else { + return Ok(None); + }; + if (0xd800..=0xdbff).contains(&first) { + match source.next_unit()? { + Some(second) if (0xdc00..=0xdfff).contains(&second) => { + let scalar = + 0x0001_0000 + ((u32::from(first) - 0xd800) << 10) + u32::from(second) - 0xdc00; + return char::from_u32(scalar).map(Some).ok_or(Error::Crypto); + } + other => state.pending = other, + } + return Ok(Some(char::REPLACEMENT_CHARACTER)); + } + if (0xdc00..=0xdfff).contains(&first) { + return Ok(Some(char::REPLACEMENT_CHARACTER)); + } + char::from_u32(u32::from(first)) + .map(Some) + .ok_or(Error::Crypto) +} diff --git a/src/files/encrypt.rs b/src/files/encrypt.rs index f906418..62502df 100644 --- a/src/files/encrypt.rs +++ b/src/files/encrypt.rs @@ -84,7 +84,11 @@ fn encrypt_with( let (e, s) = walk::collect_dir(source)?; (e, s, Content::Directory) } else { - (walk::collect_file(source)?, Vec::new(), Content::File) + ( + walk::collect_file(source)?, + super::SkippedEntries::default(), + Content::File, + ) }; let job = Job { target, @@ -205,7 +209,7 @@ pub fn encrypt_many_under( fn write_archive( entries: &SourceEntries, - skipped: Vec, + skipped: super::SkippedEntries, content: Content, job: &Job<'_>, ) -> Result { diff --git a/src/files/locked_wide.rs b/src/files/locked_wide.rs new file mode 100644 index 0000000..a6d4e31 --- /dev/null +++ b/src/files/locked_wide.rs @@ -0,0 +1,65 @@ +//! DE: Konkreten UTF16-Iterator einschließlich pending surrogate vor Nutzung sperren. +//! EN: Prelock the concrete UTF16 iterator, including its pending surrogate. +use crate::{Error, Result, crypto::secret_state::SecretState}; +use std::{ + ffi::OsStr, + os::windows::ffi::{EncodeWide, OsStrExt}, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State<'a> { + iterator: EncodeWide<'a>, + len: usize, + position: usize, +} +impl Drop for State<'_> { + fn drop(&mut self) { + // DE/EN: Nur öffentliche leere Ersatzgeometrie / public empty replacement geometry only. + self.iterator = OsStr::new("").encode_wide(); + self.len.zeroize(); + self.position.zeroize(); + } +} +impl ZeroizeOnDrop for State<'_> {} + +pub(super) struct LockedWide<'a>(SecretState>); + +impl<'a> LockedWide<'a> { + pub(super) fn new(source: &'a OsStr) -> Result { + let mut out = Self(SecretState::new(State { + iterator: OsStr::new("").encode_wide(), + len: 0, + position: 0, + })?); + let state = out.0.get_mut(); + state.iterator = source.encode_wide(); + while state.iterator.next().is_some() { + state.len = state.len.checked_add(1).ok_or(Error::MemoryLock)?; + } + state.iterator = source.encode_wide(); + Ok(out) + } + pub(super) fn len(&self) -> usize { + self.0.get().len + } + pub(super) fn position(&self) -> usize { + self.0.get().position + } + pub(super) fn next_unit(&mut self) -> Result> { + let state = self.0.get_mut(); + let next = state.iterator.next(); + if next.is_some() { + state.position = state.position.checked_add(1).ok_or(Error::MemoryLock)?; + if state.position > state.len { + return Err(Error::Crypto); + } + } else if state.position != state.len { + return Err(Error::Crypto); + } + Ok(next) + } +} + +#[cfg(test)] +#[path = "locked_wide_tests.rs"] +mod tests; diff --git a/src/files/locked_wide_tests.rs b/src/files/locked_wide_tests.rs new file mode 100644 index 0000000..994d6ad --- /dev/null +++ b/src/files/locked_wide_tests.rs @@ -0,0 +1,35 @@ +//! DE: Konkretes pending-surrogate und Iteratorgeometrie bleiben gesperrt. +//! EN: Concrete pending surrogate and iterator geometry remain locked. +#![allow(clippy::unwrap_used)] +use super::*; + +fn locked(value: &LockedWide<'_>) { + let state = value.0.get(); + crate::locked_owner_test_support::locked(state); + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(state).addr(); + assert!(query.get_mut().is_locked(start).unwrap()); + assert!( + query + .get_mut() + .is_locked(start + size_of_val(state) - 1) + .unwrap() + ); +} + +#[test] +fn actual_encoder_keeps_pending_low_surrogate_in_prelocked_iterator() { + let mut source = LockedWide::new(OsStr::new("😀ä")).unwrap(); + locked(&source); + assert_eq!(source.len(), 3); + assert_eq!(source.next_unit().unwrap(), Some(0xd83d)); + locked(&source); + let mut moved = source; + locked(&moved); + assert_eq!(moved.next_unit().unwrap(), Some(0xde00)); + locked(&moved); + assert_eq!(moved.next_unit().unwrap(), Some(0x00e4)); + assert_eq!(moved.next_unit().unwrap(), None); + assert_eq!(moved.position(), moved.len()); +} diff --git a/src/files/mod.rs b/src/files/mod.rs index 7ebebe1..1b35108 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -17,6 +17,7 @@ mod archive; mod check; mod confidential_entries; mod confidential_framing; +mod confidential_os_text; mod confidential_path_index; mod confidential_text; mod decrypt; @@ -31,6 +32,8 @@ mod hidden_result; mod list; #[cfg(test)] mod locked_owner_tests; +#[cfg(windows)] +mod locked_wide; mod native_path; mod original; mod output; @@ -47,6 +50,8 @@ mod scan; mod signed_by; mod signed_io; mod signer_v3; +mod skipped; +mod skipped_entries; mod slot_v2; mod source_entries; mod source_entry; @@ -76,9 +81,11 @@ pub use original::{ChooseTarget, decrypt_original}; pub use random_name::{is_random_name, random_name, random_target}; pub use signed_by::SignedBy; pub use signer_v3::Signer; +pub use skipped::Skipped; +pub use skipped_entries::{SkippedEntries, SkippedIter}; pub use slot_v2::MAX_RECIPIENTS; pub use stream_v4::{encrypt_stream, encrypt_stream_to}; -pub use walk::{SkipReason, Skipped}; +pub use walk::SkipReason; use crate::Result; use crate::crypto::factor::Factor; @@ -161,7 +168,7 @@ pub enum Unlock<'a> { } /// DE: Bericht über einen Vorgang. EN: Report of an operation. -#[derive(Debug, Default, PartialEq, Eq)] +#[derive(Default, PartialEq, Eq)] pub struct Report { /// DE: Anzahl Dateien. EN: Number of files. pub files: u64, @@ -170,12 +177,18 @@ pub struct Report { /// DE: Summe der Dateigrößen. EN: Total size of files. pub bytes: u64, /// DE: Übersprungene Einträge (nur beim Verschlüsseln). EN: Skipped entries (encrypting only). - pub skipped: Vec, + pub skipped: SkippedEntries, /// DE: Geprüfter Absender (nur Format v3, beim Entschlüsseln/Prüfen). /// EN: Verified sender (format v3 only, when decrypting/checking). pub signer: Option, } +impl std::fmt::Debug for Report { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Report([REDACTED])") + } +} + /// DE: Liest nur den Header (ohne Schlüssel): Inhaltstyp, Schutzart, KDF-Parameter /// bzw. Empfänger-ID – hilft, den richtigen Schlüssel zu finden. Nur v1; für v2 siehe /// [`inspect_v2`]. diff --git a/src/files/native_path.rs b/src/files/native_path.rs index ab3d45c..c645286 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -51,18 +51,14 @@ impl NativePath { } #[cfg(windows)] { - use std::os::windows::ffi::OsStrExt; + let mut source = super::locked_wide::LockedWide::new(path.as_os_str())?; let mut out = Self::prepare()?; - let len = path.as_os_str().encode_wide().count(); - out.allocate(len)?; - for (slot, unit) in out.0.get_mut().0.expose_mut()[..len] - .iter_mut() - .zip(path.as_os_str().encode_wide()) - { + out.allocate(source.len())?; + while let Some(unit) = source.next_unit()? { if unit == 0 { return Err(Error::InvalidInput { field: "path" }); } - *slot = unit; + out.0.get_mut().0.expose_mut()[source.position() - 1] = unit; } Ok(out) } diff --git a/src/files/skipped.rs b/src/files/skipped.rs new file mode 100644 index 0000000..8f04936 --- /dev/null +++ b/src/files/skipped.rs @@ -0,0 +1,57 @@ +//! DE: Übersprungene Records nur in bereits gesperrten Slots befüllen. +//! EN: Populate skipped records only in already locked slots. +use super::{ConfidentialText, SkipReason}; +use crate::{Error, Result}; +use std::fmt; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +/// DE: Vertraulicher übersprungener Eintrag; Ausgabe explizit ausleihen. +/// EN: Confidential skipped entry; explicitly borrow for disclosure. +#[derive(Default, PartialEq, Eq)] +pub struct Skipped { + pub(super) path: Option, + reason: Option, +} +impl Skipped { + /// DE/EN: Relativen verlustbehafteten Namen ausleihen / borrow relative lossy name. + /// # Errors + /// DE/EN: [`Error::Crypto`] bei leerem/ungültigem Record / empty or invalid record. + pub fn path(&self) -> Result<&str> { + self.path.as_ref().ok_or(Error::Crypto)?.expose() + } + /// DE/EN: Grund explizit ausleihen / explicitly read reason. + /// # Errors + /// DE/EN: [`Error::Crypto`] bei leerem Record / empty record. + pub fn reason(&self) -> Result { + self.reason.ok_or(Error::Crypto) + } + pub(super) fn fill(&mut self, path: ConfidentialText, reason: SkipReason) -> Result<()> { + if self.path.is_some() || self.reason.is_some() { + return Err(Error::Crypto); + } + self.path = Some(path); + self.reason = Some(reason); + Ok(()) + } + pub(super) fn copy_from(&mut self, source: &Self) -> Result<()> { + let path = source.path.as_ref().ok_or(Error::Crypto)?.try_duplicate()?; + self.fill(path, source.reason()?) + } +} +impl Zeroize for Skipped { + fn zeroize(&mut self) { + self.path = None; + self.reason = None; + } +} +impl Drop for Skipped { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for Skipped {} +impl fmt::Debug for Skipped { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Skipped([REDACTED])") + } +} diff --git a/src/files/skipped_entries.rs b/src/files/skipped_entries.rs new file mode 100644 index 0000000..a16d0bc --- /dev/null +++ b/src/files/skipped_entries.rs @@ -0,0 +1,125 @@ +//! DE: Begrenzte Skip-Arena mit vor Befüllung gesperrten Records und Wachstumscursor. +//! EN: Bounded skip arena with prelocked records and growth cursor. +use super::{ConfidentialText, SkipReason, Skipped, paths::MAX_ENTRIES}; +use crate::{ + Error, Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, +}; +use std::fmt; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State { + records: SecretWorkspace, + used: usize, + scan: usize, +} +impl Drop for State { + fn drop(&mut self) { + self.records.zeroize(); + self.used.zeroize(); + self.scan.zeroize(); + } +} +impl ZeroizeOnDrop for State {} +impl ZeroizeOnDrop for crate::crypto::secret_buffer::SecretBuffer {} + +/// DE: Gesperrte übersprungene Einträge; leere Sammlung ist öffentlich leer. +/// EN: Locked skipped entries; an empty collection is public-empty. +#[derive(Default)] +pub struct SkippedEntries(Option>); + +#[path = "skipped_entries_iter.rs"] +mod iteration; +pub use iteration::SkippedIter; + +impl SkippedEntries { + /// DE/EN: Zahl der Einträge / number of entries. + #[must_use] + pub fn len(&self) -> usize { + self.0.as_ref().map_or(0, |state| state.get().used) + } + /// DE/EN: Leere Sammlung / empty collection. + #[must_use] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// DE: Einen Record ohne private Kopie ausleihen. + /// EN: Borrow one record without a private copy. + /// # Errors + /// DE/EN: Ungültiger Index/Record / invalid index or record. + pub fn get(&self, index: usize) -> Result<&Skipped> { + let state = self + .0 + .as_ref() + .ok_or(Error::InvalidInput { field: "index" })? + .get(); + if index >= state.used { + return Err(Error::InvalidInput { field: "index" }); + } + let record = state.records.expose().get(index).ok_or(Error::Crypto)?; + record.path()?; + record.reason()?; + Ok(record) + } + pub(super) fn push(&mut self, path: ConfidentialText, reason: SkipReason) -> Result<()> { + if self.0.is_none() { + self.0 = Some(SecretState::new(State { + records: SecretWorkspace::zeroed(0)?, + used: 0, + scan: 0, + })?); + } + let state = self.0.as_mut().ok_or(Error::Crypto)?.get_mut(); + state.reserve()?; + state.records.expose_mut()[state.used].fill(path, reason)?; + state.used += 1; + Ok(()) + } +} + +impl State { + fn reserve(&mut self) -> Result<()> { + let limit = usize::try_from(MAX_ENTRIES).map_err(|_| Error::MemoryLock)?; + if self.used >= limit { + return Err(Error::InvalidInput { field: "entries" }); + } + if self.used < self.records.expose().len() { + return Ok(()); + } + let capacity = self + .used + .checked_mul(2) + .ok_or(Error::MemoryLock)? + .max(16) + .min(limit); + let mut records = SecretWorkspace::::zeroed(capacity)?; + self.scan = 0; + while self.scan < self.used { + records.expose_mut()[self.scan].copy_from(&self.records.expose()[self.scan])?; + self.scan += 1; + } + self.records = records; + self.scan = 0; + Ok(()) + } +} + +impl fmt::Debug for SkippedEntries { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SkippedEntries([REDACTED])") + } +} +impl PartialEq for SkippedEntries { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() + && (0..self.len()).all(|index| { + self.get(index) + .is_ok_and(|left| other.get(index).is_ok_and(|right| left == right)) + }) + } +} +impl Eq for SkippedEntries {} + +#[cfg(test)] +#[path = "skipped_entries_tests.rs"] +mod tests; diff --git a/src/files/skipped_entries_iter.rs b/src/files/skipped_entries_iter.rs new file mode 100644 index 0000000..1f4fb7c --- /dev/null +++ b/src/files/skipped_entries_iter.rs @@ -0,0 +1,52 @@ +//! DE: Tatsächlichen Skip-Iterator einschließlich Quelle vor Nutzung sperren. +//! EN: Prelock the actual skip iterator, including its source, before use. +use super::{Result, SecretState, Skipped, SkippedEntries}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +pub(super) struct State<'a> { + source: Option<&'a SkippedEntries>, + position: usize, +} +impl Drop for State<'_> { + fn drop(&mut self) { + self.source = None; + self.position.zeroize(); + } +} +impl ZeroizeOnDrop for State<'_> {} + +/// DE: Fallibler gesperrter Borrow-Cursor. EN: Fallible locked borrow cursor. +pub struct SkippedIter<'a>(pub(super) SecretState>); +impl SkippedEntries { + /// DE: Konkreten Iterator vor der Quellübernahme sperren. + /// EN: Lock the concrete iterator before binding its source. + /// # Errors + /// DE/EN: [`crate::Error::MemoryLock`]. + pub fn try_iter(&self) -> Result> { + let mut out = SkippedIter(SecretState::new(State { + source: None, + position: 0, + })?); + out.0.get_mut().source = Some(self); + Ok(out) + } +} +impl SkippedIter<'_> { + /// DE/EN: Bereits gesperrten Cursor ohne neue Allokation zurücksetzen / rewind without allocation. + pub fn rewind(&mut self) { + self.0.get_mut().position = 0; + } +} +impl<'a> Iterator for SkippedIter<'a> { + type Item = Result<&'a Skipped>; + fn next(&mut self) -> Option { + let state = self.0.get_mut(); + let source = state.source?; + if state.position >= source.len() { + return None; + } + let result = source.get(state.position); + state.position += 1; + Some(result) + } +} diff --git a/src/files/skipped_entries_tests.rs b/src/files/skipped_entries_tests.rs new file mode 100644 index 0000000..bd28ef7 --- /dev/null +++ b/src/files/skipped_entries_tests.rs @@ -0,0 +1,171 @@ +//! DE: Echte Skip-Records, Wachstum, Cursor und Speicherfehler prüfen. +//! EN: Verify actual skip records, growth, cursors and memory failures. +#![allow(clippy::unwrap_used)] +use super::*; + +#[cfg(windows)] +fn physical(value: &T) { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(value).addr(); + assert!(query.get_mut().is_locked(start).unwrap()); + assert!( + query + .get_mut() + .is_locked(start + size_of_val(value) - 1) + .unwrap() + ); +} + +fn owners(entries: &SkippedEntries) { + let state = entries.0.as_ref().unwrap().get(); + crate::locked_owner_test_support::locked(state); + crate::locked_owner_test_support::locked(state.records.expose()); + #[cfg(windows)] + { + physical(state); + physical(state.records.expose()); + } + for record in &state.records.expose()[..state.used] { + crate::locked_owner_test_support::locked(record); + record.path.as_ref().unwrap().assert_owner_locked(); + } +} + +#[test] +fn growing_records_and_rewound_cursor_keep_paths_and_order() { + let mut entries = SkippedEntries::default(); + for index in 0..65 { + entries + .push( + ConfidentialText::from_text(&format!("skip-{index:03}")).unwrap(), + SkipReason::InvalidName, + ) + .unwrap(); + owners(&entries); + } + let mut cursor = entries.try_iter().unwrap(); + crate::locked_owner_test_support::locked(cursor.0.get()); + #[cfg(windows)] + physical(cursor.0.get()); + for index in 0..65 { + let record = cursor.next().unwrap().unwrap(); + let equal = record.path().unwrap() == format!("skip-{index:03}"); + assert!(equal); + assert_eq!(record.reason().unwrap(), SkipReason::InvalidName); + } + assert!(cursor.next().is_none()); + cursor.rewind(); + let equal = cursor.next().unwrap().unwrap().path().unwrap() == "skip-000"; + assert!(equal); + assert!(entries.get(65).is_err()); + assert!(!format!("{entries:?}").contains("skip-000")); + assert!(!format!("{:?}", entries.get(0).unwrap()).contains("skip-000")); +} + +#[test] +fn real_walker_retains_lossy_skip_names_in_locked_records() { + let root = tempfile::tempdir().unwrap(); + #[cfg(unix)] + let invalid_name = String::from("CON"); + #[cfg(windows)] + let invalid_name = "ä".repeat(128); + std::fs::write(root.path().join(&invalid_name), b"public fixture").unwrap(); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + std::fs::write( + root.path().join(std::ffi::OsStr::from_bytes(b"bad\xff")), + b"public fixture", + ) + .unwrap(); + } + let (_, entries) = super::super::walk::collect_dir(root.path()).unwrap(); + owners(&entries); + let equal = entries.get(0).unwrap().path().unwrap() == invalid_name; + assert!(equal); + assert_eq!( + entries.get(0).unwrap().reason().unwrap(), + SkipReason::InvalidName + ); + #[cfg(unix)] + { + let equal = entries.get(1).unwrap().path().unwrap() == "bad�"; + assert!(equal); + assert_eq!( + entries.get(1).unwrap().reason().unwrap(), + SkipReason::NonUtf8Name + ); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn actual_skip_denial_and_unwind_run_in_own_child() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::skipped_entries::tests::skip_denial_child", + "PQKEEP_SKIP_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn skip_denial_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + let baseline = memlock::stats().locked_pages; + let kernel_baseline = kernel_locked_bytes(); + let result = std::panic::catch_unwind(|| { + let mut entries = SkippedEntries::default(); + for index in 0..32 { + entries + .push( + ConfidentialText::from_text(&format!("skip-{index:03}")).unwrap(), + SkipReason::InvalidName, + ) + .unwrap(); + } + owners(&entries); + let live = memlock::stats().locked_pages; + let kernel_live = kernel_locked_bytes(); + let path = ConfidentialText::from_text("new").unwrap(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + assert!(matches!( + entries.push(path, SkipReason::Symlink), + Err(Error::MemoryLock) + )); + assert_eq!(entries.len(), 32); + assert_eq!(memlock::stats().locked_pages, live); + assert_eq!(kernel_locked_bytes(), kernel_live); + assert!(matches!(entries.try_iter(), Err(Error::MemoryLock))); + let equal = entries.get(0).unwrap().path().unwrap() == "skip-000"; + assert!(equal); + owners(&entries); + std::panic::resume_unwind(Box::new(())); + }); + assert!(result.is_err()); + assert_eq!(memlock::stats().locked_pages, baseline); + assert_eq!(kernel_locked_bytes(), kernel_baseline); +} + +#[cfg(target_os = "linux")] +fn kernel_locked_bytes() -> usize { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + .checked_mul(1024) + .unwrap() +} diff --git a/src/files/walk.rs b/src/files/walk.rs index 5c9cd01..e7520c5 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -9,9 +9,9 @@ use std::fs; use std::path::{Path, PathBuf}; -use super::ConfidentialText; use super::paths::{self, MAX_ENTRIES}; use super::source_entries::SourceEntries; +use super::{ConfidentialText, SkippedEntries}; use crate::{Error, Result}; /// DE: Grund für das Überspringen. EN: Reason for skipping. @@ -29,15 +29,6 @@ pub enum SkipReason { InvalidName, } -/// DE: Übersprungener Eintrag. EN: Skipped entry. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Skipped { - /// DE: Relativer Pfad (verlustbehaftet dargestellt). EN: Relative path (lossy). - pub path: String, - /// DE: Grund. EN: Reason. - pub reason: SkipReason, -} - /// DE: Einzeldatei als einziger Eintrag (Name muss portabel sein). /// EN: Single file as the only entry (name must be portable). pub(crate) fn collect_file(path: &Path) -> Result { @@ -61,8 +52,8 @@ fn collect_file_into(path: &Path, entries: &mut SourceEntries) -> Result<()> { /// DE: Ordner rekursiv; der Ordner selbst ist nicht Teil des Archivs. /// EN: Directory recursively; the directory itself is not part of the archive. -pub(crate) fn collect_dir(root: &Path) -> Result<(SourceEntries, Vec)> { - let (mut entries, mut skipped) = (SourceEntries::prepare()?, Vec::new()); +pub(crate) fn collect_dir(root: &Path) -> Result<(SourceEntries, SkippedEntries)> { + let (mut entries, mut skipped) = (SourceEntries::prepare()?, SkippedEntries::default()); collect_tree(root, "", &mut entries, &mut skipped)?; entries.sort()?; Ok((entries, skipped)) @@ -74,11 +65,11 @@ pub(crate) fn collect_dir(root: &Path) -> Result<(SourceEntries, Vec)> /// EN: Several sources as one archive (multi-selection): each source becomes a top-level entry, /// directories with their content. Equal names (ignoring case) → abort; a selected symlink is /// skipped and reported. -pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, Vec)> { +pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, SkippedEntries)> { if sources.is_empty() || sources.len() as u64 > MAX_ENTRIES { return Err(Error::InvalidInput { field: "source" }); } - let (mut entries, mut skipped) = (SourceEntries::prepare()?, Vec::new()); + let (mut entries, mut skipped) = (SourceEntries::prepare()?, SkippedEntries::default()); let mut names = paths::PathSet::default(); for src in sources { let name = src @@ -94,10 +85,7 @@ pub(crate) fn collect_many(sources: &[&Path]) -> Result<(SourceEntries, Vec Result<(SourceEntries, Vec Result<(SourceEntries, Vec)> { +) -> Result<(SourceEntries, SkippedEntries)> { if paths::validate(root)?.len() != 1 { return Err(Error::InvalidInput { field: "path" }); } @@ -133,7 +121,7 @@ fn collect_tree( root: &Path, base: &str, entries: &mut SourceEntries, - skipped: &mut Vec, + skipped: &mut SkippedEntries, ) -> Result<()> { if !super::source_metadata::Metadata::read(root)?.is_dir() { return Err(Error::InvalidInput { field: "source" }); @@ -160,15 +148,15 @@ fn visit( child: &fs::DirEntry, prefix: &str, entries: &mut SourceEntries, - skipped: &mut Vec, + skipped: &mut SkippedEntries, subdirs: &mut Vec<(PathBuf, ConfidentialText)>, ) -> Result<()> { let name = child.file_name(); let mut skip = |reason| { - skipped.push(Skipped { - path: format!("{prefix}{}", name.to_string_lossy()), + skipped.push( + super::confidential_os_text::joined_lossy(prefix, &name)?, reason, - }); + )?; Ok(()) }; let Some(name) = name.to_str() else { diff --git a/tests/files_many.rs b/tests/files_many.rs index 466d770..331a2b4 100644 --- a/tests/files_many.rs +++ b/tests/files_many.rs @@ -106,7 +106,7 @@ fn selected_symlink_is_skipped_and_reported() { files::encrypt_many(&refs(&sources), &dir.path().join("y.pqkf"), &protection).unwrap(); assert_eq!(report.files, 1); assert_eq!(report.skipped.len(), 1); - assert_eq!(report.skipped[0].path, "link"); + assert_eq!(report.skipped.get(0).unwrap().path().unwrap(), "link"); } #[test] diff --git a/tests/files_output.rs b/tests/files_output.rs index 550d227..80d23a1 100644 --- a/tests/files_output.rs +++ b/tests/files_output.rs @@ -112,8 +112,12 @@ fn permissions_and_skipped_entries() { assert_eq!((report.files, report.directories), (1, 1)); let mut reasons: Vec<_> = report .skipped - .iter() - .map(|s| (s.path.clone(), s.reason)) + .try_iter() + .unwrap() + .map(|s| { + let s = s.unwrap(); + (s.path().unwrap().to_owned(), s.reason().unwrap()) + }) .collect(); reasons.sort_by(|a, b| a.0.cmp(&b.0)); assert_eq!( diff --git a/tests/files_roundtrip.rs b/tests/files_roundtrip.rs index 5187502..28330e8 100644 --- a/tests/files_roundtrip.rs +++ b/tests/files_roundtrip.rs @@ -61,7 +61,7 @@ fn directory_with_passphrase() { let enc = dir.path().join("quelle.pqkf"); let report = files::encrypt(&src, &enc, &protection).unwrap(); assert_eq!((report.files, report.directories), (5, 4)); - assert_eq!(report.skipped, vec![]); + assert_eq!(report.skipped, files::SkippedEntries::default()); let out = dir.path().join("ziel"); let back = files::decrypt(&enc, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); From 8ca6fb77ead8a51a21fa40bde31a08fb6e9589af Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:56:40 +0100 Subject: [PATCH 19/26] Prelock actual Linux source directory traversal and sorting records MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Vorhandenes sicheres Rustix RawDir liest in gesperrten Caller-Puffer; konkrete Iteratoren/Records und Namens-/Permutations-/Cursor-Arenen vor Befüllung sperren. Keine gewöhnlichen Linux read_dir/DirEntry/PathBuf-Traversierungscontainer oder neue eigene unsafe-Grenze. EN: Source-bound16-command/906-source acceptance,107 file groups per feature configuration,69 integrations and actual denial/unwind/handle/depth checks pass; native acceptance and remaining joint R7/R8 scope stay open. --- docs/ROADMAP.md | 4 + docs/SPEC.en.md | 4 + docs/SPEC.md | 4 + docs/security/LINUX_DIRECTORY_VALIDATION.md | 65 +++++++ docs/security/SKIPPED_RECORD_VALIDATION.md | 5 +- src/files/mod.rs | 6 + src/files/native_directory.rs | 82 +++++++++ src/files/native_directory_tests.rs | 174 +++++++++++++++++++ src/files/native_names.rs | 182 ++++++++++++++++++++ src/files/native_names_sort.rs | 64 +++++++ src/files/native_names_tests.rs | 129 ++++++++++++++ src/files/native_path.rs | 29 ++++ src/files/native_path_tests.rs | 7 + src/files/walk.rs | 9 +- src/files/walk_linux.rs | 99 +++++++++++ src/files/walk_linux_tests.rs | 94 ++++++++++ 16 files changed, 955 insertions(+), 2 deletions(-) create mode 100644 docs/security/LINUX_DIRECTORY_VALIDATION.md create mode 100644 src/files/native_directory.rs create mode 100644 src/files/native_directory_tests.rs create mode 100644 src/files/native_names.rs create mode 100644 src/files/native_names_sort.rs create mode 100644 src/files/native_names_tests.rs create mode 100644 src/files/walk_linux.rs create mode 100644 src/files/walk_linux_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 3dcb057..3bb2d23 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -216,3 +216,7 @@ normal startup passed; integrierte/native Abnahme läuft / acceptance running. DE: R7/R8 weiterhin In progress in Draft355: native Quellmetadaten8ea8 und Linux-Startgatefc26 vollständig nativ geprüft. Ausdrücklich freigegebene reduzierte Windows-CI-Probed564 erfolgreich, keine vollständige Prozessgarantie. Nächster Teil schützt Skip-Records/UTF-Namenskonvertierung; komplette native Traversierung, Ziel-/Report-/Helper-/Host-Verträge bleiben offen. EN: Same joint PR, no partial Main merge or whole-issue closure; skipped-record source-bound/native acceptance pending. + + +DE: Draft355/R7/R8 In progress: Skip-Records bd8dfc5 mit allen25 Checks und vollständigen vier nativen Rust-Logs abgenommen. Linux-native Traversierung anschließend lokal implementiert; echte Namens-/Sortier-/Verweigerungs-/Kernel-/Handle-/Unwind- und Tiefengrenzfälle gezielt bestanden, integrierter Quellencheckpoint/nativ noch offen. +EN: No partial Main merge or overall R7/R8 closure; Windows traversal/output/report/helper/host contracts remain open. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 0b89cf6..c7e77af 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -595,3 +595,7 @@ Windows/host/helper acceptance remains open: security/LINUX_STARTUP_CAPABILITY.m EN: R8 skipped records use a prelocked arena, growth state and concrete iterator instead of Vec/String. path()/reason()/try_iter() are fallible borrow APIs; Skipped/Report Debug is redacted. Lossy OS-name conversion writes directly to locked output, including prelocked concrete Windows UTF16 iterator state. Scope and acceptance: security/SKIPPED_RECORD_VALIDATION.md. DE: Gesperrte Skip-Retention und explizite fallible Ausgabe; übrige R7/R8-Verträge bleiben erforderlich. + + +EN: Linux source traversal reuses rustix::RawDir with prelocked caller buffer, actual iterator/record, name/permutation/sort arenas and cursor. Its actual Linux path no longer uses ordinary read_dir/DirEntry/file_name/PathBuf traversal containers. Borrow native paths and retain bounded depth-first ordering/skip behavior. No new own unsafe boundary; Windows traversal and full source-race338 remain open. Acceptance: security/LINUX_DIRECTORY_VALIDATION.md. +DE: Echte Linux-Traversierung gesperrt; übrige Plattform-/Ziel-/Report-/Helper-/Host-Verträge weiterhin erforderlich. diff --git a/docs/SPEC.md b/docs/SPEC.md index d87d443..106e796 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -602,3 +602,7 @@ Windows-/Host-/Helper-Abnahme offen: security/LINUX_STARTUP_CAPABILITY.md. DE: R8-Skip-Records verwenden eine vor Befüllung gesperrte Arena samt Wachstum und konkretem Iterator statt Vec/String. path()/reason()/try_iter() sind fallible Borrow-APIs; Debug von Skipped/Report bleibt redigiert. Verlustbehaftete OS-Namen direkt gesperrt konvertieren, unter Windows auch den konkreten UTF16-Iterator vor Nutzung sperren. Aktuelle Grenzen und Abnahme: security/SKIPPED_RECORD_VALIDATION.md. EN: Protected skipped-record retention and explicit fallible disclosure; file/CLI compatibility and all remaining R7/R8 obligations remain required. + + +DE: Linux-Quelltraversierung verwendet vorhandenes rustix::RawDir mit vorab gesperrtem Caller-Puffer, tatsächlichem Iterator/Record, Namens-/Permutations-/Sortierarena und Cursor. Keine gewöhnlichen read_dir-/DirEntry-/file_name-/PathBuf-Traversierungscontainer in diesem Linux-Pfad. Borrowed native Pfade und bounded depth-first Rekursion erhalten Reihenfolge und Skip-Semantik. Keine eigene neue unsafe-Grenze; Windows-Traversierung und Quelle-Race338 bleiben offen. Abnahme: security/LINUX_DIRECTORY_VALIDATION.md. +EN: Actual Linux source traversal in protected storage; remaining platform, output/report/helper/host contracts remain required. diff --git a/docs/security/LINUX_DIRECTORY_VALIDATION.md b/docs/security/LINUX_DIRECTORY_VALIDATION.md new file mode 100644 index 0000000..2190b32 --- /dev/null +++ b/docs/security/LINUX_DIRECTORY_VALIDATION.md @@ -0,0 +1,65 @@ +# Protected Linux source traversal / Gesperrte Linux-Quelltraversierung + +DE: M1/M2/M3-Teil im gemeinsamen Draft355. Die tatsächlich benutzte Linux- +Traversierung liest nicht mehr über std::read_dir/DirEntry/file_name oder einen +gewöhnlichen PathBuf-/Vec-Stack. Vorhandenes rustix1.1.6 RawDir liest Kernel- +Records direkt in einen vorab gesperrten Caller-Puffer. Pufferdescriptor, konkreter +RawDir einschließlich FD/Offset/Geometrie und konkreter RawDirEntry werden jeweils +vor privater Befüllung gesperrt. Leere öffentliche Initialisierung ist fallibel; +keine nachträgliche Sperre bereits privater Daten, keine neue eigene unsafe-Stelle. +EN: Existing SecretWorkspace> avoids a large stack array without +casts or new FFI. Buffer capacity covers u16 d_reclen plus Rustix alignment; +actual errors propagate instead of silently truncating. Existing getdents64/ +openat sandbox rules stay unchanged. RawDir's inherited kernel/unsafe contract +is explicitly reviewed, not claimed to be newly unsafe-free transitively. + +DE: Native Blattnamen, Verzeichnisflags, Permutation, Wachstums-/Sortierzustand +und tatsächlicher Traversierungscursor in geschützten Arenen; feldweise fallible +Kopien zwischen gesperrten Zielen, alte Sammlung bei Fehler erhalten. Indizes +anstatt privater Record-Scratcharrays sortieren, gleiche Namen stabil. Native +Bytes einschließlich Nicht-UTF8 exakt erhalten. Pfade direkt gesperrt anfügen; +Unix-Path-Views nur ausleihen, keine OsString-/PathBuf-Kopie. Relative gültige +Namen und verlustbehaftete Skip-Namen über vorhandene ConfidentialText-Owner. +EN: Reuse the existing protected index-heapsort pattern with native byte keys. +Kernel dot entries are filtered. Inspect actual no-follow metadata, preserving +file/directory/symlink/special classification. Process all direct children before +alphabetical depth-first recursion, then globally sort source records as before. +Existing portable length/depth/entry bounds remain. Recursion owns protected +collections, with no ordinary collection of private traversal records. + +DE: Native Verzeichnisöffnung verweigert Symlink-Blätter mit O_NOFOLLOW. Das +ist kein vollständiger Quelle-Race338-Abschluss: Vorfahren-/Leaf-Bindung und der +spätere Datei-Open müssen weiterhin gemeinsam abgesichert werden. Windows +verwendet noch den bisherigen Walker und braucht einen eigenen verifizierten +SDK-Pfad. Private CLI-Argument-/Ziel-/Report-/Transport- und Helper-/Hostverträge +sind nicht durch diese Linux-Teilbehebung geschlossen. +EN: OS filesystem namespace and compiler/register/temporary scalar borrows are +explicit boundaries. No private std internal buffer is relabelled caller-owned. +No public wire/JSON schema, package dependency, privilege or host policy changes. + +## Actual tests / Tatsächliche Tests + +DE: Tatsächliche Kernel-Namen gegen öffentliche std-Fixtures vergleichen; +lebende Puffer-/Owner-/Iterator-/Record-Sperren einschließlich Kernel-smaps. +65-Namen-Grenzen, Byte-/stabile Gleichnamensortierung, Verzeichnisflags, rewind, +NUL-/Slash-Verweigerung und Wiederverwendung. Echte eigene begrenzte Kinder: +Consumer-Fehler, Panic/Unwind, reale Namensarena-Verweigerung nach erstem +übernommenen Kernel-Eintrag, Verweigerung vor Ingress und partielle Wachstumskopie. +Registry-Seiten, Kernel-VmLck und eigene FD-Zahl nach Drop exakt Baseline; +Elternlimit unverändert. Keine Verweigerung nur aus einem Budgetwert ableiten: +kleine neue Owner dürfen bereits gesperrte Seiten teilen, ohne einen neuen +Kernel-Lock zu brauchen. Ursprüngliche fehlgeschlagene Testannahme bleibt erhalten. +EN: The corrected test requires actual MemoryLock, an already retained first +entry and complete cleanup. Actual file/directory/dangling-link/FIFO/non-UTF8/ +invalid-name tree, original skip order and maximum64-component boundary pass. +NUL directory inputs preserve Io(InvalidInput), not an undocumented API change. +Source-bound linux-directory-v1:16 commands and906 unchanged Rust/manifest +hashes pass; four strict root/two platform lints,107 file groups per feature +configuration and69 selected integration cases. All actual own-child calls +execute through their parents;14 explicit child/race entries remain ignored. +Root/platform fmt, limits, vendor/matrix and diff pass. Native acceptance pending. + +Sources / Quellen: +- Existing pinned rustix1.1.6 src/fs/raw_dir.rs and backend getdents implementation. +- Existing pinned zeroize1.9.2 MaybeUninit/slice volatile zeroization. +- https://man7.org/linux/man-pages/man2/getdents.2.html diff --git a/docs/security/SKIPPED_RECORD_VALIDATION.md b/docs/security/SKIPPED_RECORD_VALIDATION.md index e9e68b7..2f92757 100644 --- a/docs/security/SKIPPED_RECORD_VALIDATION.md +++ b/docs/security/SKIPPED_RECORD_VALIDATION.md @@ -43,6 +43,9 @@ EN: Public std oracles cover every byte, malformed/truncated UTF8, deterministic mixed byte sequences, all unpaired UTF16 surrogate units and actual pairs. Source-bound skipped-records-v1:16 commands and899 unchanged Rust/manifest hashes pass. Four strict root and two platform lints;97 file groups per feature config, -69 actual selected integration cases. Native acceptance remains pending; no new unsafe or +69 actual selected integration cases. Nativebd8dfc5 full logs pass: Linux22/ARM978 tests each, latest1877, +Windows1696. Actual physical owner/arena/cursor/pending-surrogate and every +unpaired-surrogate oracle execute. All25 checks pass, including8 fuzz targets +and own reduced Windows access probe. No new unsafe or package dependency. Mandatory root-forbid, authentication-before-output, resource limits and previous accepted provider behavior stay intact. diff --git a/src/files/mod.rs b/src/files/mod.rs index 1b35108..c38dd19 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -34,6 +34,10 @@ mod list; mod locked_owner_tests; #[cfg(windows)] mod locked_wide; +#[cfg(target_os = "linux")] +mod native_directory; +#[cfg(target_os = "linux")] +mod native_names; mod native_path; mod original; mod output; @@ -61,6 +65,8 @@ mod tail_v4; mod tail_v4_drain; mod unicode_fold; mod walk; +#[cfg(target_os = "linux")] +mod walk_linux; use std::io::BufReader; use std::path::Path; diff --git a/src/files/native_directory.rs b/src/files/native_directory.rs new file mode 100644 index 0000000..01d1669 --- /dev/null +++ b/src/files/native_directory.rs @@ -0,0 +1,82 @@ +//! DE: Linux-Verzeichnisdaten direkt in vorab gesperrten Caller-Puffer lesen. +//! EN: Read Linux directory data directly into prelocked caller-owned storage. +use super::native_path::NativePath; +use crate::{ + Error, Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, +}; +use rustix::{ + fd::OwnedFd, + fs::{CWD, Mode, OFlags, RawDir, RawDirEntry, openat}, +}; +use std::{ffi::CStr, mem::MaybeUninit}; +use zeroize::ZeroizeOnDrop; + +// DE: Höchstens u16-Recordlänge plus Rustix-Ausrichtung; nur öffentliche Initialisierung. +// EN: At most a u16 record length plus Rustix alignment; public initialization only. +const STORAGE: usize = 65_536 + align_of::() - 1; +impl ZeroizeOnDrop for crate::crypto::secret_buffer::SecretBuffer> {} + +struct Reader<'a>(Option>); +impl Drop for Reader<'_> { + fn drop(&mut self) { + self.0 = None; + } +} +impl ZeroizeOnDrop for Reader<'_> {} + +struct Entry<'a>(Option>); +impl Drop for Entry<'_> { + fn drop(&mut self) { + self.0 = None; + } +} +impl ZeroizeOnDrop for Entry<'_> {} + +pub(super) fn visit(path: &NativePath, mut consume: impl FnMut(&CStr) -> Result<()>) -> Result<()> { + let mut storage = SecretWorkspace::with_capacity(STORAGE)?; + for _ in 0..STORAGE { + storage.push_preallocated(MaybeUninit::new(0))?; + } + #[cfg(test)] + tests::storage(&storage); + let mut reader = SecretState::new(Reader(None))?; + let fd = openat( + CWD, + path.c_str()?, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW, + Mode::empty(), + ) + .map_err(std::io::Error::from)?; + // DE: Konkreter Iterator samt FD/Puffergeometrie vor erster Ausgabe gesperrt. + // EN: Concrete iterator, including FD/buffer geometry, locked before first output. + reader.get_mut().0 = Some(RawDir::new(fd, storage.expose_mut())); + loop { + // DE: Auch den konkreten RawDirEntry vor privater Befüllung sperren. + // EN: Prelock the actual RawDirEntry before its private population too. + #[cfg(test)] + tests::reader(&reader); + let mut entry = SecretState::new(Entry(None))?; + entry.get_mut().0 = reader + .get_mut() + .0 + .as_mut() + .ok_or(Error::Crypto)? + .next() + .transpose() + .map_err(std::io::Error::from)?; + #[cfg(test)] + tests::entry(&entry); + let Some(entry) = &entry.get().0 else { + return Ok(()); + }; + let name = entry.file_name(); + if name != c"." && name != c".." { + consume(name)?; + } + } +} + +#[cfg(test)] +#[path = "native_directory_tests.rs"] +mod tests; diff --git a/src/files/native_directory_tests.rs b/src/files/native_directory_tests.rs new file mode 100644 index 0000000..b673e4b --- /dev/null +++ b/src/files/native_directory_tests.rs @@ -0,0 +1,174 @@ +//! DE: Echte Kernel-Ausgabe, gesperrte Retention und begrenzte Fehler-/Unwindkinder. +//! EN: Actual kernel output, protected retention and bounded error/unwind children. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::{hardening::memlock, locked_owner_test_support::locked}; + +pub(super) fn storage(storage: &SecretWorkspace>) { + storage.assert_metadata_locked(); + locked(storage.expose()); +} +pub(super) fn reader(reader: &SecretState>) { + locked(reader.get()); +} +pub(super) fn entry(entry: &SecretState>) { + locked(entry.get()); + if let Some(entry) = &entry.get().0 { + locked(entry.file_name().to_bytes_with_nul()); + } +} + +#[test] +fn actual_kernel_names_match_std_without_dot_entries_or_lossy_conversion() { + use std::{ffi::OsStr, os::unix::ffi::OsStrExt}; + let root = tempfile::tempdir().unwrap(); + for name in [&b"plain"[..], "ä😀".as_bytes(), &b"bad\xff"[..]] { + std::fs::write(root.path().join(OsStr::from_bytes(name)), b"public fixture").unwrap(); + } + let mut expected: Vec<_> = std::fs::read_dir(root.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().as_bytes().to_vec()) + .collect(); + let path = NativePath::from_path(root.path()).unwrap(); + let mut observed = Vec::new(); + visit(&path, |name| { + locked(name.to_bytes_with_nul()); + observed.push(name.to_bytes().to_vec()); + Ok(()) + }) + .unwrap(); + expected.sort(); + observed.sort(); + let equal = expected == observed; + assert!(equal); +} + +fn kernel_locked_bytes() -> usize { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024 +} +fn own_fd_count() -> usize { + std::fs::read_dir("/proc/self/fd").unwrap().count() +} + +#[test] +fn actual_directory_failure_unwind_and_mid_read_denial_run_in_owned_child() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::native_directory::tests::directory_failure_child", + "PQKEEP_DIRECTORY_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn directory_failure_child() { + assert_eq!(std::env::var("PQKEEP_DIRECTORY_CHILD").unwrap(), "1"); + let root = tempfile::tempdir().unwrap(); + for index in 0..1000 { + std::fs::write( + root.path().join(format!("public-{index:04}")), + b"public fixture", + ) + .unwrap(); + } + let path = NativePath::from_path(root.path()).unwrap(); + let baseline = snapshot(); + assert!(matches!( + visit(&path, |_| Err(Error::Crypto)), + Err(Error::Crypto) + )); + assert_eq!(snapshot(), baseline); + let result = std::panic::catch_unwind(|| { + let _ = visit(&path, |_| std::panic::resume_unwind(Box::new(()))); + }); + assert!(result.is_err()); + assert_eq!(snapshot(), baseline); + mid_read_denial(&path); + assert_eq!(snapshot(), baseline); + let mut called = false; + assert!(matches!( + visit(&path, |_| { + called = true; + Ok(()) + }), + Err(Error::MemoryLock) + )); + assert!(!called); + assert_eq!(snapshot(), baseline); +} + +fn mid_read_denial(path: &NativePath) { + use rustix::process::{Resource, getrlimit, setrlimit}; + let mut names = super::super::native_names::NativeNames::prepare().unwrap(); + let mut count = 0; + let result = visit(path, |name| { + count += 1; + names.push(name.to_bytes())?; + if count == 1 { + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + } + Ok(()) + }); + assert!(matches!(result, Err(Error::MemoryLock))); + assert!(count > 1 && count < 1000); + names.rewind(); + names.current().unwrap().unwrap().assert_owner_locked(); +} + +#[test] +fn real_missing_directory_and_regular_file_are_errors_not_empty_success() { + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("file"); + std::fs::write(&file, b"public fixture").unwrap(); + for path in [&file, &root.path().join("missing")] { + let mut called = false; + let native = NativePath::from_path(path).unwrap(); + assert!( + visit(&native, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } +} + +fn snapshot() -> (usize, usize, usize) { + ( + memlock::stats().locked_pages, + kernel_locked_bytes(), + own_fd_count(), + ) +} + +#[test] +fn native_directory_open_refuses_a_symlink_leaf() { + let root = tempfile::tempdir().unwrap(); + let link = root.path().join("link"); + std::os::unix::fs::symlink(root.path(), &link).unwrap(); + let native = NativePath::from_path(&link).unwrap(); + let mut called = false; + assert!( + visit(&native, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); +} diff --git a/src/files/native_names.rs b/src/files/native_names.rs new file mode 100644 index 0000000..d3aa433 --- /dev/null +++ b/src/files/native_names.rs @@ -0,0 +1,182 @@ +//! DE: Native Verzeichnisnamen und Traversierungszustand in gesperrten Arenen. +//! EN: Native directory names and traversal state in protected arenas. +use super::{native_path::NativePath, paths::MAX_ENTRIES}; +use crate::{ + Error, Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct Name { + path: Option, + directory: bool, +} +impl Zeroize for Name { + fn zeroize(&mut self) { + self.path = None; + self.directory.zeroize(); + } +} +impl Drop for Name { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for Name {} +impl ZeroizeOnDrop for crate::crypto::secret_buffer::SecretBuffer {} + +#[derive(Default)] +struct Sort { + start: usize, + end: usize, + root: usize, + child: usize, +} +impl Zeroize for Sort { + fn zeroize(&mut self) { + self.start.zeroize(); + self.end.zeroize(); + self.root.zeroize(); + self.child.zeroize(); + } +} +struct State { + records: SecretWorkspace, + order: SecretWorkspace, + used: usize, + scan: usize, + position: usize, + sort: Sort, +} +impl Drop for State { + fn drop(&mut self) { + self.records.zeroize(); + self.order.zeroize(); + self.used.zeroize(); + self.scan.zeroize(); + self.position.zeroize(); + self.sort.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +pub(super) struct NativeNames(SecretState); +#[path = "native_names_sort.rs"] +mod sorting; + +impl NativeNames { + pub(super) fn prepare() -> Result { + Ok(Self(SecretState::new(State { + records: SecretWorkspace::zeroed(0)?, + order: SecretWorkspace::zeroed(0)?, + used: 0, + scan: 0, + position: 0, + sort: Sort::default(), + })?)) + } + pub(super) fn push(&mut self, bytes: &[u8]) -> Result<()> { + if bytes.is_empty() || bytes.contains(&b'/') { + return Err(Error::InvalidInput { field: "path" }); + } + let state = self.0.get_mut(); + state.reserve()?; + state.records.expose_mut()[state.used].path = Some(NativePath::from_native(bytes)?); + state.order.expose_mut()[state.used] = state.used; + state.used += 1; + Ok(()) + } + pub(super) fn current(&self) -> Result> { + let state = self.0.get(); + if state.position == state.used { + return Ok(None); + } + state.name(state.position).map(Some) + } + pub(super) fn advance(&mut self) -> Result<()> { + let state = self.0.get_mut(); + if state.position >= state.used { + return Err(Error::Crypto); + } + state.position += 1; + Ok(()) + } + pub(super) fn rewind(&mut self) { + self.0.get_mut().position = 0; + } + pub(super) fn directory(&self) -> Result { + let state = self.0.get(); + Ok(state.record(state.position)?.directory) + } + pub(super) fn set_directory(&mut self) -> Result<()> { + let state = self.0.get_mut(); + let index = state.index(state.position)?; + state + .records + .expose_mut() + .get_mut(index) + .ok_or(Error::Crypto)? + .directory = true; + Ok(()) + } +} +impl State { + fn index(&self, position: usize) -> Result { + if position >= self.used { + return Err(Error::Crypto); + } + let index = *self.order.expose().get(position).ok_or(Error::Crypto)?; + if index >= self.used { + return Err(Error::Crypto); + } + Ok(index) + } + fn record(&self, position: usize) -> Result<&Name> { + self.records + .expose() + .get(self.index(position)?) + .ok_or(Error::Crypto) + } + fn name(&self, position: usize) -> Result<&NativePath> { + self.record(position)?.path.as_ref().ok_or(Error::Crypto) + } + fn reserve(&mut self) -> Result<()> { + let limit = usize::try_from(MAX_ENTRIES).map_err(|_| Error::MemoryLock)?; + if self.used >= limit { + return Err(Error::InvalidInput { field: "entries" }); + } + if self.used < self.records.expose().len() { + return Ok(()); + } + let capacity = self + .used + .checked_mul(2) + .ok_or(Error::MemoryLock)? + .max(16) + .min(limit); + let mut records = SecretWorkspace::::zeroed(capacity)?; + let mut order = SecretWorkspace::::zeroed(capacity)?; + self.scan = 0; + while self.scan < self.used { + records.expose_mut()[self.scan].path = Some( + self.records.expose()[self.scan] + .path + .as_ref() + .ok_or(Error::Crypto)? + .try_duplicate()?, + ); + records.expose_mut()[self.scan].directory = self.records.expose()[self.scan].directory; + order.expose_mut()[self.scan] = self.order.expose()[self.scan]; + self.scan += 1; + } + self.records = records; + self.order = order; + self.scan = 0; + Ok(()) + } +} + +#[cfg(test)] +#[path = "native_names_tests.rs"] +mod tests; diff --git a/src/files/native_names_sort.rs b/src/files/native_names_sort.rs new file mode 100644 index 0000000..b8a76ed --- /dev/null +++ b/src/files/native_names_sort.rs @@ -0,0 +1,64 @@ +//! DE: Nur gesperrte skalare Indizes tauschen; keine Record- oder Sortier-Scratchkopie. +//! EN: Swap locked scalar indices only; no record or sorting scratch copy. +use super::{NativeNames, Result, State}; +use std::cmp::Ordering; + +impl NativeNames { + pub(crate) fn sort(&mut self) -> Result<()> { + let state = self.0.get_mut(); + state.sort.start = state.used / 2; + state.sort.end = state.used; + while state.sort.start > 0 { + state.sort.start -= 1; + state.sort.root = state.sort.start; + state.sift()?; + } + while state.sort.end > 1 { + state.sort.end -= 1; + state.order.expose_mut().swap(0, state.sort.end); + state.sort.root = 0; + state.sift()?; + } + state.sort.zeroize(); + Ok(()) + } +} + +use zeroize::Zeroize; +impl State { + fn compare(&self, a: usize, b: usize) -> Result { + // DE: Originalindex erhält auch bei gleichen Pfaden die bisherige stabile Reihenfolge. + // EN: Original indices retain the previous stable order even for equal paths. + Ok(self + .name(a)? + .encoded()? + .cmp(self.name(b)?.encoded()?) + .then(self.order.expose()[a].cmp(&self.order.expose()[b]))) + } + + fn sift(&mut self) -> Result<()> { + loop { + self.sort.child = self + .sort + .root + .checked_mul(2) + .and_then(|n| n.checked_add(1)) + .ok_or(crate::Error::MemoryLock)?; + if self.sort.child >= self.sort.end { + return Ok(()); + } + if self.sort.child + 1 < self.sort.end + && self.compare(self.sort.child, self.sort.child + 1)? == Ordering::Less + { + self.sort.child += 1; + } + if self.compare(self.sort.root, self.sort.child)? != Ordering::Less { + return Ok(()); + } + self.order + .expose_mut() + .swap(self.sort.root, self.sort.child); + self.sort.root = self.sort.child; + } + } +} diff --git a/src/files/native_names_tests.rs b/src/files/native_names_tests.rs new file mode 100644 index 0000000..8503533 --- /dev/null +++ b/src/files/native_names_tests.rs @@ -0,0 +1,129 @@ +//! DE: Native Sortierreihenfolge, geschützte Arenen und tatsächliche Wachstumsfehler. +//! EN: Native ordering, protected arenas and actual growth failures. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::locked_owner_test_support::locked; + +fn owners(names: &NativeNames) { + let state = names.0.get(); + locked(state); + state.records.assert_metadata_locked(); + state.order.assert_metadata_locked(); + locked(state.records.expose()); + locked(state.order.expose()); + for record in &state.records.expose()[..state.used] { + record.path.as_ref().unwrap().assert_owner_locked(); + } +} + +#[test] +fn native_byte_order_and_directory_flags_survive_growth_sort_and_rewind() { + for length in [0, 1, 2, 3, 16, 17, 31, 32, 65] { + let mut names = NativeNames::prepare().unwrap(); + let mut expected = Vec::new(); + for index in (0..length).rev() { + let bytes = [format!("name-{}", index % 5).as_bytes(), &[255 - index]].concat(); + names.push(&bytes).unwrap(); + if index % 2 == 0 { + names.set_directory().unwrap(); + } + names.advance().unwrap(); + expected.push((bytes, index % 2 == 0)); + } + names.rewind(); + names.sort().unwrap(); + owners(&names); + expected.sort_by(|a, b| a.0.cmp(&b.0)); + for (bytes, directory) in expected { + let name = names.current().unwrap().unwrap(); + let equal = name.c_str().unwrap().to_bytes() == bytes; + assert!(equal); + assert_eq!(names.directory().unwrap(), directory); + names.advance().unwrap(); + } + assert!(names.current().unwrap().is_none()); + assert!(names.advance().is_err()); + names.rewind(); + assert_eq!(names.current().unwrap().is_some(), length != 0); + } +} + +#[test] +fn equal_names_keep_original_stable_order_and_rejected_bytes_leave_old_slots_valid() { + let mut names = NativeNames::prepare().unwrap(); + for directory in [true, false, true] { + names.push(b"same").unwrap(); + if directory { + names.set_directory().unwrap(); + } + names.advance().unwrap(); + } + for invalid in [&b""[..], &b"bad/name"[..], &b"bad\0name"[..]] { + assert!(names.push(invalid).is_err()); + } + assert_eq!(names.0.get().used, 3); + names.rewind(); + names.sort().unwrap(); + for expected in [true, false, true] { + assert_eq!(names.directory().unwrap(), expected); + names.advance().unwrap(); + } + owners(&names); +} + +#[test] +fn actual_partial_name_growth_denial_runs_in_owned_child() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::native_names::tests::partial_growth_child", + "PQKEEP_NATIVE_NAMES_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +fn kernel_locked_bytes() -> usize { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024 +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn partial_growth_child() { + use crate::hardening::memlock; + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_NATIVE_NAMES_CHILD").unwrap(), "1"); + let baseline = (memlock::stats().locked_pages, kernel_locked_bytes()); + let mut names = NativeNames::prepare().unwrap(); + let page = region::page::size(); + let bytes = vec![b'x'; 2 * page]; + for _ in 0..16 { + names.push(&bytes).unwrap(); + } + let live = (memlock::stats().locked_pages, kernel_locked_bytes()); + let budget = u64::try_from(kernel_locked_bytes().checked_add(12 * page).unwrap()).unwrap(); + let mut limit = getrlimit(Resource::Memlock); + assert!(limit.current.is_none_or(|original| budget < original)); + limit.current = Some(budget); + setrlimit(Resource::Memlock, limit).unwrap(); + assert!(matches!(names.push(&bytes), Err(Error::MemoryLock))); + let state = names.0.get(); + assert_eq!(state.used, 16); + assert!(state.scan > 0 && state.scan < state.used); + owners(&names); + assert_eq!((memlock::stats().locked_pages, kernel_locked_bytes()), live); + drop(names); + assert_eq!( + (memlock::stats().locked_pages, kernel_locked_bytes()), + baseline + ); +} diff --git a/src/files/native_path.rs b/src/files/native_path.rs index c645286..97a89cc 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -112,6 +112,35 @@ impl NativePath { Ok(()) } + #[cfg(target_os = "linux")] + pub(super) fn as_path(&self) -> Result<&Path> { + use std::os::unix::ffi::OsStrExt; + Ok(Path::new(std::ffi::OsStr::from_bytes( + self.c_str()?.to_bytes(), + ))) + } + + #[cfg(target_os = "linux")] + pub(super) fn joined(parent: &Self, leaf: &Self) -> Result { + let base = parent.c_str()?.to_bytes(); + let name = leaf.c_str()?.to_bytes(); + if name.is_empty() || name.contains(&b'/') { + return Err(Error::InvalidInput { field: "path" }); + } + let separator = usize::from(!base.is_empty() && !base.ends_with(b"/")); + let head = base.len().checked_add(separator).ok_or(Error::MemoryLock)?; + let len = head.checked_add(name.len()).ok_or(Error::MemoryLock)?; + let mut out = Self::prepare()?; + out.allocate(len)?; + let units = out.0.get_mut().0.expose_mut(); + units[..base.len()].copy_from_slice(base); + if separator != 0 { + units[base.len()] = b'/'; + } + units[head..len].copy_from_slice(name); + Ok(out) + } + pub(super) fn try_duplicate(&self) -> Result { let units = self.encoded()?; Self::from_native(&units[..units.len() - 1]) diff --git a/src/files/native_path_tests.rs b/src/files/native_path_tests.rs index 1759a04..e2fcc36 100644 --- a/src/files/native_path_tests.rs +++ b/src/files/native_path_tests.rs @@ -33,6 +33,13 @@ fn assert_owner(path: &NativePath) { } } +#[cfg(target_os = "linux")] +impl NativePath { + pub(crate) fn assert_owner_locked(&self) { + assert_owner(self); + } +} + #[test] fn native_open_preserves_the_std_invalid_nul_error_class() { assert!(matches!( diff --git a/src/files/walk.rs b/src/files/walk.rs index e7520c5..dc928a6 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -6,8 +6,13 @@ //! reproducible). Symlinks are never followed. Symlinks, devices/pipes, names //! without valid UTF-8 and non-portable names are skipped and reported. +#[cfg(target_os = "linux")] +use super::walk_linux::collect_tree; +#[cfg(not(target_os = "linux"))] use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; +#[cfg(not(target_os = "linux"))] +use std::path::PathBuf; use super::paths::{self, MAX_ENTRIES}; use super::source_entries::SourceEntries; @@ -117,6 +122,7 @@ pub(crate) fn collect_under( } /// DE: Inhalt von `root` mit Präfix `base` anhängen. EN: Append the content of `root` with prefix `base`. +#[cfg(not(target_os = "linux"))] fn collect_tree( root: &Path, base: &str, @@ -144,6 +150,7 @@ fn collect_tree( Ok(()) } +#[cfg(not(target_os = "linux"))] fn visit( child: &fs::DirEntry, prefix: &str, diff --git a/src/files/walk_linux.rs b/src/files/walk_linux.rs new file mode 100644 index 0000000..abed6e9 --- /dev/null +++ b/src/files/walk_linux.rs @@ -0,0 +1,99 @@ +//! DE: Verzeichnisnamen, Sortierung und Rekursionsrecords ohne gewöhnliche FS-Puffer. +//! EN: Directory names, sorting and recursion records without ordinary FS buffers. +use super::{ + ConfidentialText, SkipReason, SkippedEntries, confidential_os_text, native_directory, + native_names::NativeNames, native_path::NativePath, paths, source_entries::SourceEntries, + source_metadata::Metadata, +}; +use crate::{Error, Result}; +use std::{ffi::OsStr, os::unix::ffi::OsStrExt, path::Path}; + +pub(super) fn collect_tree( + root: &Path, + prefix: &str, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result<()> { + let root = NativePath::from_path(root).map_err(|error| match error { + Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), + other => other, + })?; + let prefix = ConfidentialText::from_text(prefix)?; + collect_native(&root, &prefix, entries, skipped) +} + +fn collect_native( + root: &NativePath, + prefix: &ConfidentialText, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result<()> { + if !Metadata::read(root.as_path()?)?.is_dir() { + return Err(Error::InvalidInput { field: "source" }); + } + let mut names = NativeNames::prepare()?; + native_directory::visit(root, |name| names.push(name.to_bytes()))?; + names.sort()?; + while let Some(name) = names.current()? { + if visit(root, prefix.expose()?, name, entries, skipped)? { + names.set_directory()?; + } + names.advance()?; + } + // DE: Wie bisher erst alle direkten Kinder, danach Verzeichnisse alphabetisch. + // EN: Preserve direct-child processing followed by alphabetical directory descent. + names.rewind(); + while let Some(name) = names.current()? { + if names.directory()? { + let child = NativePath::joined(root, name)?; + let name = name.c_str()?.to_str().map_err(|_| Error::Crypto)?; + let relative = ConfidentialText::joined(prefix.expose()?, name)?; + let child_prefix = ConfidentialText::joined(relative.expose()?, "/")?; + collect_native(&child, &child_prefix, entries, skipped)?; + } + names.advance()?; + } + Ok(()) +} + +fn visit( + root: &NativePath, + prefix: &str, + name: &NativePath, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result { + let bytes = name.c_str()?.to_bytes(); + let Ok(name_text) = std::str::from_utf8(bytes) else { + skipped.push( + confidential_os_text::joined_lossy(prefix, OsStr::from_bytes(bytes))?, + SkipReason::NonUtf8Name, + )?; + return Ok(false); + }; + let relative = ConfidentialText::joined(prefix, name_text)?; + if paths::validate_only(relative.expose()?).is_err() { + skipped.push(relative, SkipReason::InvalidName)?; + return Ok(false); + } + let absolute = NativePath::joined(root, name)?; + let kind = Metadata::read(absolute.as_path()?)?; + if kind.is_symlink() { + skipped.push(relative, SkipReason::Symlink)?; + } else if kind.is_dir() || kind.is_file() { + entries.push( + relative.expose()?, + absolute.as_path()?, + kind.is_dir(), + if kind.is_file() { kind.bytes() } else { 0 }, + )?; + return Ok(kind.is_dir()); + } else { + skipped.push(relative, SkipReason::Special)?; + } + Ok(false) +} + +#[cfg(test)] +#[path = "walk_linux_tests.rs"] +mod tests; diff --git a/src/files/walk_linux_tests.rs b/src/files/walk_linux_tests.rs new file mode 100644 index 0000000..4d52cc3 --- /dev/null +++ b/src/files/walk_linux_tests.rs @@ -0,0 +1,94 @@ +//! DE: Echte Bäume, Sortier-/Skip-Vertrag und maximale erlaubte Rekursion. +//! EN: Actual trees, sorting/skip contract and maximum permitted recursion. +#![allow(clippy::unwrap_used)] +use super::*; +use std::{ + ffi::OsStr, + os::unix::{ffi::OsStrExt, fs::symlink}, +}; + +fn fixture(root: &Path) { + for name in ["a-dir", "z-dir"] { + std::fs::create_dir(root.join(name)).unwrap(); + std::fs::write(root.join(name).join("file"), b"public fixture").unwrap(); + } + for name in ["m.txt", "CON", "a-dir/CON", "z-dir/space "] { + std::fs::write(root.join(name), b"public fixture").unwrap(); + } + std::fs::write(root.join(OsStr::from_bytes(b"bad\xff")), b"public fixture").unwrap(); + symlink(root.join("missing"), root.join("link")).unwrap(); + rustix::fs::mknodat( + rustix::fs::CWD, + root.join("pipe"), + rustix::fs::FileType::Fifo, + rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR, + 0, + ) + .unwrap(); +} + +#[test] +fn actual_tree_keeps_global_entry_sort_and_prior_depth_first_skip_order() { + let root = tempfile::tempdir().unwrap(); + fixture(root.path()); + let (entries, skipped) = super::super::walk::collect_dir(root.path()).unwrap(); + let expected = ["a-dir", "a-dir/file", "m.txt", "z-dir", "z-dir/file"]; + assert_eq!(entries.len(), expected.len()); + for (entry, expected) in entries.try_iter().unwrap().zip(expected) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == expected; + assert!(equal); + assert_eq!( + entry.is_directory(), + !expected.contains('/') && expected.ends_with("-dir") + ); + assert_eq!(entry.size(), if entry.is_directory() { 0 } else { 14 }); + } + let expected = [ + ("CON", SkipReason::InvalidName), + ("bad�", SkipReason::NonUtf8Name), + ("link", SkipReason::Symlink), + ("pipe", SkipReason::Special), + ("a-dir/CON", SkipReason::InvalidName), + ("z-dir/space ", SkipReason::InvalidName), + ]; + assert_eq!(skipped.len(), expected.len()); + for (entry, (path, reason)) in skipped.try_iter().unwrap().zip(expected) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == path; + assert!(equal); + assert_eq!(entry.reason().unwrap(), reason); + } +} + +#[test] +fn maximum_depth_is_reached_without_following_or_descending_into_invalid_children() { + let root = tempfile::tempdir().unwrap(); + let mut directory = root.path().to_path_buf(); + for depth in 1..=paths::MAX_DEPTH + 1 { + directory.push("d"); + std::fs::create_dir(&directory).unwrap(); + if depth == paths::MAX_DEPTH - 1 { + std::fs::write(directory.join("file"), b"public fixture").unwrap(); + } + } + std::fs::write(directory.join("must-not-be-visited"), b"public fixture").unwrap(); + let (entries, skipped) = super::super::walk::collect_dir(root.path()).unwrap(); + assert_eq!(entries.len(), paths::MAX_DEPTH + 1); + assert_eq!(skipped.len(), 1); + let rejected = vec!["d"; paths::MAX_DEPTH + 1].join("/"); + let equal = skipped.get(0).unwrap().path().unwrap() == rejected; + assert!(equal); + assert_eq!( + skipped.get(0).unwrap().reason().unwrap(), + SkipReason::InvalidName + ); +} + +#[test] +fn source_directory_nul_keeps_the_existing_native_io_error_class() { + assert!(matches!( + super::super::walk::collect_dir(Path::new("public\0fixture")), + Err(Error::Io(std::io::ErrorKind::InvalidInput)) + )); +} From aae9a0696203b13325ed332bc7c266a8f884c02a Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:44:44 +0100 Subject: [PATCH 20/26] Add a protected synchronous NT directory caller and native fixtures DE: Privaten synchronen Handle und echte SDK-/Caller-Ausgabe vor NT-Verzeichnisabfrage sperren; geoeffneten Handle pruefen und Fehlerzustaende strikt sperren. Vorhandenen geschuetzten Metadaten-Query wiederverwenden, keine Root-unsafe-Grenze. EN: Four necessary platform FFI blocks plus read-only optional own-handle fixture;14 commands/908 exact source hashes pass. Native fixtures pending; production Windows traversal and joint R7/R8 remain open. --- docs/ROADMAP.md | 4 + docs/SPEC.en.md | 4 + docs/SPEC.md | 4 + docs/security/LINUX_DIRECTORY_VALIDATION.md | 4 +- .../WINDOWS_DIRECTORY_CALLER_VALIDATION.md | 77 +++++ platform/pqkeep-platform/Cargo.toml | 2 +- .../pqkeep-platform/src/directory_windows.rs | 184 ++++++++++++ platform/pqkeep-platform/src/lib.rs | 5 + .../pqkeep-platform/src/memory_fixture.rs | 17 +- .../src/source_metadata_windows.rs | 9 +- src/crypto/secret_buffer.rs | 1 + src/crypto/secret_workspace_tests.rs | 1 + src/files/mod.rs | 4 + src/files/windows_directory_adapter_tests.rs | 262 ++++++++++++++++++ 14 files changed, 574 insertions(+), 4 deletions(-) create mode 100644 docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md create mode 100644 platform/pqkeep-platform/src/directory_windows.rs create mode 100644 src/files/windows_directory_adapter_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 3bb2d23..f973236 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -220,3 +220,7 @@ EN: Same joint PR, no partial Main merge or whole-issue closure; skipped-record DE: Draft355/R7/R8 In progress: Skip-Records bd8dfc5 mit allen25 Checks und vollständigen vier nativen Rust-Logs abgenommen. Linux-native Traversierung anschließend lokal implementiert; echte Namens-/Sortier-/Verweigerungs-/Kernel-/Handle-/Unwind- und Tiefengrenzfälle gezielt bestanden, integrierter Quellencheckpoint/nativ noch offen. EN: No partial Main merge or overall R7/R8 closure; Windows traversal/output/report/helper/host contracts remain open. + + +DE: R7/R8 weiter In progress in genau Draft355. Linux-Traversierung8ca6fb7 lokal vollständig geprüft und veröffentlicht, native Gesamtabnahme läuft. Windows-NT-Caller/echte gesperrte SDK-Fixtures lokal in Prüfung; keine vorgezogene Windows-Walker-/Helper-/Host-Abnahme. +EN: Same joint PR, no partial Main merge or scope closure. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index c7e77af..d47a479 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -599,3 +599,7 @@ DE: Gesperrte Skip-Retention und explizite fallible Ausgabe; übrige R7/R8-Vertr EN: Linux source traversal reuses rustix::RawDir with prelocked caller buffer, actual iterator/record, name/permutation/sort arenas and cursor. Its actual Linux path no longer uses ordinary read_dir/DirEntry/file_name/PathBuf traversal containers. Borrow native paths and retain bounded depth-first ordering/skip behavior. No new own unsafe boundary; Windows traversal and full source-race338 remain open. Acceptance: security/LINUX_DIRECTORY_VALIDATION.md. DE: Echte Linux-Traversierung gesperrt; übrige Plattform-/Ziel-/Report-/Helper-/Host-Verträge weiterhin erforderlich. + + +EN: A direct synchronous NT directory caller with prelocked actual SDK status/output storage is under verification for upcoming Windows source traversal. Private handle construction rejects foreign/asynchronous handles; partial responses/overflow never mean EOF. Production walker remains unmigrated; no overall closure. Scope: security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md. +DE: Native Fixtures und vollständige Windows-Produktionscaller noch abnehmen. diff --git a/docs/SPEC.md b/docs/SPEC.md index 106e796..2e856a2 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -606,3 +606,7 @@ EN: Protected skipped-record retention and explicit fallible disclosure; file/CL DE: Linux-Quelltraversierung verwendet vorhandenes rustix::RawDir mit vorab gesperrtem Caller-Puffer, tatsächlichem Iterator/Record, Namens-/Permutations-/Sortierarena und Cursor. Keine gewöhnlichen read_dir-/DirEntry-/file_name-/PathBuf-Traversierungscontainer in diesem Linux-Pfad. Borrowed native Pfade und bounded depth-first Rekursion erhalten Reihenfolge und Skip-Semantik. Keine eigene neue unsafe-Grenze; Windows-Traversierung und Quelle-Race338 bleiben offen. Abnahme: security/LINUX_DIRECTORY_VALIDATION.md. EN: Actual Linux source traversal in protected storage; remaining platform, output/report/helper/host contracts remain required. + + +DE: Für die folgende Windows-Quelltraversierung steht ein direkter synchroner NT-Verzeichniscaller mit vorab gesperrtem tatsächlichem SDK-Status-/Ausgabespeicher in Prüfung. Private Handle-Konstruktion verbietet fremde/asynchrone Handles; Teilantworten/Overflow nicht als EOF akzeptieren. Produktionswalker noch nicht migriert; kein Gesamtabschluss. Scope/Abnahme: security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md. +EN: Native fixtures and full Windows production traversal acceptance remain required. diff --git a/docs/security/LINUX_DIRECTORY_VALIDATION.md b/docs/security/LINUX_DIRECTORY_VALIDATION.md index 2190b32..9ee42e2 100644 --- a/docs/security/LINUX_DIRECTORY_VALIDATION.md +++ b/docs/security/LINUX_DIRECTORY_VALIDATION.md @@ -57,7 +57,9 @@ Source-bound linux-directory-v1:16 commands and906 unchanged Rust/manifest hashes pass; four strict root/two platform lints,107 file groups per feature configuration and69 selected integration cases. All actual own-child calls execute through their parents;14 explicit child/race entries remain ignored. -Root/platform fmt, limits, vendor/matrix and diff pass. Native acceptance pending. +Root/platform fmt, limits, vendor/matrix and diff pass. Native8ca6fb7 full Rust logs pass: Linux22/ARM988 tests each, latest1897, +Windows1696; zero failures. Actual new Linux parents/depth cases run on both +architectures; Windows is compatibility-only. Complete hashed logs retained. Sources / Quellen: - Existing pinned rustix1.1.6 src/fs/raw_dir.rs and backend getdents implementation. diff --git a/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md b/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md new file mode 100644 index 0000000..e4e37b2 --- /dev/null +++ b/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md @@ -0,0 +1,77 @@ +# Direct Windows directory caller / Direkter Windows-Verzeichniscaller + +DE: Weiterer M1/M3-Teil im gemeinsamen Draft355; zunächst eigenständiger +Plattformadapter und tatsächliche Root-Caller-Fixtures. Der produktive Windows- +Walker ist hier NOCH NICHT migriert. Cross-Kompilierung ist keine native Abnahme. +EN: Existing windows-sys0.61.2 features extended, no package version/source or +new provider changed. Native Linux traversal and prior acceptance retained. + +DE: DirectoryRead besitzt ausschließlich einen selbst mit CreateFileW geöffneten +synchronen privaten File-Handle: null Security/Template, SHARE_ALL, Directory- +List-/Synchronize-Zugriff, BACKUP_SEMANTICS/OPEN_REPARSE_POINT und kein +OVERLAPPED. File weder exportieren/klonen noch fremden/asynchronen File annehmen. +Den tatsächlich geöffneten Handle zusätzlich über den vorhandenen gesperrten +SourceMetadata-Handle-Query prüfen; reguläre Dateien und namensumleitende Reparse- +Blätter vor der ersten Verzeichnisabfrage verweigern. Kein erneutes Pfad-Open. +Dadurch kann sichere Rust-Nutzung die synchrone Borrow-Lebensdauer nicht durch +Einschleusen eines asynchronen Handles verletzen. Owner vor Öffnung gesperrt. +EN: NtQueryDirectoryFile uses no event/APC and writes FileNamesInformation +straight into exclusive prelocked aligned u32 storage. The actual SDK +IO_STATUS_BLOCK is also inside the prelocked owner. This avoids relying solely +on unspecified Find-handle/user-space buffering for directory-name retention. +It is not an empirical claim about a specific closed-source OS implementation. + +DE: Nur vollständiger STATUS_SUCCESS mit geprüftem nichtleerem Information- +Bereich liefert Daten; EOF ausschließlich STATUS_NO_MORE_FILES. Overflow, +native Fehler, Success-mit-Null und unvollständige Geometrie sind Fehler, keine +stille Teilauflistung. Nach Fehler kein weiterer erfolgreicher Capture auf +diesem Objekt: auch Capture-vor-Open, ungültiger Puffer und erneutes Open sperren +den Zustand dauerhaft; kein versehentlicher Rückgriff auf einen alten Handle. Private synchrone Handle-Konstruktion ist die notwendige +Lebensdauergrundlage: keine asynchrone IO darf geliehene Daten nach Return nutzen. +EN: Four necessary production platform unsafe blocks: CreateFileW, sole File +ownership transfer, synchronous NtQueryDirectoryFile and documented scalar +RtlNtStatusToDosError. SDK Default/union-zero call sites use safe Rust (the pinned SDK Default +implementation contains inherited unsafe, not a new project block); +fieldwise volatile counters plus complete Root allocation/padding wipe. +No root unsafe, new syscall numbers, privilege or host-policy change. + +DE: Optionale native-memory-fixture ergänzt eine ausschließlich lesende eigene +Handle-Zählung mit einem begründeten FFI-Block. Keine Speicherinhalte, fremden +Prozesse oder Rechteänderungen. Neues u32-Workspace-Marker nutzt dieselbe +vorhandene primitive vollständige Wipe-/Unlock-Implementierung; tatsächlicher +Owner-/Move-/Zeroize-Test erweitert, kein Klartext-Vec-Fallback. +EN: Fixtures use actual native names, including an unpaired UTF16 surrogate, +public std reference names, physically observed protected SDK/output pages, +empty/missing/NUL/regular-file/reparse-leaf, poisoned caller state and a genuinely +too-small kernel buffer. Errors +must never become EOF or resumable success. A bounded own Windows child checks +exact own handle/locked-page cleanup after success, native failure and unwind. +These are public fixtures, not a plaintext export path for production metadata. + +## Remaining / Noch offen + +DE: Vollständige native Fixture-Abnahme, kontrollierter Packed-Record-Parser, +geschützter UTF16/WTF8-Sortier-/Skip-Pfad und tatsächliche Windows-Walker-Caller +müssen noch folgen. Kein M1/M3-/R7/R8-Abschluss. CLI-/JSON-/Wire-Verträge, ganze +Prozess-/Dump-/Helper-/Host-Verträge und restliche Metadaten weiter erforderlich. +EN: OS namespace/service internals and compiler/register boundaries stay explicit; +known ordinary application buffers are not relabelled external. No partial merge. + +Sources / Quellen: +- https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew +- https://learn.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o +- https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntquerydirectoryfile +- https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_names_information +- Existing pinned windows-sys0.61.2 declarations and SDK record defaults. + +## Local checkpoint / Lokaler Checkpoint + +DE: windows-directory-v4 besteht14 Kommandos bei908 unveränderten Rust-/Manifest- +Hashes: zwei strenge Plattform-Lints, vier Root-Lints mit/ohne API für Linux und +Windows-GNU; je8 tatsächliche Workspace-Gruppen samt echten Verweigerungskindern. +Fmt/Dateilimits/Provider-/Angriffsmatrix-/Diff-Gates unverändert bestanden. +EN: All168 locked package entries and full Cargo.lock are byte-identical to8ca6fb7. +Actual opened-handle metadata reuses the previously verified protected SDK query, +with no extra FFI block or second path open. Directory access requests only +LIST_DIRECTORY|SYNCHRONIZE. Native Windows fixture execution remains pending; +no production traversal or whole R7/R8 acceptance is claimed. diff --git a/platform/pqkeep-platform/Cargo.toml b/platform/pqkeep-platform/Cargo.toml index c0fcf12..6e6201f 100644 --- a/platform/pqkeep-platform/Cargo.toml +++ b/platform/pqkeep-platform/Cargo.toml @@ -11,7 +11,7 @@ description = "Narrow synchronous platform adapters for PQKeep" libc = "=0.2.191" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_Storage_FileSystem", "Win32_Security", "Win32_UI_Input_KeyboardAndMouse"] } +windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_ErrorReporting", "Win32_System_Threading", "Win32_System_ProcessStatus", "Win32_Storage_FileSystem", "Wdk_Storage_FileSystem", "Win32_System_IO", "Win32_Security", "Win32_UI_Input_KeyboardAndMouse"] } [dependencies.zeroize] version = "1.9.1" diff --git a/platform/pqkeep-platform/src/directory_windows.rs b/platform/pqkeep-platform/src/directory_windows.rs new file mode 100644 index 0000000..ac9b99d --- /dev/null +++ b/platform/pqkeep-platform/src/directory_windows.rs @@ -0,0 +1,184 @@ +//! DE: Direkte NT-Verzeichnisdaten in ausgerichtetem Caller-Puffer, keine Find-Records. +//! EN: Direct NT directory data in aligned caller storage, without Find records. +use std::{ + fs::File, + io, + os::windows::io::{AsRawHandle, FromRawHandle}, + ptr, +}; +use windows_sys::{ + Wdk::Storage::FileSystem::{FileNamesInformation, NtQueryDirectoryFile}, + Win32::{ + Foundation::{INVALID_HANDLE_VALUE, NTSTATUS, RtlNtStatusToDosError, STATUS_NO_MORE_FILES}, + Storage::FileSystem::{ + CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, + FILE_LIST_DIRECTORY, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, + OPEN_EXISTING, SYNCHRONIZE, + }, + System::IO::IO_STATUS_BLOCK, + }, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +/// DE: Caller muss diesen konkreten Owner und seine Ausgabepuffer vor Nutzung sperren. +/// EN: The caller must prelock this concrete owner and its output buffers before use. +/// DE/EN: Kein Clone/Debug, kein fremder/asynchroner Handle / no foreign or async handle. +pub struct DirectoryRead { + file: Option, + status: IO_STATUS_BLOCK, + metadata: crate::SourceMetadata, + ended: bool, + failed: bool, +} + +impl DirectoryRead { + /// DE/EN: Nur öffentlicher leerer Zustand / public empty state only. + #[must_use] + pub fn empty() -> Self { + Self { + file: None, + status: IO_STATUS_BLOCK::default(), + metadata: crate::SourceMetadata::empty(), + ended: false, + failed: false, + } + } + + /// DE: Bereits nativen Pfad nur einmal öffnen; Root schützt Quelle und Owner. + /// EN: Open an already native path once; root protects source and owner. + /// # Errors + /// DE/EN: Ungültiger Zustand/Pfad oder nativer Fehler / invalid state/path or native failure. + pub fn open_into(&mut self, path: &[u16]) -> io::Result<()> { + if self.file.is_some() || self.failed || self.ended { + self.failed = true; + return Err(io::ErrorKind::InvalidInput.into()); + } + if let Err(error) = crate::path_windows::validate(path) { + self.failed = true; + return Err(error); + } + // DE: Lebende NUL-Quelle, genau ein nicht vererbbarer synchroner Handle. + // SAFETY: Validated NUL-terminated live path; null security/template means + // no inheritance. NO OVERLAPPED, private owned handle: all later directory + // queries are synchronous; no caller can substitute an async/foreign handle. + let handle = unsafe { + CreateFileW( + path.as_ptr(), + FILE_LIST_DIRECTORY | SYNCHRONIZE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + self.failed = true; + return Err(io::Error::last_os_error()); + } + // DE: Erfolgreich erzeugtes Eigentum genau einmal übertragen. + // SAFETY: Fresh successful CreateFileW handle transferred exactly once; + // the private File is never exported, cloned, or used for overlapped I/O. + self.file = Some(unsafe { File::from_raw_handle(handle) }); + let result = self.verify_opened(); + if result.is_err() { + self.failed = true; + } + result + } + + fn verify_opened(&mut self) -> io::Result<()> { + let file = self.file.as_ref().ok_or(io::ErrorKind::InvalidInput)?; + self.metadata.capture_file(file)?; + if !self.metadata.is_dir() { + return Err(io::ErrorKind::NotADirectory.into()); + } + Ok(()) + } + + /// DE: Native `FileNamesInformation`-Bytes direkt in vollständig geliehenes Ziel. + /// EN: Write native `FileNamesInformation` bytes directly into a complete borrowed target. + /// # Errors + /// DE/EN: Zustand/Puffer, native Fehler oder unvollständige Antwort / state/buffer/native/partial response. + pub fn capture(&mut self, output: &mut [u32]) -> io::Result> { + if self.failed || self.file.is_none() { + return self.reject(io::ErrorKind::InvalidInput.into()); + } + if self.ended { + return Ok(None); + } + let Ok(length) = u32::try_from(size_of_val(output)) else { + return self.reject(io::ErrorKind::InvalidInput.into()); + }; + if length < 16 { + return self.reject(io::ErrorKind::InvalidInput.into()); + } + self.status.Anonymous.Pointer = ptr::null_mut(); + self.status.Information.zeroize(); + let file = self.file.as_ref().ok_or(io::ErrorKind::InvalidInput)?; + // DE: Exklusive ausgerichtete Ziele; synchroner Handle behält keine geborgten Zeiger. + // SAFETY: Hidden known synchronous owned handle, no APC/event/async flag. + // DWORD-aligned exclusive output covers exactly length valid bytes; u32 + // accepts every output bit pattern. Actual exclusive SDK status is complete. + // Documented synchronous completion retains neither borrowed pointer. + let status = unsafe { + NtQueryDirectoryFile( + file.as_raw_handle(), + ptr::null_mut(), + None, + ptr::null(), + &raw mut self.status, + output.as_mut_ptr().cast(), + length, + FileNamesInformation, + false, + ptr::null(), + false, + ) + }; + self.completed(status, output.len()) + } + + fn completed(&mut self, status: NTSTATUS, words: usize) -> io::Result> { + if status == STATUS_NO_MORE_FILES { + self.ended = true; + return Ok(None); + } + if status != 0 { + return self.reject(native_error(status)); + } + let count = self.status.Information; + if count < 12 || count > words * size_of::() { + return self.reject(io::ErrorKind::InvalidData.into()); + } + Ok(Some(count)) + } + + fn reject(&mut self, error: io::Error) -> io::Result> { + self.failed = true; + Err(error) + } +} + +fn native_error(status: NTSTATUS) -> io::Error { + // DE: Dokumentierte skalare Fehlerübersetzung ohne geborgte Datenzeiger. + // SAFETY: Documented scalar NTSTATUS-to-Win32 error translation, no borrowed + // input/output pointer, token/privilege or host-policy changes. + let code = unsafe { RtlNtStatusToDosError(status) }; + i32::try_from(code).map_or_else( + |_| io::ErrorKind::InvalidData.into(), + io::Error::from_raw_os_error, + ) +} + +impl Drop for DirectoryRead { + fn drop(&mut self) { + self.file = None; + self.status.Anonymous.Pointer = ptr::null_mut(); + self.status.Information.zeroize(); + self.ended.zeroize(); + self.failed.zeroize(); + // DE/EN: Root löscht zusätzlich die gesamte Allokation samt Padding / full allocation and padding. + } +} +impl ZeroizeOnDrop for DirectoryRead {} diff --git a/platform/pqkeep-platform/src/lib.rs b/platform/pqkeep-platform/src/lib.rs index ec98787..b9b9c74 100644 --- a/platform/pqkeep-platform/src/lib.rs +++ b/platform/pqkeep-platform/src/lib.rs @@ -41,3 +41,8 @@ pub use source_metadata::SourceMetadata; mod core_limits_linux; #[cfg(target_os = "linux")] pub use core_limits_linux::core_limits_disabled; + +#[cfg(windows)] +mod directory_windows; +#[cfg(windows)] +pub use directory_windows::DirectoryRead; diff --git a/platform/pqkeep-platform/src/memory_fixture.rs b/platform/pqkeep-platform/src/memory_fixture.rs index 81729db..3c0c54e 100644 --- a/platform/pqkeep-platform/src/memory_fixture.rs +++ b/platform/pqkeep-platform/src/memory_fixture.rs @@ -4,7 +4,7 @@ use std::io; use windows_sys::Win32::System::{ ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}, - Threading::GetCurrentProcess, + Threading::{GetCurrentProcess, GetProcessHandleCount}, }; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -71,3 +71,18 @@ impl Drop for MemoryLockQuery { } } impl ZeroizeOnDrop for MemoryLockQuery {} + +/// DE: Nur die öffentliche Handle-Zahl des eigenen Testprozesses lesen. +/// EN: Read only the public handle count of the own test process. +/// # Errors +/// DE/EN: Native Verweigerung / native refusal. +pub fn own_handle_count() -> io::Result { + let mut count = 0; + // DE: Nur eigene öffentliche Zählung im exklusiven DWORD, keine Speicherinhalte. + // SAFETY: Borrowed current-process pseudo handle and exclusive initialized + // DWORD output. Read-only count, no handle creation/duplication or memory read. + if unsafe { GetProcessHandleCount(GetCurrentProcess(), &raw mut count) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(count) +} diff --git a/platform/pqkeep-platform/src/source_metadata_windows.rs b/platform/pqkeep-platform/src/source_metadata_windows.rs index e072860..c9967d3 100644 --- a/platform/pqkeep-platform/src/source_metadata_windows.rs +++ b/platform/pqkeep-platform/src/source_metadata_windows.rs @@ -62,6 +62,13 @@ impl SourceMetadata { } Err(error) => return Err(error), }; + self.capture_file(&file) + } + + // DE: Bereits besessenen Handle prüfen, statt einen Pfad erneut zu öffnen. + // EN: Query an already owned handle rather than reopen a path. + pub(crate) fn capture_file(&mut self, file: &File) -> io::Result<()> { + self.zeroize(); // DE: Echtes SDK-Ziel ist ausgerichtet und exklusiv; API behält keinen Pointer. // SAFETY: File owns a valid handle through this synchronous call; native // is aligned and writable for the actual BY_HANDLE_FILE_INFORMATION type. @@ -71,7 +78,7 @@ impl SourceMetadata { // DE/EN: Initialisiertes SDK-Ziel ausschließlich leihen / borrow the initialized SDK target. let native = &self.native; if native.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { - self.symlink = capture_tag(&file, &mut self.tag)?; + self.symlink = capture_tag(file, &mut self.tag)?; } self.file = !self.symlink && native.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0; self.directory = !self.symlink && native.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0; diff --git a/src/crypto/secret_buffer.rs b/src/crypto/secret_buffer.rs index a449999..1ed2c77 100644 --- a/src/crypto/secret_buffer.rs +++ b/src/crypto/secret_buffer.rs @@ -134,6 +134,7 @@ impl ZeroizeOnDrop for SecretBuffer {} impl ZeroizeOnDrop for SecretBuffer {} impl ZeroizeOnDrop for SecretBuffer {} impl ZeroizeOnDrop for SecretBuffer {} +impl ZeroizeOnDrop for SecretBuffer {} impl Zeroize for SecretBuffer { fn zeroize(&mut self) { diff --git a/src/crypto/secret_workspace_tests.rs b/src/crypto/secret_workspace_tests.rs index 4d75002..ac96a70 100644 --- a/src/crypto/secret_workspace_tests.rs +++ b/src/crypto/secret_workspace_tests.rs @@ -55,6 +55,7 @@ fn concrete_primitive_descriptors_are_locked_and_stable() { primitive(17usize); primitive(true); primitive(0xd834u16); + primitive(0xa5a5_1234u32); } #[test] diff --git a/src/files/mod.rs b/src/files/mod.rs index c38dd19..68af0f5 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -218,3 +218,7 @@ pub fn inspect_v2(source: &Path) -> Result { let mut reader = BufReader::new(native_path::open_file(source)?); HeaderV2::read(&mut reader) } + +#[cfg(all(test, windows))] +#[path = "windows_directory_adapter_tests.rs"] +mod windows_directory_adapter_tests; diff --git a/src/files/windows_directory_adapter_tests.rs b/src/files/windows_directory_adapter_tests.rs new file mode 100644 index 0000000..f233750 --- /dev/null +++ b/src/files/windows_directory_adapter_tests.rs @@ -0,0 +1,262 @@ +//! DE: Echter synchroner NT-Caller mit gesperrten SDK-/Ausgaberecords, nur öffentliche Fixtures. +//! EN: Actual synchronous NT caller with locked SDK/output records; public fixtures only. +#![allow(clippy::unwrap_used)] +use crate::crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}; +use pqkeep_platform::{DirectoryRead, memory_fixture::MemoryLockQuery}; +use std::{ + ffi::OsString, + os::windows::ffi::{OsStrExt, OsStringExt}, + path::Path, +}; + +fn reader(path: &Path) -> SecretState { + let encoded = super::native_path::NativePath::from_path(path).unwrap(); + let mut reader = SecretState::new(DirectoryRead::empty()).unwrap(); + reader + .get_mut() + .open_into(encoded.encoded().unwrap()) + .unwrap(); + reader +} + +fn locked(value: &T) { + crate::locked_owner_test_support::locked(value); + let mut query = SecretState::new(MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(value).addr(); + assert!(query.get_mut().is_locked(start).unwrap()); + assert!( + query + .get_mut() + .is_locked(start + size_of_val(value) - 1) + .unwrap() + ); +} + +fn public_names(words: &[u32], count: usize) -> Vec> { + let mut cursor = 0; + let mut names = Vec::new(); + loop { + assert!(cursor % 4 == 0 && cursor + 12 <= count); + let header = &words[cursor / 4..]; + let next = usize::try_from(header[0]).unwrap(); + let bytes = usize::try_from(header[2]).unwrap(); + assert!(bytes % 2 == 0 && cursor + 12 + bytes <= count); + let units: Vec<_> = (0..bytes / 2) + .map(|index| { + let word = header[3 + index / 2]; + u16::try_from((word >> (16 * (index % 2))) & 0xffff).unwrap() + }) + .collect(); + if units != [46] && units != [46, 46] { + names.push(units); + } + if next == 0 { + return names; + } + assert!(next % 4 == 0 && next >= 12 + bytes); + cursor = cursor.checked_add(next).unwrap(); + assert!(cursor < count); + } +} + +#[test] +fn actual_nt_directory_output_and_status_are_prelocked_and_preserve_raw_utf16_names() { + let root = tempfile::tempdir().unwrap(); + for name in [ + OsString::from("a"), + OsString::from("ä😀"), + OsString::from_wide(&[0xd800]), + ] { + std::fs::write(root.path().join(name), b"public NT fixture").unwrap(); + } + let mut expected: Vec<_> = std::fs::read_dir(root.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().encode_wide().collect::>()) + .collect(); + let mut reader = reader(root.path()); + let mut output = SecretWorkspace::::zeroed(16_388).unwrap(); + let mut names = Vec::new(); + let mut ended = false; + for _ in 0..100 { + locked(reader.get()); + output.assert_metadata_locked(); + locked(output.expose()); + let Some(count) = reader.get_mut().capture(output.expose_mut()).unwrap() else { + ended = true; + break; + }; + locked(reader.get()); + locked(output.expose()); + names.extend(public_names(output.expose(), count)); + } + assert!(ended); + assert!( + reader + .get_mut() + .capture(output.expose_mut()) + .unwrap() + .is_none() + ); + expected.sort(); + names.sort(); + let equal = names == expected; + assert!(equal); +} + +#[test] +fn empty_directory_finishes_and_missing_nul_and_regular_file_are_not_empty_success() { + let root = tempfile::tempdir().unwrap(); + let mut output = SecretWorkspace::::zeroed(16_388).unwrap(); + let mut empty = reader(root.path()); + let mut ended = false; + for _ in 0..8 { + let Some(count) = empty.get_mut().capture(output.expose_mut()).unwrap() else { + ended = true; + break; + }; + let empty_names = public_names(output.expose(), count).is_empty(); + assert!(empty_names); + } + assert!(ended); + let missing = super::native_path::NativePath::from_path(&root.path().join("missing")).unwrap(); + let mut failed = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!( + failed + .get_mut() + .open_into(missing.encoded().unwrap()) + .is_err() + ); + assert!(failed.get_mut().capture(output.expose_mut()).is_err()); + let mut failed = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!(failed.get_mut().open_into(&[65, 0, 66, 0]).is_err()); + let file = root.path().join("file"); + std::fs::write(&file, b"public fixture").unwrap(); + let encoded = super::native_path::NativePath::from_path(&file).unwrap(); + let mut regular = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!( + regular + .get_mut() + .open_into(encoded.encoded().unwrap()) + .is_err() + ); + assert!(regular.get_mut().capture(output.expose_mut()).is_err()); +} + +#[test] +fn actual_small_kernel_buffer_failure_never_becomes_truncation_or_resumable_success() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("a".repeat(128)), b"public fixture").unwrap(); + let mut reader = reader(root.path()); + let mut output = SecretWorkspace::::zeroed(8).unwrap(); + let mut failed = false; + for _ in 0..8 { + match reader.get_mut().capture(output.expose_mut()) { + Ok(Some(_)) => {} + Ok(None) => break, + Err(_) => { + failed = true; + break; + } + } + } + assert!(failed); + locked(reader.get()); + locked(output.expose()); + assert!(reader.get_mut().capture(output.expose_mut()).is_err()); +} + +#[test] +fn actual_own_handle_and_lock_cleanup_run_in_a_bounded_windows_child() { + crate::locked_owner_test_support::isolated_test( + "files::windows_directory_adapter_tests::handle_cleanup_child", + "PQKEEP_WINDOWS_DIRECTORY_CHILD", + ); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn handle_cleanup_child() { + assert_eq!( + std::env::var("PQKEEP_WINDOWS_DIRECTORY_CHILD").unwrap(), + "1" + ); + let root = tempfile::tempdir().unwrap(); + let file = root.path().join("public"); + std::fs::write(&file, b"public fixture").unwrap(); + active_reader(root.path(), false); + let baseline = own_resources(); + active_reader(root.path(), false); + assert_eq!(own_resources(), baseline); + let result = std::panic::catch_unwind(|| active_reader(root.path(), true)); + assert!(result.is_err()); + assert_eq!(own_resources(), baseline); + { + let encoded = super::native_path::NativePath::from_path(&file).unwrap(); + let mut reader = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!( + reader + .get_mut() + .open_into(encoded.encoded().unwrap()) + .is_err() + ); + } + assert_eq!(own_resources(), baseline); +} + +fn active_reader(path: &Path, unwind: bool) { + let mut reader = reader(path); + let mut output = SecretWorkspace::::zeroed(16_388).unwrap(); + assert!( + reader + .get_mut() + .capture(output.expose_mut()) + .unwrap() + .is_some() + ); + locked(reader.get()); + locked(output.expose()); + if unwind { + std::panic::resume_unwind(Box::new(())); + } +} + +fn own_resources() -> (u32, usize) { + ( + pqkeep_platform::memory_fixture::own_handle_count().unwrap(), + crate::hardening::memlock::stats().locked_pages, + ) +} + +#[test] +fn state_errors_poison_before_open_after_reopen_and_after_invalid_buffer() { + let root = tempfile::tempdir().unwrap(); + let encoded = super::native_path::NativePath::from_path(root.path()).unwrap(); + let path = encoded.encoded().unwrap(); + let mut output = SecretWorkspace::::zeroed(16_388).unwrap(); + let mut early = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!(early.get_mut().capture(output.expose_mut()).is_err()); + assert!(early.get_mut().open_into(path).is_err()); + let mut reopened = reader(root.path()); + assert!(reopened.get_mut().open_into(path).is_err()); + assert!(reopened.get_mut().capture(output.expose_mut()).is_err()); + let mut short = reader(root.path()); + assert!(short.get_mut().capture(&mut []).is_err()); + assert!(short.get_mut().capture(output.expose_mut()).is_err()); +} + +#[test] +fn opened_directory_symlink_leaf_is_rejected_before_any_directory_query() { + let root = tempfile::tempdir().unwrap(); + let link = root.path().join("link"); + std::os::windows::fs::symlink_dir(root.path(), &link).unwrap(); + let encoded = super::native_path::NativePath::from_path(&link).unwrap(); + let mut reader = SecretState::new(DirectoryRead::empty()).unwrap(); + assert!( + reader + .get_mut() + .open_into(encoded.encoded().unwrap()) + .is_err() + ); + let mut output = SecretWorkspace::::zeroed(16_388).unwrap(); + assert!(reader.get_mut().capture(output.expose_mut()).is_err()); +} From 8913f5c365fbbe97f3f1697c57fbaa5003983080 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:28:12 +0100 Subject: [PATCH 21/26] Protect native Windows source traversal and WTF-8 ownership DE: NT-Ausgabe, Parser, native Namen/Pfade und WTF8-Sortierschluessel vor privater Befuellung sperren; vorhandenen Linux-Walker/Quellslot wiederverwenden. 16 lokale Pruefungen bei918 unveraenderten Quellen bestanden. Keine neue unsafe-Stelle oder Abhaengigkeit; native Windows-Produktionsabnahme und R7/R8-Gesamtvertraege offen. EN: Reuse protected native arenas, direct source copies and checked synchronous NT output. Preserve raw UTF16, stable std WTF8 ordering, verbatim join and depth/skip rules; bounded own cleanup/unwind and physical-owner fixtures. Full source-bound local acceptance passes; native acceptance pending. Same joint Draft355, no Main merge. Refs #147 --- docs/ROADMAP.md | 3 + docs/SPEC.en.md | 3 + docs/SPEC.md | 3 + docs/security/SECRET_LIFETIME_INVENTORY.md | 11 ++ .../WINDOWS_DIRECTORY_CALLER_VALIDATION.md | 10 +- docs/security/WINDOWS_TRAVERSAL_VALIDATION.md | 94 ++++++++++++ src/files/confidential_os_text.rs | 7 + src/files/confidential_os_text_tests.rs | 7 + src/files/confidential_os_text_windows.rs | 9 +- src/files/directory_records.rs | 79 ++++++++++ src/files/directory_records_tests.rs | 93 ++++++++++++ src/files/locked_wide.rs | 15 +- src/files/mod.rs | 14 +- src/files/native_directory_windows.rs | 70 +++++++++ src/files/native_directory_windows_tests.rs | 115 +++++++++++++++ src/files/native_names.rs | 121 ++++++++++++++-- src/files/native_names_sort.rs | 6 +- src/files/native_names_windows_tests.rs | 74 ++++++++++ src/files/native_path.rs | 12 +- src/files/native_path_join_windows.rs | 135 ++++++++++++++++++ src/files/native_path_windows.rs | 66 +++++++++ src/files/native_path_windows_tests.rs | 66 +++++++++ src/files/native_wtf8.rs | 124 ++++++++++++++++ src/files/native_wtf8_tests.rs | 73 ++++++++++ src/files/source_entries.rs | 24 +++- src/files/source_entry.rs | 7 +- src/files/source_metadata.rs | 5 + src/files/walk.rs | 10 +- src/files/walk_linux.rs | 98 +------------ src/files/walk_linux_tests.rs | 6 +- src/files/walk_native.rs | 89 ++++++++++++ src/files/walk_windows_tests.rs | 78 ++++++++++ 32 files changed, 1388 insertions(+), 139 deletions(-) create mode 100644 docs/security/WINDOWS_TRAVERSAL_VALIDATION.md create mode 100644 src/files/directory_records.rs create mode 100644 src/files/directory_records_tests.rs create mode 100644 src/files/native_directory_windows.rs create mode 100644 src/files/native_directory_windows_tests.rs create mode 100644 src/files/native_names_windows_tests.rs create mode 100644 src/files/native_path_join_windows.rs create mode 100644 src/files/native_wtf8.rs create mode 100644 src/files/native_wtf8_tests.rs create mode 100644 src/files/walk_native.rs create mode 100644 src/files/walk_windows_tests.rs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index f973236..c1203c8 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -224,3 +224,6 @@ EN: No partial Main merge or overall R7/R8 closure; Windows traversal/output/rep DE: R7/R8 weiter In progress in genau Draft355. Linux-Traversierung8ca6fb7 lokal vollständig geprüft und veröffentlicht, native Gesamtabnahme läuft. Windows-NT-Caller/echte gesperrte SDK-Fixtures lokal in Prüfung; keine vorgezogene Windows-Walker-/Helper-/Host-Abnahme. EN: Same joint PR, no partial Main merge or scope closure. + +DE: R7/R8 weiter In progress: Windows-NT-Adapter aae9a vollständig nativ abgenommen, alle25 Checks erfolgreich. Produktive Windows-Traversierung mit geschützten WTF8-/UTF16-/Namensarenen lokal angebunden; vollständiger lokaler Quellencheckpoint mit16 Kommandos/918 unveränderten Quellen bestanden; native Produktionsabnahme ausstehend. Verbindlicher Stand und offene Gesamtverträge: security/WINDOWS_TRAVERSAL_VALIDATION.md. +EN: Same Draft355; native production acceptance pending, no whole R7/R8 closure. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index d47a479..492e48f 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -603,3 +603,6 @@ DE: Echte Linux-Traversierung gesperrt; übrige Plattform-/Ziel-/Report-/Helper- EN: A direct synchronous NT directory caller with prelocked actual SDK status/output storage is under verification for upcoming Windows source traversal. Private handle construction rejects foreign/asynchronous handles; partial responses/overflow never mean EOF. Production walker remains unmigrated; no overall closure. Scope: security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md. DE: Native Fixtures und vollständige Windows-Produktionscaller noch abnehmen. + +EN: Follow-up production Windows traversal uses the protected NT caller. Native name/sort arenas, UTF16 paths and directly protected WTF8 keys preserve std ordering, including unpaired surrogates; fallible direct source-slot copies avoid intermediate PathBuf containers. The shared Linux/Windows walker preserves skip/depth rules. Checked NT record boundaries and verbatim path reconstruction add no root unsafe. Actual acceptance and remaining boundaries: security/WINDOWS_TRAVERSAL_VALIDATION.md. +DE: Produktionsimplementierung; vollständige native Abnahme und übrige R7/R8-Verträge weiterhin erforderlich. diff --git a/docs/SPEC.md b/docs/SPEC.md index 2e856a2..f502dbb 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -610,3 +610,6 @@ EN: Actual Linux source traversal in protected storage; remaining platform, outp DE: Für die folgende Windows-Quelltraversierung steht ein direkter synchroner NT-Verzeichniscaller mit vorab gesperrtem tatsächlichem SDK-Status-/Ausgabespeicher in Prüfung. Private Handle-Konstruktion verbietet fremde/asynchrone Handles; Teilantworten/Overflow nicht als EOF akzeptieren. Produktionswalker noch nicht migriert; kein Gesamtabschluss. Scope/Abnahme: security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md. EN: Native fixtures and full Windows production traversal acceptance remain required. + +DE: Folgeimplementierung bindet den geschützten NT-Caller im produktiven Windows-Walker an. Native Namens-/Sortierarenen, UTF16-Pfade und direkt gesperrte WTF8-Schlüssel erhalten std-Reihenfolge einschließlich einzelner Surrogate; direkte fallible Quellslot-Kopien ohne PathBuf-Zwischencontainer. Gemeinsamer Linux-/Windows-Walker erhält Skip-/Tiefengrenzen. Geprüfte NT-Recordgrenzen und Verbatim-Pfadaufbau ohne Root-unsafe. Tatsächliche Abnahme und verbleibende Grenzen: security/WINDOWS_TRAVERSAL_VALIDATION.md. +EN: Production traversal implementation; full native acceptance and remaining R7/R8 contracts still required. diff --git a/docs/security/SECRET_LIFETIME_INVENTORY.md b/docs/security/SECRET_LIFETIME_INVENTORY.md index 59ee9eb..d9365b2 100644 --- a/docs/security/SECRET_LIFETIME_INVENTORY.md +++ b/docs/security/SECRET_LIFETIME_INVENTORY.md @@ -138,3 +138,14 @@ DE: Aktueller R6-Gesamtstand: [Provider-Abnahmematrix](PROVIDER_LIFETIME_VALIDAT Frühere OPEN-/Teilnachweise hier sind historische Zwischenstände. EN: The current complete matrix supersedes earlier scoped provider status, without asserting complete R7/R8 or whole-issue147 remediation. + +## Current joint traversal follow-up / Aktuelle gemeinsame Traversierungsnacharbeit + +DE: Linux-native Traversierung8ca6fb7 und Windows-NT-Caller aae9a sind getrennt +nativ abgenommen. Der produktive gemeinsame Linux-/Windows-Walker mit +geschützten nativen Namensarenen, WTF8-Schlüsseln, NT-Parser und direkten +Quellslot-Kopien wird in WINDOWS_TRAVERSAL_VALIDATION.md separat abgenommen. +EN: Do not infer whole M1/M2/M3 closure from directory enumeration. Top-level +std::Path component scanning, API/CLI-owned ingress, output/temporary/original +paths, cleanup/identity/handle records and report/transport remain in scope. +Source-race338 and complete process/helper/host contracts remain open. diff --git a/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md b/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md index e4e37b2..926d3c0 100644 --- a/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md +++ b/docs/security/WINDOWS_DIRECTORY_CALLER_VALIDATION.md @@ -2,7 +2,8 @@ DE: Weiterer M1/M3-Teil im gemeinsamen Draft355; zunächst eigenständiger Plattformadapter und tatsächliche Root-Caller-Fixtures. Der produktive Windows- -Walker ist hier NOCH NICHT migriert. Cross-Kompilierung ist keine native Abnahme. +Walker war am Adapter-Head aae9a noch nicht migriert. Die Folgeimplementierung +steht in WINDOWS_TRAVERSAL_VALIDATION.md. Cross-Kompilierung ist keine native Abnahme. EN: Existing windows-sys0.61.2 features extended, no package version/source or new provider changed. Native Linux traversal and prior acceptance retained. @@ -73,5 +74,8 @@ Fmt/Dateilimits/Provider-/Angriffsmatrix-/Diff-Gates unverändert bestanden. EN: All168 locked package entries and full Cargo.lock are byte-identical to8ca6fb7. Actual opened-handle metadata reuses the previously verified protected SDK query, with no extra FFI block or second path open. Directory access requests only -LIST_DIRECTORY|SYNCHRONIZE. Native Windows fixture execution remains pending; -no production traversal or whole R7/R8 acceptance is claimed. +LIST_DIRECTORY|SYNCHRONIZE. Native aae9a full logs pass: Linux22/ARM988 tests each, +latest1897 and Windows1708, zero failures. All six actual Windows SDK parent +cases execute in both feature configurations; all25 checks pass. Production +traversal is a separate follow-up: WINDOWS_TRAVERSAL_VALIDATION.md. No whole +R7/R8 acceptance is claimed. diff --git a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md new file mode 100644 index 0000000..b4ecf70 --- /dev/null +++ b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md @@ -0,0 +1,94 @@ +# Protected Windows traversal / Geschützte Windows-Traversierung + +DE: M1/M2/M3-Teil im gemeinsamen Draft355. Der produktive Windows-Walker nutzt +jetzt den zuvor separat nativ abgenommenen synchronen NT-Caller. Dieser Schritt +schließt nicht die übrigen R7/R8-Verträge. Cross-Clippy allein ist keine native +Abnahme; den tatsächlichen Stand unten anhand des exakten Heads prüfen. +EN: Reuse the existing protected native-name arena and shared Linux/Windows +walker. No new dependency, platform FFI or root unsafe block. Existing R6 and +Linux sandbox behavior remain required. + +## Ownership and semantics / Eigentum und Semantik + +DE: Tatsächlicher SDK-Reader, IO-Status, ausgerichteter u32-Kernelpuffer samt +Descriptor, NT-Recordgeometrie und aktueller UTF16-Name liegen vor Befüllung in +gesperrten Ownern. Record-Header auf Überlauf, Ausrichtung, Nichtleerheit, gerade +UTF16-Länge, Puffergrenzen, überlappende Folgeoffsets und vollständige Folgeheader +prüfen. Keine unsichere Slice-Umdeutung und kein privates Zwischenarray. Nur +nachgeprüfte Recordbytes übernehmen; abgeschnittene oder fehlerhafte Records +beenden die Operation mit Fehler. Punktnamen des Kernels ausfiltern. +EN: The previously verified SDK reader owns only its private synchronous +non-inherited handle. No pending asynchronous request may outlive a borrowed +output. Native error/overflow is never accepted as EOF or a partial directory. + +DE: Native Namensrecords, Verzeichnisflags, Permutation, Wachstums-/Sortiercursor +und tatsächlicher Traversierungscursor verwenden die vorhandenen geschützten +Arenen. Für Windows kommt ein direkt gesperrt erzeugter WTF8-Schlüssel hinzu: +gültige Surrogatpaare zusammenfassen, einzelne Surrogate als WTF8 erhalten und +als Nicht-UTF8 markieren. Nicht nach UTF16 oder Ersatzzeichen sortieren: +OsString vergleicht seine WTF8-Bytes; sonst ändern sich Reihenfolge und +Gleichheit ungültiger Namen. Stabile Gleichnamensortierung über Originalindizes. +EN: Growth copies native paths and keys fallibly between already protected +destinations; clear partially populated slots on failure. Keep the original +collection intact if copying fails. Valid names borrow UTF8 directly from the +protected key, invalid names use the protected UTF16 replacement writer. + +DE: Blattnamen direkt an gesperrte native UTF16-Pfade anfügen. Laufwerksrelative +Pfade, UNC und Verbatim-Präfixe behalten die std-Semantik. Verbatim-Parent- +Komponenten wie std beim Anfügen neu zusammensetzen: mehrfache Backslashes +entfallen, bestehende Punktkomponenten bleiben erhalten. Kein gewöhnlicher +privater Komponenten-Vec oder PathBuf. Konkreter Aufbau-/Kopiercursor vor +privater Geometrie gesperrt; terminierendes NUL ausdrücklich schreiben. +EN: Source collectors copy protected native paths directly through the same +fallible slot initializer. Actual no-follow metadata is queried into protected +records. Process all direct children before alphabetical directory descent, +preserving portable validation, maximum depth and global source ordering. + +## Tests and acceptance / Tests und Abnahme + +DE: Öffentliche native Fixtures prüfen rohe UTF16-Ausgabe gegen std, einschließlich +einzelner Surrogate. Physische Windows-Seitensperren von tatsächlichem Reader, +Kernelpuffer, aktuellem Namen, Namensarenen, Schlüsseln und Cursor beobachten. +65 Einträge erzwingen Arena-Wachstum; Vergleich mit stabiler std-WTF8-Sortierung, +Verzeichnisflags, rewind, abgewiesene Namen und Erhalt alter Records. +EN: All65536 single UTF16 units plus paired/unpaired/random public sequences +are checked against std OsString encoding and UTF8 validity. Protected path +joining is compared with std drive/UNC/verbatim/unpaired-unit fixtures. + +DE: Echter vollständiger Windows-Baum mit gültigen Dateien/Unterverzeichnissen, +Nicht-UTF8-Namen und zwei portabel ungültigen Unicode-Namen prüft Dateigrößen, +globale Reihenfolge und Skip-Gründe/-Reihenfolge. Tiefengrenze verhindert den +Abstieg in das nächste unzulässige Verzeichnis. Begrenztes eigenes Kind prüft +Erfolg, Consumer-Fehler, Unwind und fehlende/falsche Quelle; danach exakt eigene +Handle-Zahl und registrierte gesperrte Seiten wie vorher. Kein fremder Prozess, +kein Speicherlesen und keine Rechte-/Token-/Hoständerung für diese Tests. +EN: Three malformed NT-parser groups also execute locally on Linux, exercising +real protected cursor/output ownership rather than only a type name. Existing +Linux actual mid-read/growth denial and cleanup cases remain mandatory. + +DE: Vollständiger lokaler Quellencheckpoint windows-traversal-v1 bestanden: +918 unveränderte Rust-/Manifest-Hashes über16 erfolgreiche Kommandos, sechs +strenge Lints, je110 Dateigruppen mit/ohne API und69 Integrationsfälle. Tatsächliche +Linux-Verweigerungs-/Unwindkinder ausgeführt;14 explizite Kind-/Race-Einstiege +bleiben sichtbar ignoriert. Native Windows-Produktionsabnahme steht noch aus. Der vorherige +Adapter-Head aae9a ist separat abgenommen: alle25 Checks; Linux22/ARM je988, +latest1897, Windows1708 erfolgreiche Tests. Seine sechs tatsächlichen Windows- +SDK-Elternfälle liefen in beiden Featurekonfigurationen; das ersetzt nicht die +Abnahme des hier angebundenen Produktionswalkers. +EN: Full logs, exact source hashes and native results must be retained before +claiming acceptance. Root stays forbid(unsafe_code). + +## Remaining boundaries / Verbleibende Grenzen + +DE: Quelle-Race338 bleibt offen: no-follow am Verzeichnisblatt allein bindet +nicht jeden Vorfahren und späteren Datei-Open. Ziel-/Temp-/Cleanup-/Handle-/ +Identitätsrecords, Reports/CLI/Transport und vollständige Prozess-/native +Passworthelper-/Bibliothekshost-Verträge sind weiterhin erforderlich. OS- +Namensraum und Compiler-/Registerskalare sind explizite Grenzen; gewöhnliche +interne App-Puffer werden dadurch nicht nachträglich zu Caller-Speicher erklärt. +EN: No whole R7/R8 closure, partial Main merge, wire/JSON change or weakened gate. + +Sources / Quellen: +- Existing pinned windows-sys0.61.2 FileNamesInformation/NtQueryDirectoryFile declarations. +- Rust std `path.rs::_push`, `sys/path/windows_prefix.rs`, WTF8 OsString representation; + local toolchain sources reviewed, native/MSRV checks still required. diff --git a/src/files/confidential_os_text.rs b/src/files/confidential_os_text.rs index 687363a..7916a69 100644 --- a/src/files/confidential_os_text.rs +++ b/src/files/confidential_os_text.rs @@ -5,6 +5,7 @@ use crate::{ Error, Result, crypto::{SecretBytes, secret_state::SecretState}, }; +#[cfg(any(not(windows), test))] use std::ffi::OsStr; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -27,6 +28,7 @@ impl Drop for Position { } impl ZeroizeOnDrop for Position {} +#[cfg(not(windows))] pub(super) fn joined_lossy(prefix: &str, name: &OsStr) -> Result { if let Some(valid) = name.to_str() { return ConfidentialText::joined(prefix, valid); @@ -40,6 +42,11 @@ pub(super) fn joined_lossy(prefix: &str, name: &OsStr) -> Result Result { + windows::wide_lossy_units(prefix, units) +} + fn output(prefix: &str, units: usize) -> Result { let len = units .checked_mul(3) diff --git a/src/files/confidential_os_text_tests.rs b/src/files/confidential_os_text_tests.rs index 14d5aa7..16631dd 100644 --- a/src/files/confidential_os_text_tests.rs +++ b/src/files/confidential_os_text_tests.rs @@ -5,7 +5,14 @@ use super::*; fn check(name: &OsStr) { let expected = format!("prefix/{}", name.to_string_lossy()); + #[cfg(not(windows))] let actual = joined_lossy("prefix/", name).unwrap(); + #[cfg(windows)] + let actual = { + use std::os::windows::ffi::OsStrExt; + let units: Vec<_> = name.encode_wide().collect(); + joined_lossy_units("prefix/", &units).unwrap() + }; actual.assert_owner_locked(); let equal = actual.expose().unwrap() == expected; assert!(equal); diff --git a/src/files/confidential_os_text_windows.rs b/src/files/confidential_os_text_windows.rs index 41899d1..974b162 100644 --- a/src/files/confidential_os_text_windows.rs +++ b/src/files/confidential_os_text_windows.rs @@ -1,10 +1,13 @@ //! DE: UTF16-Ersatzzeichen ohne privaten decode_utf16-Zwischeniterator. //! EN: UTF16 replacement without a private `decode_utf16` intermediate iterator. -use super::{ConfidentialText, Error, OsStr, Position, Result, SecretState, output}; +use super::{ConfidentialText, Error, Position, Result, SecretState, output}; use crate::files::locked_wide::LockedWide; -pub(super) fn wide_lossy(prefix: &str, name: &OsStr) -> Result { - let mut source = LockedWide::new(name)?; +pub(super) fn wide_lossy_units(prefix: &str, units: &[u16]) -> Result { + wide_source(prefix, LockedWide::from_units(units)?) +} + +fn wide_source(prefix: &str, mut source: LockedWide<'_>) -> Result { let mut position = SecretState::new(Position::default())?; let state = position.get_mut(); let mut out = output(prefix, source.len())?; diff --git a/src/files/directory_records.rs b/src/files/directory_records.rs new file mode 100644 index 0000000..41e2ede --- /dev/null +++ b/src/files/directory_records.rs @@ -0,0 +1,79 @@ +//! DE: Geprüfte NT-Namensgeometrie; konkreten Cursor vor privaten Headern sperren. +//! EN: Checked NT name geometry; prelock the concrete cursor before private headers. +use crate::{Error, Result}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +pub(super) struct Records { + pub(super) used: usize, + pub(super) position: usize, + pub(super) next: usize, + pub(super) name_bytes: usize, +} +impl Zeroize for Records { + fn zeroize(&mut self) { + self.used.zeroize(); + self.position.zeroize(); + self.next.zeroize(); + self.name_bytes.zeroize(); + } +} +impl Drop for Records { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for Records {} + +impl Records { + pub(super) fn begin(&mut self, count: usize, words: &[u32]) -> Result<()> { + if count < 12 || count > size_of_val(words) { + return Err(Error::Crypto); + } + self.used = count; + self.position = 0; + self.next = 0; + self.name_bytes = 0; + Ok(()) + } + pub(super) fn header(&mut self, words: &[u32]) -> Result<()> { + if self.used > size_of_val(words) + || self.position & 3 != 0 + || self.position.checked_add(12).is_none_or(|n| n > self.used) + { + return Err(Error::Crypto); + } + let words = words.get(self.position / 4..).ok_or(Error::Crypto)?; + self.next = + usize::try_from(*words.first().ok_or(Error::Crypto)?).map_err(|_| Error::Crypto)?; + self.name_bytes = + usize::try_from(*words.get(2).ok_or(Error::Crypto)?).map_err(|_| Error::Crypto)?; + if self.name_bytes == 0 || self.name_bytes & 1 != 0 { + return Err(Error::Crypto); + } + let end = self + .position + .checked_add(12) + .and_then(|n| n.checked_add(self.name_bytes)) + .ok_or(Error::Crypto)?; + if end > self.used { + return Err(Error::Crypto); + } + if self.next == 0 { + self.next = self.used; + } else { + if self.next & 3 != 0 || self.next < 12 + self.name_bytes { + return Err(Error::Crypto); + } + self.next = self.position.checked_add(self.next).ok_or(Error::Crypto)?; + if self.next.checked_add(12).is_none_or(|n| n > self.used) { + return Err(Error::Crypto); + } + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "directory_records_tests.rs"] +mod tests; diff --git a/src/files/directory_records_tests.rs b/src/files/directory_records_tests.rs new file mode 100644 index 0000000..caf37c5 --- /dev/null +++ b/src/files/directory_records_tests.rs @@ -0,0 +1,93 @@ +//! DE: Öffentliche NT-Layoutfixtures, Grenzen und überlappende/abgeschnittene Records. +//! EN: Public NT layout fixtures, bounds and overlapping/truncated records. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}; + +#[test] +fn actual_cursor_is_prelocked_and_two_records_end_exactly_at_reported_bytes() { + let mut words = SecretWorkspace::::zeroed(8).unwrap(); + words + .expose_mut() + .copy_from_slice(&[16, 9, 2, 65, 0, 10, 4, 0xdc00_d800]); + let mut cursor = SecretState::new(Records::default()).unwrap(); + crate::locked_owner_test_support::locked(cursor.get()); + cursor.get_mut().begin(32, words.expose()).unwrap(); + cursor.get_mut().header(words.expose()).unwrap(); + assert_eq!( + ( + cursor.get().position, + cursor.get().next, + cursor.get().name_bytes + ), + (0, 16, 2) + ); + cursor.get_mut().position = cursor.get().next; + cursor.get_mut().header(words.expose()).unwrap(); + assert_eq!( + ( + cursor.get().position, + cursor.get().next, + cursor.get().name_bytes + ), + (16, 32, 4) + ); + cursor.get_mut().position = cursor.get().next; + assert!(cursor.get_mut().header(words.expose()).is_err()); + crate::locked_owner_test_support::locked(cursor.get()); +} + +#[test] +fn malformed_lengths_offsets_and_unavailable_prefixes_are_errors() { + for (next, bytes, count) in [ + (0, 0, 16), + (0, 3, 16), + (0, 6, 16), + (0, u32::MAX, 16), + (4, 2, 32), + (12, 2, 32), + (18, 2, 32), + (28, 2, 32), + (32, 2, 32), + (u32::MAX, 2, 32), + ] { + let mut words = SecretWorkspace::::zeroed(8).unwrap(); + words.expose_mut()[0] = next; + words.expose_mut()[2] = bytes; + let mut cursor = SecretState::new(Records::default()).unwrap(); + cursor.get_mut().begin(count, words.expose()).unwrap(); + assert!(cursor.get_mut().header(words.expose()).is_err()); + } + let words = SecretWorkspace::::zeroed(4).unwrap(); + for count in [0, 1, 11, 17, usize::MAX] { + let mut cursor = SecretState::new(Records::default()).unwrap(); + assert!(cursor.get_mut().begin(count, words.expose()).is_err()); + } +} + +#[test] +fn corrupt_later_record_and_maximum_cursor_never_become_success_or_panic() { + let mut words = SecretWorkspace::::zeroed(8).unwrap(); + words + .expose_mut() + .copy_from_slice(&[16, 0, 2, 65, 0, 0, 6, 66]); + let mut cursor = SecretState::new(Records::default()).unwrap(); + cursor.get_mut().begin(32, words.expose()).unwrap(); + cursor.get_mut().header(words.expose()).unwrap(); + cursor.get_mut().position = cursor.get().next; + assert!(cursor.get_mut().header(words.expose()).is_err()); + cursor.get_mut().position = usize::MAX; + assert!(cursor.get_mut().header(words.expose()).is_err()); + cursor.get_mut().position = 1; + assert!(cursor.get_mut().header(words.expose()).is_err()); + cursor.get_mut().zeroize(); + assert_eq!( + ( + cursor.get().used, + cursor.get().position, + cursor.get().next, + cursor.get().name_bytes + ), + (0, 0, 0, 0) + ); +} diff --git a/src/files/locked_wide.rs b/src/files/locked_wide.rs index a6d4e31..bf7597e 100644 --- a/src/files/locked_wide.rs +++ b/src/files/locked_wide.rs @@ -9,6 +9,7 @@ use zeroize::{Zeroize, ZeroizeOnDrop}; struct State<'a> { iterator: EncodeWide<'a>, + native: Option<&'a [u16]>, len: usize, position: usize, } @@ -16,6 +17,7 @@ impl Drop for State<'_> { fn drop(&mut self) { // DE/EN: Nur öffentliche leere Ersatzgeometrie / public empty replacement geometry only. self.iterator = OsStr::new("").encode_wide(); + self.native = None; self.len.zeroize(); self.position.zeroize(); } @@ -28,6 +30,7 @@ impl<'a> LockedWide<'a> { pub(super) fn new(source: &'a OsStr) -> Result { let mut out = Self(SecretState::new(State { iterator: OsStr::new("").encode_wide(), + native: None, len: 0, position: 0, })?); @@ -39,6 +42,13 @@ impl<'a> LockedWide<'a> { state.iterator = source.encode_wide(); Ok(out) } + pub(super) fn from_units(source: &'a [u16]) -> Result { + let mut out = Self::new(OsStr::new(""))?; + let state = out.0.get_mut(); + state.native = Some(source); + state.len = source.len(); + Ok(out) + } pub(super) fn len(&self) -> usize { self.0.get().len } @@ -47,7 +57,10 @@ impl<'a> LockedWide<'a> { } pub(super) fn next_unit(&mut self) -> Result> { let state = self.0.get_mut(); - let next = state.iterator.next(); + let next = match state.native { + Some(units) => units.get(state.position).copied(), + None => state.iterator.next(), + }; if next.is_some() { state.position = state.position.checked_add(1).ok_or(Error::MemoryLock)?; if state.position > state.len { diff --git a/src/files/mod.rs b/src/files/mod.rs index 68af0f5..b5406a0 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -22,6 +22,8 @@ mod confidential_path_index; mod confidential_text; mod decrypt; mod decrypt_v2; +#[cfg(any(test, windows))] +mod directory_records; mod encrypt; mod encrypt_header; mod encrypt_v2; @@ -36,9 +38,13 @@ mod locked_owner_tests; mod locked_wide; #[cfg(target_os = "linux")] mod native_directory; -#[cfg(target_os = "linux")] +#[cfg(windows)] +mod native_directory_windows; +#[cfg(any(target_os = "linux", windows))] mod native_names; mod native_path; +#[cfg(windows)] +mod native_wtf8; mod original; mod output; mod output_guard; @@ -67,6 +73,8 @@ mod unicode_fold; mod walk; #[cfg(target_os = "linux")] mod walk_linux; +#[cfg(any(target_os = "linux", windows))] +mod walk_native; use std::io::BufReader; use std::path::Path; @@ -222,3 +230,7 @@ pub fn inspect_v2(source: &Path) -> Result { #[cfg(all(test, windows))] #[path = "windows_directory_adapter_tests.rs"] mod windows_directory_adapter_tests; + +#[cfg(all(test, windows))] +#[path = "walk_windows_tests.rs"] +mod walk_windows_tests; diff --git a/src/files/native_directory_windows.rs b/src/files/native_directory_windows.rs new file mode 100644 index 0000000..29de537 --- /dev/null +++ b/src/files/native_directory_windows.rs @@ -0,0 +1,70 @@ +//! DE: NT-Namensrecords vollständig in vorab gesperrtem Status-/Parser-/Ausgabespeicher. +//! EN: NT name records entirely in prelocked status/parser/output storage. +use super::{directory_records::Records, native_path::NativePath}; +use crate::{ + Result, + crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State { + reader: pqkeep_platform::DirectoryRead, + words: SecretWorkspace, + name: NativePath, + records: Records, +} +impl Drop for State { + fn drop(&mut self) { + self.words.zeroize(); + self.name.zeroize(); + self.records.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +pub(super) fn visit( + path: &NativePath, + mut consume: impl FnMut(&[u16]) -> Result<()>, +) -> Result<()> { + let mut storage = SecretState::new(State { + reader: pqkeep_platform::DirectoryRead::empty(), + words: SecretWorkspace::zeroed(16_388)?, + name: NativePath::prepare()?, + records: Records::default(), + })?; + let state = storage.get_mut(); + path.directory_into(&mut state.reader)?; + while state.advance()? { + #[cfg(test)] + tests::observe(state); + let encoded = state.name.encoded()?; + let units = &encoded[..encoded.len() - 1]; + if units != [46] && units != [46, 46] { + consume(units)?; + } + } + Ok(()) +} + +impl State { + fn advance(&mut self) -> Result { + if self.records.position >= self.records.used { + let Some(count) = self.reader.capture(self.words.expose_mut())? else { + return Ok(false); + }; + self.records.begin(count, self.words.expose())?; + } + self.records.header(self.words.expose())?; + self.name.copy_words( + self.words.expose(), + self.records.position / 4 + 3, + self.records.name_bytes / 2, + )?; + self.records.position = self.records.next; + Ok(true) + } +} + +#[cfg(test)] +#[path = "native_directory_windows_tests.rs"] +mod tests; diff --git a/src/files/native_directory_windows_tests.rs b/src/files/native_directory_windows_tests.rs new file mode 100644 index 0000000..20c4295 --- /dev/null +++ b/src/files/native_directory_windows_tests.rs @@ -0,0 +1,115 @@ +//! DE: Tatsächliche NT-Traversierungsowner und rohe native Namensbytes beobachten. +//! EN: Observe actual NT traversal owners and raw native name units. +#![allow(clippy::unwrap_used)] +use super::*; +use std::{ + ffi::OsString, + os::windows::ffi::{OsStrExt, OsStringExt}, +}; + +fn physical(value: &T) { + crate::locked_owner_test_support::locked(value); + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(value).addr(); + for offset in (0..size_of_val(value)).step_by(region::page::size()) { + assert!(query.get_mut().is_locked(start + offset).unwrap()); + } + assert!( + query + .get_mut() + .is_locked(start + size_of_val(value) - 1) + .unwrap() + ); +} + +pub(super) fn observe(state: &State) { + physical(state); + state.words.assert_metadata_locked(); + physical(state.words.expose()); + physical(state.name.encoded().unwrap()); +} + +#[test] +fn actual_native_directory_visit_preserves_all_non_dot_utf16_names() { + let root = tempfile::tempdir().unwrap(); + for name in [ + OsString::from("a"), + OsString::from("😀ä"), + OsString::from_wide(&[0xd800]), + ] { + std::fs::write(root.path().join(name), b"public fixture").unwrap(); + } + let mut expected: Vec<_> = std::fs::read_dir(root.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().encode_wide().collect::>()) + .collect(); + let native = NativePath::from_path(root.path()).unwrap(); + let mut observed = Vec::new(); + visit(&native, |units| { + physical(units); + observed.push(units.to_vec()); + Ok(()) + }) + .unwrap(); + expected.sort(); + observed.sort(); + let equal = expected == observed; + assert!(equal); +} + +fn own_resources() -> (u32, usize) { + ( + pqkeep_platform::memory_fixture::own_handle_count().unwrap(), + crate::hardening::memlock::stats().locked_pages, + ) +} + +#[test] +fn actual_native_traversal_cleanup_after_success_callback_error_and_unwind_is_bounded() { + crate::locked_owner_test_support::isolated_test( + "files::native_directory_windows::tests::traversal_cleanup_child", + "PQKEEP_WINDOWS_NATIVE_TRAVERSAL_CHILD", + ); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn traversal_cleanup_child() { + assert_eq!( + std::env::var("PQKEEP_WINDOWS_NATIVE_TRAVERSAL_CHILD").unwrap(), + "1" + ); + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("public"), b"public fixture").unwrap(); + let native = NativePath::from_path(root.path()).unwrap(); + visit(&native, |_| Ok(())).unwrap(); + let baseline = own_resources(); + visit(&native, |_| Ok(())).unwrap(); + assert_eq!(own_resources(), baseline); + assert!(matches!( + visit(&native, |_| Err(crate::Error::Crypto)), + Err(crate::Error::Crypto) + )); + assert_eq!(own_resources(), baseline); + let result = std::panic::catch_unwind(|| { + let _ = visit(&native, |_| std::panic::resume_unwind(Box::new(()))); + }); + assert!(result.is_err()); + assert_eq!(own_resources(), baseline); + for path in [root.path().join("public"), root.path().join("missing")] { + { + let native = NativePath::from_path(&path).unwrap(); + let mut called = false; + assert!( + visit(&native, |_| { + called = true; + Ok(()) + }) + .is_err() + ); + assert!(!called); + } + assert_eq!(own_resources(), baseline); + } +} diff --git a/src/files/native_names.rs b/src/files/native_names.rs index d3aa433..2394a5f 100644 --- a/src/files/native_names.rs +++ b/src/files/native_names.rs @@ -1,6 +1,9 @@ //! DE: Native Verzeichnisnamen und Traversierungszustand in gesperrten Arenen. //! EN: Native directory names and traversal state in protected arenas. -use super::{native_path::NativePath, paths::MAX_ENTRIES}; +use super::{ + native_path::{NativePath, Unit}, + paths::MAX_ENTRIES, +}; use crate::{ Error, Result, crypto::{secret_state::SecretState, secret_workspace::SecretWorkspace}, @@ -11,11 +14,17 @@ use zeroize::{Zeroize, ZeroizeOnDrop}; struct Name { path: Option, directory: bool, + #[cfg(windows)] + key: Option, } impl Zeroize for Name { fn zeroize(&mut self) { self.path = None; self.directory.zeroize(); + #[cfg(windows)] + { + self.key = None; + } } } impl Drop for Name { @@ -66,6 +75,16 @@ pub(super) struct NativeNames(SecretState); mod sorting; impl NativeNames { + pub(super) fn read(root: &NativePath) -> Result { + let mut out = Self::prepare()?; + #[cfg(target_os = "linux")] + super::native_directory::visit(root, |name| out.push(name.to_bytes()))?; + #[cfg(windows)] + super::native_directory_windows::visit(root, |name| out.push(name))?; + out.sort()?; + Ok(out) + } + pub(super) fn prepare() -> Result { Ok(Self(SecretState::new(State { records: SecretWorkspace::zeroed(0)?, @@ -76,13 +95,17 @@ impl NativeNames { sort: Sort::default(), })?)) } - pub(super) fn push(&mut self, bytes: &[u8]) -> Result<()> { - if bytes.is_empty() || bytes.contains(&b'/') { + pub(super) fn push(&mut self, bytes: &[Unit]) -> Result<()> { + if bytes.is_empty() || bytes.contains(&Unit::from(b'/')) { return Err(Error::InvalidInput { field: "path" }); } let state = self.0.get_mut(); state.reserve()?; - state.records.expose_mut()[state.used].path = Some(NativePath::from_native(bytes)?); + let slot = &mut state.records.expose_mut()[state.used]; + if let Err(error) = slot.fill(bytes) { + slot.zeroize(); + return Err(error); + } state.order.expose_mut()[state.used] = state.used; state.used += 1; Ok(()) @@ -94,6 +117,41 @@ impl NativeNames { } state.name(state.position).map(Some) } + pub(super) fn current_text(&self) -> Result> { + let state = self.0.get(); + let record = state.record(state.position)?; + #[cfg(target_os = "linux")] + { + Ok(record + .path + .as_ref() + .ok_or(Error::Crypto)? + .c_str()? + .to_str() + .ok()) + } + #[cfg(windows)] + { + record.key.as_ref().ok_or(Error::Crypto)?.text() + } + } + pub(super) fn current_lossy(&self, prefix: &str) -> Result { + let name = self.current()?.ok_or(Error::Crypto)?; + #[cfg(target_os = "linux")] + { + use std::os::unix::ffi::OsStrExt; + super::confidential_os_text::joined_lossy( + prefix, + std::ffi::OsStr::from_bytes(name.c_str()?.to_bytes()), + ) + } + #[cfg(windows)] + { + let units = name.encoded()?; + super::confidential_os_text::joined_lossy_units(prefix, &units[..units.len() - 1]) + } + } + pub(super) fn advance(&mut self) -> Result<()> { let state = self.0.get_mut(); if state.position >= state.used { @@ -159,14 +217,7 @@ impl State { let mut order = SecretWorkspace::::zeroed(capacity)?; self.scan = 0; while self.scan < self.used { - records.expose_mut()[self.scan].path = Some( - self.records.expose()[self.scan] - .path - .as_ref() - .ok_or(Error::Crypto)? - .try_duplicate()?, - ); - records.expose_mut()[self.scan].directory = self.records.expose()[self.scan].directory; + records.expose_mut()[self.scan].copy_from(&self.records.expose()[self.scan])?; order.expose_mut()[self.scan] = self.order.expose()[self.scan]; self.scan += 1; } @@ -177,6 +228,50 @@ impl State { } } -#[cfg(test)] +#[cfg(all(test, target_os = "linux"))] #[path = "native_names_tests.rs"] mod tests; + +impl Name { + fn fill(&mut self, units: &[Unit]) -> Result<()> { + if self.path.is_some() { + return Err(Error::Crypto); + } + self.path = Some(NativePath::from_native(units)?); + #[cfg(windows)] + { + self.key = Some(super::native_wtf8::Key::from_units(units)?); + } + Ok(()) + } + fn copy_from(&mut self, source: &Self) -> Result<()> { + if self.path.is_some() { + return Err(Error::Crypto); + } + self.path = Some(source.path.as_ref().ok_or(Error::Crypto)?.try_duplicate()?); + #[cfg(windows)] + { + self.key = Some(source.key.as_ref().ok_or(Error::Crypto)?.try_duplicate()?); + } + self.directory = source.directory; + Ok(()) + } + fn key(&self) -> Result<&[u8]> { + #[cfg(target_os = "linux")] + { + self.path + .as_ref() + .ok_or(Error::Crypto)? + .c_str() + .map(std::ffi::CStr::to_bytes) + } + #[cfg(windows)] + { + Ok(self.key.as_ref().ok_or(Error::Crypto)?.bytes()) + } + } +} + +#[cfg(all(test, windows))] +#[path = "native_names_windows_tests.rs"] +mod windows_tests; diff --git a/src/files/native_names_sort.rs b/src/files/native_names_sort.rs index b8a76ed..a790e80 100644 --- a/src/files/native_names_sort.rs +++ b/src/files/native_names_sort.rs @@ -30,9 +30,9 @@ impl State { // DE: Originalindex erhält auch bei gleichen Pfaden die bisherige stabile Reihenfolge. // EN: Original indices retain the previous stable order even for equal paths. Ok(self - .name(a)? - .encoded()? - .cmp(self.name(b)?.encoded()?) + .record(a)? + .key()? + .cmp(self.record(b)?.key()?) .then(self.order.expose()[a].cmp(&self.order.expose()[b]))) } diff --git a/src/files/native_names_windows_tests.rs b/src/files/native_names_windows_tests.rs new file mode 100644 index 0000000..d3e511f --- /dev/null +++ b/src/files/native_names_windows_tests.rs @@ -0,0 +1,74 @@ +//! DE: Tatsächliche Windows-Namensarenen, Wachstum und stabile WTF8-Reihenfolge. +//! EN: Actual Windows name arenas, growth and stable WTF8 ordering. +#![allow(clippy::unwrap_used)] +use super::*; +use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + +fn physical(value: &T) { + crate::locked_owner_test_support::locked(value); + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(value).addr(); + for offset in (0..size_of_val(value)).step_by(region::page::size()) { + assert!(query.get_mut().is_locked(start + offset).unwrap()); + } + assert!( + query + .get_mut() + .is_locked(start + size_of_val(value) - 1) + .unwrap() + ); +} + +fn owners(names: &NativeNames) { + let state = names.0.get(); + physical(state); + state.records.assert_metadata_locked(); + state.order.assert_metadata_locked(); + physical(state.records.expose()); + physical(state.order.expose()); + for record in &state.records.expose()[..state.used] { + physical(record.path.as_ref().unwrap().encoded().unwrap()); + physical(record.key.as_ref().unwrap().bytes()); + } +} + +#[test] +fn native_windows_arena_preserves_stable_std_order_flags_and_owners_through_growth() { + let mut names = NativeNames::prepare().unwrap(); + let mut expected = Vec::new(); + for index in (0..65).rev() { + let units = [65, 0xd800 + index % 9, 0xe000, 0xd800, 0xdc00]; + names.push(&units).unwrap(); + if index % 2 == 0 { + names.set_directory().unwrap(); + } + names.advance().unwrap(); + expected.push((OsString::from_wide(&units), index % 2 == 0)); + } + owners(&names); + for invalid in [&[][..], &[65, 0, 66][..], &[65, 47, 66][..]] { + assert!(names.push(invalid).is_err()); + } + names.rewind(); + names.sort().unwrap(); + expected.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, directory) in expected { + let equal = names + .0 + .get() + .record(names.0.get().position) + .unwrap() + .key() + .unwrap() + == name.as_encoded_bytes(); + assert!(equal); + assert_eq!(names.directory().unwrap(), directory); + names.advance().unwrap(); + } + assert!(names.current().unwrap().is_none()); + assert!(names.advance().is_err()); + names.rewind(); + assert!(names.current().unwrap().is_some()); + owners(&names); +} diff --git a/src/files/native_path.rs b/src/files/native_path.rs index 97a89cc..9364dd9 100644 --- a/src/files/native_path.rs +++ b/src/files/native_path.rs @@ -10,9 +10,9 @@ type Units = crate::crypto::SecretBytes; #[cfg(windows)] type Units = crate::crypto::secret_workspace::SecretWorkspace; #[cfg(unix)] -type Unit = u8; +pub(super) type Unit = u8; #[cfg(windows)] -type Unit = u16; +pub(super) type Unit = u16; struct State(Units); @@ -112,14 +112,6 @@ impl NativePath { Ok(()) } - #[cfg(target_os = "linux")] - pub(super) fn as_path(&self) -> Result<&Path> { - use std::os::unix::ffi::OsStrExt; - Ok(Path::new(std::ffi::OsStr::from_bytes( - self.c_str()?.to_bytes(), - ))) - } - #[cfg(target_os = "linux")] pub(super) fn joined(parent: &Self, leaf: &Self) -> Result { let base = parent.c_str()?.to_bytes(); diff --git a/src/files/native_path_join_windows.rs b/src/files/native_path_join_windows.rs new file mode 100644 index 0000000..b368a52 --- /dev/null +++ b/src/files/native_path_join_windows.rs @@ -0,0 +1,135 @@ +//! DE: Verbatim-Komponenten wie std neu aufbauen, direkt in gesperrten UTF16-Speicher. +//! EN: Rebuild verbatim components like std, directly in protected UTF16 storage. +//! DE/EN: Branch semantics: rust-lang/rust `library/std/src/path.rs::_push`, +//! `sys/path/windows_prefix.rs`; MIT OR Apache-2.0. Parent dot components are preserved. +use super::{ALT, COLON, NativePath, SEP, VERBATIM}; +use crate::{Error, Result, crypto::secret_state::SecretState}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct Cursor { + read: usize, + write: usize, + start: usize, + drive: bool, + separator: bool, +} +impl Drop for Cursor { + fn drop(&mut self) { + self.read.zeroize(); + self.write.zeroize(); + self.start.zeroize(); + self.drive.zeroize(); + self.separator.zeroize(); + } +} +impl ZeroizeOnDrop for Cursor {} + +impl Cursor { + fn prefix(&mut self, base: &[u16]) { + self.read = 4; + if base.get(4..7) == Some(&[85, 78, 67]) + && base.get(7).is_some_and(|unit| [SEP, ALT].contains(unit)) + { + self.read = 8; + while self.read < base.len() && base[self.read] != SEP { + self.read += 1; + } + self.start = self.read; + if self.read < base.len() { + self.read += 1; + while self.read < base.len() && base[self.read] != SEP { + self.read += 1; + } + if self.read == self.start + 1 { + self.read = self.start; + } + } + } else if base + .get(4) + .is_some_and(|unit| (65..=90).contains(unit) || (97..=122).contains(unit)) + && base.get(5) == Some(&COLON) + && base.get(6).is_none_or(|unit| [SEP, ALT].contains(unit)) + { + self.drive = true; + self.read = 6; + } else { + while self.read < base.len() && base[self.read] != SEP { + self.read += 1; + } + } + self.write = self.read; + self.separator = !self.drive; + } + + fn rebuild(&mut self, base: &[u16], target: &mut [u16]) { + self.prefix(base); + target[..self.write].copy_from_slice(&base[..self.read]); + if base + .get(self.read) + .is_some_and(|unit| [SEP, ALT].contains(unit)) + { + target[self.write] = SEP; + self.write += 1; + self.read += 1; + self.separator = false; + } + while self.read < base.len() { + self.start = self.read; + while self.read < base.len() && base[self.read] != SEP { + self.read += 1; + } + if self.read != self.start { + self.append(&base[self.start..self.read], target); + } + if self.read < base.len() { + self.read += 1; + } + } + } + + fn append(&mut self, part: &[u16], target: &mut [u16]) { + if self.separator { + target[self.write] = SEP; + self.write += 1; + } + target[self.write..self.write + part.len()].copy_from_slice(part); + self.write += part.len(); + self.separator = true; + } +} + +pub(super) fn joined(base: &[u16], name: &[u16]) -> Result { + if name.is_empty() + || name == [46] + || name == [46, 46] + || name.iter().any(|unit| [SEP, ALT, COLON].contains(unit)) + { + return Err(Error::InvalidInput { field: "path" }); + } + let mut cursor = SecretState::new(Cursor::default())?; + let capacity = base + .len() + .checked_add(name.len()) + .and_then(|n| n.checked_add(1)) + .ok_or(Error::MemoryLock)?; + let mut output = NativePath::prepare()?; + output.allocate(capacity)?; + let target = output.0.get_mut().0.expose_mut(); + let state = cursor.get_mut(); + if base.starts_with(VERBATIM) { + state.rebuild(base, target); + } else { + target[..base.len()].copy_from_slice(base); + state.write = base.len(); + state.separator = !(base.is_empty() + || base.last().is_some_and(|unit| [SEP, ALT].contains(unit)) + || base.len() == 2 + && base[1] == COLON + && ((65..=90).contains(&base[0]) || (97..=122).contains(&base[0]))); + } + state.append(name, target); + target[state.write] = 0; + output.0.get_mut().0.truncate(state.write + 1); + Ok(output) +} diff --git a/src/files/native_path_windows.rs b/src/files/native_path_windows.rs index 275985a..695ec10 100644 --- a/src/files/native_path_windows.rs +++ b/src/files/native_path_windows.rs @@ -4,6 +4,8 @@ //! `get_long_path(prefer_verbatim=true)`, MIT OR Apache-2.0; no cryptographic changes. use super::{Error, NativePath, Result}; +use crate::crypto::secret_state::SecretState; +use zeroize::{Zeroize, ZeroizeOnDrop}; const SEP: u16 = 92; const ALT: u16 = 47; @@ -76,3 +78,67 @@ fn with_prefix(absolute: &NativePath) -> Result { target[prefix.len()..len].copy_from_slice(tail); Ok(out) } + +#[derive(Default)] +struct CopyPosition { + base: usize, + count: usize, + read: usize, +} +impl Drop for CopyPosition { + fn drop(&mut self) { + self.base.zeroize(); + self.count.zeroize(); + self.read.zeroize(); + } +} +impl ZeroizeOnDrop for CopyPosition {} + +impl NativePath { + pub(in crate::files) fn directory_into( + &self, + output: &mut pqkeep_platform::DirectoryRead, + ) -> Result<()> { + let normalized = for_open(self)?; + output.open_into(normalized.as_ref().unwrap_or(self).encoded()?)?; + Ok(()) + } + + pub(in crate::files) fn copy_words( + &mut self, + words: &[u32], + base: usize, + count: usize, + ) -> Result<()> { + let mut position = SecretState::new(CopyPosition::default())?; + let state = position.get_mut(); + state.base = base; + state.count = count; + let needed = count.checked_add(1).ok_or(Error::MemoryLock)? / 2; + if base.checked_add(needed).is_none_or(|end| end > words.len()) { + return Err(Error::Crypto); + } + self.allocate(count)?; + while state.read < state.count { + let word = words[state.base + state.read / 2]; + let unit = u16::try_from((word >> (16 * (state.read % 2))) & 0xffff) + .map_err(|_| Error::Crypto)?; + if unit == 0 { + return Err(Error::InvalidInput { field: "path" }); + } + self.0.get_mut().0.expose_mut()[state.read] = unit; + state.read += 1; + } + Ok(()) + } + + pub(in crate::files) fn joined(parent: &Self, leaf: &Self) -> Result { + let base = parent.encoded()?; + let name = leaf.encoded()?; + let (base, name) = (&base[..base.len() - 1], &name[..name.len() - 1]); + joining::joined(base, name) + } +} + +#[path = "native_path_join_windows.rs"] +mod joining; diff --git a/src/files/native_path_windows_tests.rs b/src/files/native_path_windows_tests.rs index 9350e9b..f517197 100644 --- a/src/files/native_path_windows_tests.rs +++ b/src/files/native_path_windows_tests.rs @@ -111,3 +111,69 @@ fn native_adapters_reject_unterminated_and_interior_nul_input() { std::io::ErrorKind::InvalidInput ); } + +fn public_join_parents() -> Vec { + use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + let mut parents: Vec = [ + "", + "C:", + "c:", + "1:", + "C:\\", + "relative", + "relative/", + ".", + "..", + "//host/share", + "\\\\host\\share\\", + "\\\\?\\C:", + "\\\\?\\C:\\", + "\\\\?\\C:\\a\\\\b\\", + "\\\\?\\C:\\a\\.\\..\\b\\", + "\\\\?\\C:/a/b/", + "\\\\?\\UNC\\host\\share\\a\\\\b", + "\\\\?\\UNC\\host\\share", + "\\\\?\\UNC/host\\share\\", + "\\\\?\\UNC\\host\\", + "\\\\?\\UNC\\\\share", + "\\\\?\\device\\a\\\\b/", + "\\\\?\\", + "\\\\?\\C:relative", + r"\??\C:\a", + ] + .into_iter() + .map(OsString::from) + .collect(); + parents.push(OsString::from_wide(&[ + 92, 92, 63, 92, 67, 58, 92, 0xd800, 92, 92, + ])); + parents +} + +#[test] +fn protected_join_matches_std_drive_unc_verbatim_and_unpaired_units() { + use std::{ + ffi::OsString, + os::windows::ffi::{OsStrExt, OsStringExt}, + }; + for parent in public_join_parents() { + for name in [OsString::from("ä😀"), OsString::from_wide(&[0xdc00])] { + let reference = Path::new(&parent).join(&name); + let left = NativePath::from_path(Path::new(&parent)).unwrap(); + let right = NativePath::from_path(Path::new(&name)).unwrap(); + let result = NativePath::joined(&left, &right).unwrap(); + let expected: Vec<_> = reference.as_os_str().encode_wide().chain([0]).collect(); + let equal = result.encoded().unwrap() == expected; + assert!(equal, "public fixture mismatch: {parent:?}"); + crate::locked_owner_test_support::locked(result.encoded().unwrap()); + } + } +} + +#[test] +fn protected_join_refuses_non_leaf_inputs_instead_of_changing_roots() { + let parent = owned("C:\\public"); + for name in ["", ".", "..", "C:", "root/leaf", "root\\leaf"] { + assert!(NativePath::joined(&parent, &owned(name)).is_err()); + } +} diff --git a/src/files/native_wtf8.rs b/src/files/native_wtf8.rs new file mode 100644 index 0000000..98bb71e --- /dev/null +++ b/src/files/native_wtf8.rs @@ -0,0 +1,124 @@ +//! DE: Native UTF16-Sortierschlüssel direkt gesperrt wie OsString-WTF8 kodieren. +//! EN: Encode native UTF16 sort keys directly into locked OsString-compatible WTF8. +use crate::{ + Error, Result, + crypto::{SecretBytes, secret_state::SecretState}, +}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State { + bytes: SecretBytes, + read: usize, + write: usize, + scalar: u32, + valid: bool, +} +impl Drop for State { + fn drop(&mut self) { + self.bytes.zeroize(); + self.read.zeroize(); + self.write.zeroize(); + self.scalar.zeroize(); + self.valid.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +pub(super) struct Key(SecretState); +impl Key { + fn prepare() -> Result { + Ok(Self(SecretState::new(State { + bytes: SecretBytes::zeroed(0)?, + read: 0, + write: 0, + scalar: 0, + valid: true, + })?)) + } + pub(super) fn from_units(units: &[u16]) -> Result { + let mut out = Self::prepare()?; + let state = out.0.get_mut(); + state.bytes = SecretBytes::zeroed(units.len().checked_mul(3).ok_or(Error::MemoryLock)?)?; + while state.read < units.len() { + state.scalar = u32::from(units[state.read]); + state.read += 1; + state.combine(units)?; + state.encode()?; + } + state.bytes.truncate(state.write); + Ok(out) + } + pub(super) fn bytes(&self) -> &[u8] { + self.0.get().bytes.expose() + } + pub(super) fn text(&self) -> Result> { + if !self.0.get().valid { + return Ok(None); + } + std::str::from_utf8(self.bytes()) + .map(Some) + .map_err(|_| Error::Crypto) + } + pub(super) fn try_duplicate(&self) -> Result { + let mut out = Self::prepare()?; + out.0.get_mut().bytes = SecretBytes::from_slice(self.bytes())?; + out.0.get_mut().valid = self.0.get().valid; + Ok(out) + } +} +impl State { + fn combine(&mut self, units: &[u16]) -> Result<()> { + if (0xd800..=0xdbff).contains(&self.scalar) { + if units + .get(self.read) + .is_some_and(|unit| (0xdc00..=0xdfff).contains(unit)) + { + self.scalar = + 0x0001_0000 + ((self.scalar - 0xd800) << 10) + u32::from(units[self.read]) + - 0xdc00; + self.read = self.read.checked_add(1).ok_or(Error::MemoryLock)?; + } else { + self.valid = false; + } + } else if (0xdc00..=0xdfff).contains(&self.scalar) { + self.valid = false; + } + Ok(()) + } + fn byte(&mut self, value: u32) -> Result<()> { + *self + .bytes + .expose_mut() + .get_mut(self.write) + .ok_or(Error::Crypto)? = u8::try_from(value).map_err(|_| Error::Crypto)?; + self.write = self.write.checked_add(1).ok_or(Error::MemoryLock)?; + Ok(()) + } + fn encode(&mut self) -> Result<()> { + // DE: Kein privates UTF8-Zwischenarray; einzelne Skalare sind ABI-/Compilergrenze. + // EN: No private UTF8 scratch array; individual scalars are the ABI/compiler boundary. + match self.scalar { + 0..=0x7f => self.byte(self.scalar)?, + 0x80..=0x7ff => { + self.byte(0xc0 | (self.scalar >> 6))?; + self.byte(0x80 | (self.scalar & 0x3f))?; + } + 0x800..=0xffff => { + self.byte(0xe0 | (self.scalar >> 12))?; + self.byte(0x80 | ((self.scalar >> 6) & 0x3f))?; + self.byte(0x80 | (self.scalar & 0x3f))?; + } + _ => { + self.byte(0xf0 | (self.scalar >> 18))?; + self.byte(0x80 | ((self.scalar >> 12) & 0x3f))?; + self.byte(0x80 | ((self.scalar >> 6) & 0x3f))?; + self.byte(0x80 | (self.scalar & 0x3f))?; + } + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "native_wtf8_tests.rs"] +mod tests; diff --git a/src/files/native_wtf8_tests.rs b/src/files/native_wtf8_tests.rs new file mode 100644 index 0000000..b7fccb4 --- /dev/null +++ b/src/files/native_wtf8_tests.rs @@ -0,0 +1,73 @@ +//! DE: Öffentliche std-WTF8-Referenz einschließlich aller einzelnen UTF16-Einheiten. +//! EN: Public std WTF8 oracle, including every individual UTF16 unit. +#![allow(clippy::unwrap_used)] +use super::*; +use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + +fn reference(units: &[u16]) { + let expected = OsString::from_wide(units); + let key = Key::from_units(units).unwrap(); + let equal = key.bytes() == expected.as_encoded_bytes(); + assert!(equal); + let equal = key.text().unwrap() == expected.to_str(); + assert!(equal); +} + +#[test] +fn every_utf16_unit_and_paired_mixed_boundaries_match_std_encoded_bytes() { + reference(&[]); + for unit in 0..=u16::MAX { + reference(&[unit]); + } + for units in [ + &[0xd800, 0xdc00][..], + &[0xdbff, 0xdfff][..], + &[0xd800, 65, 0xdbff, 0xdfff, 0xdc00][..], + &[0xd800, 0xd800, 0xdc00, 0xdc00][..], + &[0xe000, 0xd800, 0xdc00][..], + ] { + reference(units); + } + let mut seed = 7_u32; + for length in 0..128 { + let units: Vec<_> = (0..length) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + u16::try_from(seed & 0xffff).unwrap() + }) + .collect(); + reference(&units); + } +} + +fn locked(key: &Key) { + crate::locked_owner_test_support::locked(key.0.get()); + crate::locked_owner_test_support::locked(key.bytes()); + key.0.get().bytes.assert_metadata_locked(); + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + for (start, len) in [ + ( + std::ptr::from_ref(key.0.get()).addr(), + size_of_val(key.0.get()), + ), + (key.bytes().as_ptr().addr(), key.bytes().len()), + ] { + assert!(query.get_mut().is_locked(start).unwrap()); + assert!(query.get_mut().is_locked(start + len - 1).unwrap()); + } +} + +#[test] +fn actual_key_bytes_and_retained_encoder_state_stay_locked_through_move_and_copy() { + let key = Key::from_units(&[65, 0xd800, 0xdc00, 0xdfff]).unwrap(); + locked(&key); + let moved = Box::new(key); + locked(&moved); + let copy = moved.try_duplicate().unwrap(); + locked(©); + let equal = moved.bytes() == copy.bytes(); + assert!(equal); + assert!(!std::ptr::eq(moved.bytes().as_ptr(), copy.bytes().as_ptr())); + assert!(copy.text().unwrap().is_none()); +} diff --git a/src/files/source_entries.rs b/src/files/source_entries.rs index c38351c..868dde0 100644 --- a/src/files/source_entries.rs +++ b/src/files/source_entries.rs @@ -77,11 +77,33 @@ impl SourceEntries { abs: &Path, directory: bool, bytes: u64, + ) -> Result<()> { + self.push_with(rel, directory, bytes, || { + super::native_path::NativePath::from_path(abs) + }) + } + + pub(super) fn push_native( + &mut self, + rel: &str, + abs: &super::native_path::NativePath, + directory: bool, + bytes: u64, + ) -> Result<()> { + self.push_with(rel, directory, bytes, || abs.try_duplicate()) + } + + fn push_with( + &mut self, + rel: &str, + directory: bool, + bytes: u64, + path: impl FnOnce() -> Result, ) -> Result<()> { let state = self.0.get_mut(); state.reserve()?; let slot = &mut state.records.expose_mut()[state.used]; - if let Err(error) = slot.fill(rel, abs, directory, bytes) { + if let Err(error) = slot.fill_with(rel, path, directory, bytes) { slot.zeroize(); return Err(error); } diff --git a/src/files/source_entry.rs b/src/files/source_entry.rs index 7826328..79e8f7c 100644 --- a/src/files/source_entry.rs +++ b/src/files/source_entry.rs @@ -3,7 +3,6 @@ use super::{ConfidentialText, native_path::NativePath, paths}; use crate::{Error, Result, crypto::SecretBytes}; -use std::path::Path; use zeroize::{Zeroize, ZeroizeOnDrop}; #[derive(Default)] @@ -32,10 +31,10 @@ impl ZeroizeOnDrop for SourceEntry {} impl SourceEntry { // DE: Nur bereits gesperrte Arenaslots befüllen; keine privaten Record-Rückgaben. // EN: Populate only prelocked arena slots; no private record return values. - pub(super) fn fill( + pub(super) fn fill_with( &mut self, rel: &str, - abs: &Path, + path: impl FnOnce() -> Result, directory: bool, bytes: u64, ) -> Result<()> { @@ -43,7 +42,7 @@ impl SourceEntry { return Err(Error::Crypto); } self.rel = Some(ConfidentialText::from_text(rel)?); - self.abs = Some(NativePath::from_path(abs)?); + self.abs = Some(path()?); self.directory = directory; self.bytes = bytes; Ok(()) diff --git a/src/files/source_metadata.rs b/src/files/source_metadata.rs index 2c5c4db..d23c50f 100644 --- a/src/files/source_metadata.rs +++ b/src/files/source_metadata.rs @@ -16,6 +16,11 @@ impl Metadata { path.metadata_into(output.0.get_mut())?; Ok(output) } + pub(super) fn read_native(path: &NativePath) -> Result { + let mut output = Self(SecretState::new(pqkeep_platform::SourceMetadata::empty())?); + path.metadata_into(output.0.get_mut())?; + Ok(output) + } pub(super) fn is_file(&self) -> bool { self.0.get().is_file() } diff --git a/src/files/walk.rs b/src/files/walk.rs index dc928a6..28555cc 100644 --- a/src/files/walk.rs +++ b/src/files/walk.rs @@ -8,10 +8,12 @@ #[cfg(target_os = "linux")] use super::walk_linux::collect_tree; -#[cfg(not(target_os = "linux"))] +#[cfg(windows)] +use super::walk_native::collect_tree; +#[cfg(not(any(target_os = "linux", windows)))] use std::fs; use std::path::Path; -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] use std::path::PathBuf; use super::paths::{self, MAX_ENTRIES}; @@ -122,7 +124,7 @@ pub(crate) fn collect_under( } /// DE: Inhalt von `root` mit Präfix `base` anhängen. EN: Append the content of `root` with prefix `base`. -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] fn collect_tree( root: &Path, base: &str, @@ -150,7 +152,7 @@ fn collect_tree( Ok(()) } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", windows)))] fn visit( child: &fs::DirEntry, prefix: &str, diff --git a/src/files/walk_linux.rs b/src/files/walk_linux.rs index abed6e9..bc9e3e9 100644 --- a/src/files/walk_linux.rs +++ b/src/files/walk_linux.rs @@ -1,98 +1,6 @@ -//! DE: Verzeichnisnamen, Sortierung und Rekursionsrecords ohne gewöhnliche FS-Puffer. -//! EN: Directory names, sorting and recursion records without ordinary FS buffers. -use super::{ - ConfidentialText, SkipReason, SkippedEntries, confidential_os_text, native_directory, - native_names::NativeNames, native_path::NativePath, paths, source_entries::SourceEntries, - source_metadata::Metadata, -}; -use crate::{Error, Result}; -use std::{ffi::OsStr, os::unix::ffi::OsStrExt, path::Path}; - -pub(super) fn collect_tree( - root: &Path, - prefix: &str, - entries: &mut SourceEntries, - skipped: &mut SkippedEntries, -) -> Result<()> { - let root = NativePath::from_path(root).map_err(|error| match error { - Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), - other => other, - })?; - let prefix = ConfidentialText::from_text(prefix)?; - collect_native(&root, &prefix, entries, skipped) -} - -fn collect_native( - root: &NativePath, - prefix: &ConfidentialText, - entries: &mut SourceEntries, - skipped: &mut SkippedEntries, -) -> Result<()> { - if !Metadata::read(root.as_path()?)?.is_dir() { - return Err(Error::InvalidInput { field: "source" }); - } - let mut names = NativeNames::prepare()?; - native_directory::visit(root, |name| names.push(name.to_bytes()))?; - names.sort()?; - while let Some(name) = names.current()? { - if visit(root, prefix.expose()?, name, entries, skipped)? { - names.set_directory()?; - } - names.advance()?; - } - // DE: Wie bisher erst alle direkten Kinder, danach Verzeichnisse alphabetisch. - // EN: Preserve direct-child processing followed by alphabetical directory descent. - names.rewind(); - while let Some(name) = names.current()? { - if names.directory()? { - let child = NativePath::joined(root, name)?; - let name = name.c_str()?.to_str().map_err(|_| Error::Crypto)?; - let relative = ConfidentialText::joined(prefix.expose()?, name)?; - let child_prefix = ConfidentialText::joined(relative.expose()?, "/")?; - collect_native(&child, &child_prefix, entries, skipped)?; - } - names.advance()?; - } - Ok(()) -} - -fn visit( - root: &NativePath, - prefix: &str, - name: &NativePath, - entries: &mut SourceEntries, - skipped: &mut SkippedEntries, -) -> Result { - let bytes = name.c_str()?.to_bytes(); - let Ok(name_text) = std::str::from_utf8(bytes) else { - skipped.push( - confidential_os_text::joined_lossy(prefix, OsStr::from_bytes(bytes))?, - SkipReason::NonUtf8Name, - )?; - return Ok(false); - }; - let relative = ConfidentialText::joined(prefix, name_text)?; - if paths::validate_only(relative.expose()?).is_err() { - skipped.push(relative, SkipReason::InvalidName)?; - return Ok(false); - } - let absolute = NativePath::joined(root, name)?; - let kind = Metadata::read(absolute.as_path()?)?; - if kind.is_symlink() { - skipped.push(relative, SkipReason::Symlink)?; - } else if kind.is_dir() || kind.is_file() { - entries.push( - relative.expose()?, - absolute.as_path()?, - kind.is_dir(), - if kind.is_file() { kind.bytes() } else { 0 }, - )?; - return Ok(kind.is_dir()); - } else { - skipped.push(relative, SkipReason::Special)?; - } - Ok(false) -} +//! DE: Bestehenden Linux-Einstieg/Testnamen beim gemeinsamen Walker erhalten. +//! EN: Preserve the existing Linux entry/test names with the shared walker. +pub(super) use super::walk_native::collect_tree; #[cfg(test)] #[path = "walk_linux_tests.rs"] diff --git a/src/files/walk_linux_tests.rs b/src/files/walk_linux_tests.rs index 4d52cc3..5b86fec 100644 --- a/src/files/walk_linux_tests.rs +++ b/src/files/walk_linux_tests.rs @@ -1,7 +1,11 @@ //! DE: Echte Bäume, Sortier-/Skip-Vertrag und maximale erlaubte Rekursion. //! EN: Actual trees, sorting/skip contract and maximum permitted recursion. #![allow(clippy::unwrap_used)] -use super::*; +use crate::{ + Error, + files::{SkipReason, paths}, +}; +use std::path::Path; use std::{ ffi::OsStr, os::unix::{ffi::OsStrExt, fs::symlink}, diff --git a/src/files/walk_native.rs b/src/files/walk_native.rs new file mode 100644 index 0000000..593abce --- /dev/null +++ b/src/files/walk_native.rs @@ -0,0 +1,89 @@ +//! DE: Linux-/Windows-Quellen ohne gewöhnliche native FS-/Traversal-Puffer. +//! EN: Linux/Windows sources without ordinary native FS/traversal buffers. +use super::{ + ConfidentialText, SkipReason, SkippedEntries, native_names::NativeNames, + native_path::NativePath, paths, source_entries::SourceEntries, source_metadata::Metadata, +}; +use crate::{Error, Result}; +use std::path::Path; + +pub(super) fn collect_tree( + root: &Path, + prefix: &str, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result<()> { + let root = NativePath::from_path(root).map_err(|error| match error { + Error::InvalidInput { field: "path" } => Error::Io(std::io::ErrorKind::InvalidInput), + other => other, + })?; + let prefix = ConfidentialText::from_text(prefix)?; + collect_native(&root, &prefix, entries, skipped) +} + +fn collect_native( + root: &NativePath, + prefix: &ConfidentialText, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result<()> { + if !Metadata::read_native(root)?.is_dir() { + return Err(Error::InvalidInput { field: "source" }); + } + let mut names = NativeNames::read(root)?; + while names.current()?.is_some() { + if visit(root, prefix.expose()?, &names, entries, skipped)? { + names.set_directory()?; + } + names.advance()?; + } + // DE: Wie bisher erst alle direkten Kinder, danach Verzeichnisse alphabetisch. + // EN: Preserve direct-child processing followed by alphabetical directory descent. + names.rewind(); + while let Some(name) = names.current()? { + if names.directory()? { + let child = NativePath::joined(root, name)?; + let name = names.current_text()?.ok_or(Error::Crypto)?; + let relative = ConfidentialText::joined(prefix.expose()?, name)?; + let child_prefix = ConfidentialText::joined(relative.expose()?, "/")?; + collect_native(&child, &child_prefix, entries, skipped)?; + } + names.advance()?; + } + Ok(()) +} + +fn visit( + root: &NativePath, + prefix: &str, + names: &NativeNames, + entries: &mut SourceEntries, + skipped: &mut SkippedEntries, +) -> Result { + let name = names.current()?.ok_or(Error::Crypto)?; + let Some(name_text) = names.current_text()? else { + skipped.push(names.current_lossy(prefix)?, SkipReason::NonUtf8Name)?; + return Ok(false); + }; + let relative = ConfidentialText::joined(prefix, name_text)?; + if paths::validate_only(relative.expose()?).is_err() { + skipped.push(relative, SkipReason::InvalidName)?; + return Ok(false); + } + let absolute = NativePath::joined(root, name)?; + let kind = Metadata::read_native(&absolute)?; + if kind.is_symlink() { + skipped.push(relative, SkipReason::Symlink)?; + } else if kind.is_dir() || kind.is_file() { + entries.push_native( + relative.expose()?, + &absolute, + kind.is_dir(), + if kind.is_file() { kind.bytes() } else { 0 }, + )?; + return Ok(kind.is_dir()); + } else { + skipped.push(relative, SkipReason::Special)?; + } + Ok(false) +} diff --git a/src/files/walk_windows_tests.rs b/src/files/walk_windows_tests.rs new file mode 100644 index 0000000..d3705c5 --- /dev/null +++ b/src/files/walk_windows_tests.rs @@ -0,0 +1,78 @@ +//! DE: Echte Windows-Traversierung mit Wachstum, WTF8-Reihenfolge und Skip-Namen. +//! EN: Actual Windows traversal with growth, WTF8 order and skipped names. +#![allow(clippy::unwrap_used)] +use crate::files::{SkipReason, paths}; +use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + +fn fixtures(root: &std::path::Path) -> Vec<(OsString, SkipReason)> { + for directory in ["ad", "zd"] { + std::fs::create_dir(root.join(directory)).unwrap(); + std::fs::write(root.join(directory).join("file"), b"public fixture").unwrap(); + } + for index in 0..65 { + std::fs::write(root.join(format!("file-{index:03}")), b"public fixture").unwrap(); + } + let skips = vec![ + (OsString::from_wide(&[0xd800]), SkipReason::NonUtf8Name), + ( + OsString::from(format!("\u{e000}{}", "ä".repeat(128))), + SkipReason::InvalidName, + ), + ( + OsString::from(format!("\u{10000}{}", "ä".repeat(128))), + SkipReason::InvalidName, + ), + ]; + for (name, _) in &skips { + std::fs::write(root.join(name), b"public fixture").unwrap(); + } + skips +} + +#[test] +fn native_windows_tree_keeps_files_and_std_wtf8_order_of_lossy_and_invalid_skips() { + let root = tempfile::tempdir().unwrap(); + let mut expected = fixtures(root.path()); + expected.sort_by(|a, b| a.0.cmp(&b.0)); + let (entries, skipped) = super::walk::collect_dir(root.path()).unwrap(); + assert_eq!(entries.len(), 69); + assert_eq!(skipped.len(), expected.len()); + for (entry, (path, reason)) in skipped.try_iter().unwrap().zip(expected) { + let entry = entry.unwrap(); + let equal = entry.path().unwrap() == path.to_string_lossy(); + assert!(equal); + assert_eq!(entry.reason().unwrap(), reason); + } + let mut previous: Option = None; + let mut files = 0; + for entry in entries.try_iter().unwrap() { + let entry = entry.unwrap(); + if let Some(previous) = &previous { + assert!(previous.as_str() < entry.path().unwrap()); + } + if !entry.is_directory() { + files += 1; + assert_eq!(entry.size(), 14); + } + previous = Some(entry.path().unwrap().to_owned()); + } + assert_eq!(files, 67); +} + +#[test] +fn native_windows_depth_boundary_rejects_the_next_directory_without_descending() { + let root = tempfile::tempdir().unwrap(); + let mut directory = root.path().to_path_buf(); + for _ in 0..=paths::MAX_DEPTH { + directory.push("d"); + } + std::fs::create_dir_all(&directory).unwrap(); + std::fs::write(directory.join("must-not-be-visited"), b"public fixture").unwrap(); + let (entries, skipped) = super::walk::collect_dir(root.path()).unwrap(); + assert_eq!(entries.len(), paths::MAX_DEPTH); + assert_eq!(skipped.len(), 1); + assert_eq!( + skipped.get(0).unwrap().reason().unwrap(), + SkipReason::InvalidName + ); +} From c03f8fded8ae771aa75fc93f086ef6cef48e12ee Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:52:38 +0100 Subject: [PATCH 22/26] Preserve std semantics for bare verbatim drive joins DE: Tatsachlicher Windows-Referenztest am8913f5c findet falsche Laufwerksannahme bei barem Verbatim-C:-Praefix. std is_drive gilt nur fuer Disk, nicht VerbatimDisk. Falsches Flag entfernen; unveraenderten Oracle beibehalten. Strenge Windows-Cross-Lints beider Featurekonfigurationen und unveraenderte Quellen geprueft. EN: Correct the real native join mismatch without weakening or removing the std oracle. No new unsafe, dependency or privilege change. Complete original failure retained; full native rerun required. Main integration staged tree and working sources remain unchanged. Refs #147 --- docs/security/WINDOWS_TRAVERSAL_VALIDATION.md | 14 ++++++++++++++ src/files/native_path_join_windows.rs | 7 +++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md index b4ecf70..c6943d9 100644 --- a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md +++ b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md @@ -92,3 +92,17 @@ Sources / Quellen: - Existing pinned windows-sys0.61.2 FileNamesInformation/NtQueryDirectoryFile declarations. - Rust std `path.rs::_push`, `sys/path/windows_prefix.rs`, WTF8 OsString representation; local toolchain sources reviewed, native/MSRV checks still required. + + +## Native correction / Native Korrektur + +DE: Erster nativer Windows-Lauf am8913f5c:300 Tests bestanden, ein echter +std-Referenzvergleich fehlgeschlagen. Konkreter Fehler: bare `\\?\C:` wurde wie +gewöhnliches laufwerksrelatives `C:` behandelt. std::Prefix::is_drive gilt jedoch +nur für Disk, nicht VerbatimDisk. Verbatim-Rekonstruktion braucht deshalb nach +jedem Präfix ohne folgenden physischen Root-Trenner einen Trenner. Ungültige +Compiler-/Cross-Abnahme nicht als native Vollabnahme gezählt. +EN: Remove the incorrect protected drive flag; retain the exact failing std +oracle and all other cases unchanged. No weaker assertion, removed fixture, +new unsafe, fallback or privilege change. Original complete failure log retained; +corrected source-bound cross-lints and full native rerun remain required. diff --git a/src/files/native_path_join_windows.rs b/src/files/native_path_join_windows.rs index b368a52..40c899e 100644 --- a/src/files/native_path_join_windows.rs +++ b/src/files/native_path_join_windows.rs @@ -11,7 +11,6 @@ struct Cursor { read: usize, write: usize, start: usize, - drive: bool, separator: bool, } impl Drop for Cursor { @@ -19,7 +18,6 @@ impl Drop for Cursor { self.read.zeroize(); self.write.zeroize(); self.start.zeroize(); - self.drive.zeroize(); self.separator.zeroize(); } } @@ -51,7 +49,6 @@ impl Cursor { && base.get(5) == Some(&COLON) && base.get(6).is_none_or(|unit| [SEP, ALT].contains(unit)) { - self.drive = true; self.read = 6; } else { while self.read < base.len() && base[self.read] != SEP { @@ -59,7 +56,9 @@ impl Cursor { } } self.write = self.read; - self.separator = !self.drive; + // DE: std::Prefix::is_drive meint nur Disk, NICHT VerbatimDisk. + // EN: std::Prefix::is_drive matches Disk only, NOT VerbatimDisk. + self.separator = true; } fn rebuild(&mut self, base: &[u16], target: &mut [u16]) { From 13f2cb4721b36c729c6219130cd23c50933580b6 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:06:33 +0100 Subject: [PATCH 23/26] Diagnose native Windows path oracle differences before long suites DE: Native c03-Wiederholung besteht300 Librarytests, findet zweiten unveraenderten Oracle-Fall bei Verbatim-C:/a/b/. Alle Abweichungen ausschliesslich oeffentlicher Fixtures sammeln; keine Bedingung oder Fixture abschwaechen. Bestehenden Windows-Job um fruehes natives Orakel und rustc-Version ergaenzen; alle vorherigen Gates/Rechte/Pinning erhalten. EN: Diagnose all native std path mismatches in one run, using public fixture units and std components only. Keep exactly the same equality and all fixtures. Seven source-bound checks pass, including both strict Windows lints and workflow policy/tests. No production Rust change, new unsafe, privilege or dependency. Native production acceptance remains failed/pending. Refs #147 --- .github/workflows/ci.yml | 11 +++++++++++ docs/security/WINDOWS_TRAVERSAL_VALIDATION.md | 11 +++++++++++ src/files/native_path_windows_tests.rs | 12 +++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d99d0c6..deefb57 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,6 +58,17 @@ jobs: # DE/EN: Isolierte Plattform-FFI nativ mit denselben strengen Regeln prüfen. # EN: Check isolated platform FFI natively under the same strict rules. - run: cargo fmt --check -p pqkeep-platform + # DE: Pfadsemantik vor langen Suiten nativ prüfen; alle bisherigen Gates bleiben erhalten. + # EN: Check native path semantics before long suites; retain every existing gate. + - name: Windows-Pfadorakel / Windows path oracle + if: matrix.os == 'windows-latest' + shell: bash + run: | + set -euo pipefail + rustc -vV + cargo test --locked --no-default-features --lib \ + files::native_path::windows::tests::protected_join_matches_std_drive_unc_verbatim_and_unpaired_units \ + -- --exact --nocapture --test-threads=1 - run: cargo clippy --all-targets --all-features --locked -p pqkeep-platform -- -D warnings - run: cargo test --all-features --locked -p pqkeep-platform - run: cargo clippy --all-targets --locked -- -D warnings diff --git a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md index c6943d9..fbc6fd4 100644 --- a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md +++ b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md @@ -106,3 +106,14 @@ EN: Remove the incorrect protected drive flag; retain the exact failing std oracle and all other cases unchanged. No weaker assertion, removed fixture, new unsafe, fallback or privilege change. Original complete failure log retained; corrected source-bound cross-lints and full native rerun remain required. + + +DE: Native Wiederholung c03f8fd bestätigt barem Verbatim-C:-Fix, zeigt jedoch +weiteren unveränderten Oracle-Fehler bei öffentlicher Fixture mit Slash nach dem +Verbatim-Laufwerk. Alle300 anderen Librarytests bestehen; keine Gesamtfreigabe. +EN: Collect all mismatching public fixtures with actual/expected UTF16 units and +std components, preserving exactly the same equality requirement and every +fixture. Only synthetic public data is formatted in this cfg(test) diagnostic. +Run this native oracle early in the existing Windows CI job, retain all prior +checks, readonly permissions and pinned checkout, and print actual rustc version. +No test success or production correction is claimed from diagnostic changes. diff --git a/src/files/native_path_windows_tests.rs b/src/files/native_path_windows_tests.rs index f517197..b8c753c 100644 --- a/src/files/native_path_windows_tests.rs +++ b/src/files/native_path_windows_tests.rs @@ -156,6 +156,7 @@ fn protected_join_matches_std_drive_unc_verbatim_and_unpaired_units() { ffi::OsString, os::windows::ffi::{OsStrExt, OsStringExt}, }; + let mut mismatches = Vec::new(); for parent in public_join_parents() { for name in [OsString::from("ä😀"), OsString::from_wide(&[0xdc00])] { let reference = Path::new(&parent).join(&name); @@ -164,10 +165,19 @@ fn protected_join_matches_std_drive_unc_verbatim_and_unpaired_units() { let result = NativePath::joined(&left, &right).unwrap(); let expected: Vec<_> = reference.as_os_str().encode_wide().chain([0]).collect(); let equal = result.encoded().unwrap() == expected; - assert!(equal, "public fixture mismatch: {parent:?}"); + if !equal { + // DE: Ausschließlich öffentliche Fixture-Einheiten, keine Nutzerpfade/Adressen. + // EN: Public fixture units only; never user paths or memory addresses. + mismatches.push(format!( + "fixture={parent:?}; actual={:?}; expected={expected:?}; components={:?}", + result.encoded().unwrap(), + Path::new(&parent).components() + )); + } crate::locked_owner_test_support::locked(result.encoded().unwrap()); } } + assert!(mismatches.is_empty(), "public fixtures: {mismatches:?}"); } #[test] From 3fad4e45c715735af04f88b2d1a81b1b0aa39152 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:18:29 +0100 Subject: [PATCH 24/26] Match linked std prefix semantics without private path copies DE: Native Gesamtdiagnose am13f findet genau zwei Slash-Abweichungen; MSVC nutzt Rust1.100, lokal/MSRV nutzt vorherige Praefixsemantik. Oeffentliche konstante std-Proben lesen die tatsaechliche Datentraeger-/UNC-Erkennung. Nie private Pfade oder Strings an std-Pfadkonvertierung geben. Alle Fixtures und das strenge Orakel bleiben bytegleich. EN: Match the actually linked std Windows prefix rules using public-only constant component probes. Preserve locked UTF16 destinations and the exact native oracle. Five source-bound checks and both strict Windows cross-lints pass at918 unchanged hashes. No new unsafe, dependency, OS operation or security setting. Full native rerun required. Original validated Main tree preserved. Refs #147 --- docs/security/WINDOWS_TRAVERSAL_VALIDATION.md | 20 ++++++++++++++++ src/files/native_path_join_windows.rs | 24 +++++++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md index fbc6fd4..90861d4 100644 --- a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md +++ b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md @@ -117,3 +117,23 @@ fixture. Only synthetic public data is formatted in this cfg(test) diagnostic. Run this native oracle early in the existing Windows CI job, retain all prior checks, readonly permissions and pinned checkout, and print actual rustc version. No test success or production correction is claimed from diagnostic changes. + + +DE: Vollständige öffentliche Diagnose am13f2cb4 zeigt genau zwei Abweichungen +(dieselbe Slash-Parent-Fixture mit zwei Blattnamen). Tatsächliches MSVC rustc +1.100.0/0ef1bc386 behandelt C:/a/b/ als ganzes Verbatim-Präfix; MSRV1.88 und +lokales1.99 erkennen dort noch einen Verbatim-Datenträger. Daher keine private +Pfadkopie an std und kein starres Versionsraten: zwei öffentliche konstante +Präfixproben lesen die tatsächlich eingebundene std-Semantik. Native UTF16- +Parser verwenden ausschließlich diese öffentlichen Laufzeitregeln; private +Einheiten/Recordowner bleiben vor Befüllung gesperrt. +EN: Public-only std component probes adapt drive/UNC slash recognition across +supported compiler versions. No private data enters std components/PathBuf; +no unsafe, new dependency, OS call, policy/privilege change or weakened oracle. +Exact original fixtures and equality requirement remain. Source-bound cross- +checks and corrected full native acceptance still required. + + +Versioned primary sources / Versionierte Primärquellen: +- https://github.com/rust-lang/rust/blob/1.88.0/library/std/src/sys/path/windows.rs +- https://github.com/rust-lang/rust/blob/1.100.0/library/std/src/sys/path/windows_prefix.rs diff --git a/src/files/native_path_join_windows.rs b/src/files/native_path_join_windows.rs index 40c899e..b6ad780 100644 --- a/src/files/native_path_join_windows.rs +++ b/src/files/native_path_join_windows.rs @@ -27,7 +27,9 @@ impl Cursor { fn prefix(&mut self, base: &[u16]) { self.read = 4; if base.get(4..7) == Some(&[85, 78, 67]) - && base.get(7).is_some_and(|unit| [SEP, ALT].contains(unit)) + && base + .get(7) + .is_some_and(|unit| *unit == SEP || *unit == ALT && slash_unc()) { self.read = 8; while self.read < base.len() && base[self.read] != SEP { @@ -47,7 +49,9 @@ impl Cursor { .get(4) .is_some_and(|unit| (65..=90).contains(unit) || (97..=122).contains(unit)) && base.get(5) == Some(&COLON) - && base.get(6).is_none_or(|unit| [SEP, ALT].contains(unit)) + && base + .get(6) + .is_none_or(|unit| *unit == SEP || *unit == ALT && slash_drive()) { self.read = 6; } else { @@ -132,3 +136,19 @@ pub(super) fn joined(base: &[u16], name: &[u16]) -> Result { output.0.get_mut().0.truncate(state.write + 1); Ok(output) } + +// DE: Nur öffentliche Konstanten an std geben; nie private Pfade/UTF16-Zwischenowner. +// EN: Pass only public constants to std; never private paths or intermediate UTF16 owners. +// DE: Rust1.100 erkennt C:/ im Verbatim-Präfix anders als MSRV1.88/1.99. +// EN: Rust1.100 interprets C:/ in a verbatim prefix differently from MSRV1.88/1.99. +fn slash_drive() -> bool { + use std::path::{Component, Path, Prefix}; + matches!(Path::new(r"\\?\C:/").components().next(), + Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimDisk(_))) +} + +fn slash_unc() -> bool { + use std::path::{Component, Path, Prefix}; + matches!(Path::new(r"\\?\UNC/host\share").components().next(), + Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimUNC(_, _))) +} From dd36dc57cf707de04da3c5a36e81cb1eed21a269 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:54:36 +0100 Subject: [PATCH 25/26] Prelock complete report records before producer output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Zähler, Scratch und Skip-/Absenderpräsenz vor Befüllung sperren; fallible Konstruktion und bewusste Getter, Caller gemeinsam migriert. Reale Verweigerung vor Stream-I/O und vollständiger Main361-Abgleich geprüft. Gemeinsamer R7/R8-Draft, keine Gesamtfreigabe. EN: Protect retained report state and checked arithmetic; preserve wire/CLI/JSON contracts. Source-bound integrated and consumer acceptance, no new unsafe/dependency. Other process/helper/transport obligations remain open. Refs #147. --- docs/SPEC.en.md | 6 + docs/SPEC.md | 6 + docs/security/PROTECTED_REPORT_VALIDATION.md | 79 ++++++ docs/security/SECRET_LIFETIME_INVENTORY.md | 11 + docs/security/WINDOWS_TRAVERSAL_VALIDATION.md | 19 ++ src/cli/check_cmd.rs | 12 +- src/cli/files_json.rs | 6 +- src/cli/list_cmd.rs | 6 +- src/cli/list_cmd_tests.rs | 11 +- src/cli/list_json.rs | 6 +- src/cli/report.rs | 9 +- src/cli/stream_cmd.rs | 7 +- src/files/decrypt.rs | 16 +- src/files/encrypt.rs | 11 +- src/files/fault_tests.rs | 2 +- src/files/mod.rs | 24 +- src/files/report.rs | 146 +++++++++++ src/files/report_tests.rs | 239 ++++++++++++++++++ src/files/scan.rs | 45 ++-- src/files/stream_v4.rs | 18 +- tests/files_anonymous.rs | 2 +- tests/files_check.rs | 4 +- tests/files_hidden_sender.rs | 12 +- tests/files_list_limits.rs | 6 +- tests/files_malicious.rs | 5 +- tests/files_many.rs | 8 +- tests/files_original.rs | 4 +- tests/files_output.rs | 4 +- tests/files_padding.rs | 2 +- tests/files_roundtrip.rs | 14 +- tests/files_signed.rs | 8 +- tests/files_stream_v4.rs | 6 +- tests/files_v2_kat.rs | 2 +- tests/files_v2_roundtrip.rs | 2 +- tests/integrity_headers.rs | 2 +- 35 files changed, 615 insertions(+), 145 deletions(-) create mode 100644 docs/security/PROTECTED_REPORT_VALIDATION.md create mode 100644 src/files/report.rs create mode 100644 src/files/report_tests.rs diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index 492e48f..f689869 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -7,6 +7,12 @@ > process/helper and other metadata acceptance remains open. See > [confidential sender identity](security/CONFIDENTIAL_SENDER_IDENTITY.md). +> R8 report record: prelock counts, arithmetic scratch and skip/sender presence +> together before population. `Report::empty()`/`with_counts()` are fallible; +> replace fields with `files()`/`directories()`/`bytes()`/`skipped()`/`signer()`; +> no `Default`. Prepare the report before producer output; lock refusal is an error. +> Ordinary CLI/JSON/transport buffers remain open. [Evidence and migration](security/PROTECTED_REPORT_VALIDATION.md). + > R8 follow-up in PR355: hidden signing-key construction, encoding and verification > use prelocked workspaces including identity-derived matrices and SHAKE128 scratch, > without ordinary Signature/cache copies in these paths. Implemented in the joint draft; diff --git a/docs/SPEC.md b/docs/SPEC.md index f502dbb..616368e 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -7,6 +7,12 @@ > Finale Prozess-/Helper- und übrige Metadatenabnahme weiter offen. > Details: [vertrauliche Absenderidentität](security/CONFIDENTIAL_SENDER_IDENTITY.md). +> R8-Berichtsrecord: Zähler, Rechenscratch und Skip-/Absenderpräsenz gemeinsam vor +> Befüllung sperren. `Report::empty()`/`with_counts()` sind fallibel; Felder durch +> `files()`/`directories()`/`bytes()`/`skipped()`/`signer()` ersetzen, kein `Default`. +> Bericht vor Produzentenausgabe vorbereiten; Speicherverweigerung ist ein Fehler. +> Gewöhnliche CLI-/JSON-/Transportpuffer bleiben offen. [Nachweise und Migration](security/PROTECTED_REPORT_VALIDATION.md). + > R8-Folgebaustein in PR355: Verborgener Signierschlüssel-Aufbau, Kodierung und > Verifikation verwenden vorab gesperrte Arbeitsflächen einschließlich Identitäts- > matrix und SHAKE128-Scratch; keine gewöhnlichen Signature-/Cache-Kopien in diff --git a/docs/security/PROTECTED_REPORT_VALIDATION.md b/docs/security/PROTECTED_REPORT_VALIDATION.md new file mode 100644 index 0000000..4e7cc8d --- /dev/null +++ b/docs/security/PROTECTED_REPORT_VALIDATION.md @@ -0,0 +1,79 @@ +# Protected report retention / Geschützte Berichtsretention + +DE: Lokaler M5-Teil des gemeinsamen R7/R8-Draft355. Keine Gesamtfreigabe: +CLI-/JSON-/Format-/Transportpuffer und übrige Prozess-/Helper-/Host-Verträge +bleiben ausdrücklich erforderlich. Implementierung und Abnahme unterscheiden. +EN: Protect the actual retained report, not only its nested identity/path bytes. +Root forbid(unsafe_code), wire bytes, CLI text and JSON schemas remain required. + +## Actual record / Tatsächlicher Record + +DE: Dateizahl, Ordnerzahl, Bytezahl, geprüfte Rechenscratchfelder, konkrete +Skip-Sammlung und Option des Absenders gemeinsam vor privater Befüllung in +SecretState sperren. Außen bleibt ein opaker Owner. Auch die Absenderpräsenz +und der Skip-Descriptor dürfen nicht als gewöhnlicher Report-Record verbleiben. +Keine frei kopierbaren Felder, kein Clone und kein infallibles Default. +EN: Construct only the public-empty State before locking. Fallible empty() +allocates no private record first. with_counts() copies caller-provided scalar +counts only after empty() succeeds; it does not prove authentication. Explicit +files()/directories()/bytes()/skipped()/signer() getters disclose metadata. +Scalar ABI/compiler copies remain explicit; known retained buffers are not +relabelled compiler temporaries. + +DE: Rechenüberläufe fehlschlagen lassen, bevor sichtbare bisherige Zähler geändert +werden. Beide Dateizähl-/Summenergebnisse in geschützten Scratchfeldern prüfen. +Zeroize löscht Zähler/Scratch und verschachtelte private Owner; SecretState +löscht danach die volle frühere Allokation einschließlich Padding vor Unlock. +Debug bleibt redigiert. Ein Move verschiebt nur den opaken Owner. +EN: Report allocation happens before producer output, not after publish/flush. +Encryption, extraction, authenticated scan/check/list and stream producers migrate +together. The stream's ordinary retained total is replaced by the protected +report count. No change to algorithms, KDF parameters or archive formats. + +## Rust migration / Rust-Migration + +DE: Report::default() und Struct-Literale ersetzen durch Report::empty()? bzw. +Report::with_counts(files, directories, bytes)?. Feldzugriffe durch obige Getter +ersetzen; signer() liefert Option<&SignedBy>, skipped() leiht die Sammlung aus. +Vorhandene Aufrufer/Tests einschließlich mehrzeiliger Methodenkaskaden gemeinsam +abgleichen. Diese fallible Metadaten-Typmigration ist Teil des freigegebenen Plans. +EN: CLI callers preserve the same JSON field names, numeric values, null signer +and text counts. They still require separate protected formatting/escaping and +transport workspaces. Copying a count into an ordinary serialization Summary or +serde_json::Value is not declared safe by protecting its source report. + +## Evidence still required / Noch erforderliche Nachweise + +DE: Neue Tests prüfen den tatsächlichen vollständigen Record und seine Felder, +Move, bewusstes Ausleihen, redigiertes Debug, Gleichheit, Überläufe und expliziten +Wipe während lebender Sperre. Begrenzte eigene Kinder prüfen Unwind/Cleanup und +exakte Sperr-/Linux-Kernel-Baseline. Reale Linux-Factory-Verweigerung durch nur +im eigenen Kind gesenktes Memlock-Limit; keine Verweigerung bloß aus Limit0 +ableiten, da kleine Owner bereits gesperrte Seiten teilen können. Erfolgreiche +leere Owner bis zu tatsächlichem MemoryLock halten, alten privaten Bericht +weiter geschützt/inhaltlich unverändert prüfen, danach Baseline wieder erreichen. +EN: Parent limits remain unchanged. Windows tests must physically observe the +actual report allocation, not infer a lock from a wrapper type. Native Linux, +Windows and ARM64 and both feature configurations remain mandatory. + +DE: Isolierter protected-report-focused-v3 besteht8 Kommandos mit910 +unveränderten Rust-/Manifest-Hashes: fünf tatsächliche Reportgruppen samt beiden +begrenzten Kindern, vier strenge Root-Lints für Linux/Windows mit/ohne API, +Fmt/Limits/Diff. Reale Stream-API unter echter Sperrverweigerung aufgerufen: +kein Source-Read, Target-Write oder Flush, Standard-KDF-Parameter unverändert. +Vorherige Lintfehler in Testaufrufern ohne neue Allow-Ausnahmen behoben und +Fehlerprotokolle behalten. Integrierte Gesamt-/native Abnahme steht aus; noch +nicht veröffentlicht. Kein R7/R8-Gesamtabschluss. +EN: No new dependency, unsafe, privileged test, installation or Main merge. + +DE: Integrierter protected-report-integrated-v1 besteht alle17 Kommandos auf920 +unveränderten Rust-/Manifest-Hashes nach konfliktfreiem Main361-/Windows-Abgleich: +sechs strenge Lints, acht Plattformtests, je116 Dateitests mit/ohne API und70 +Integrationen in16 Gruppen. Tatsächlicher Kill-/No-leftover-Test erfolgreich; +16 explizite Kind-/Race-Einstiege pro Dateilauf bleiben sichtbar ignoriert, +ihre vorgesehenen Eltern führen die eigenen begrenzten Kinder tatsächlich aus. +Vendor-/Angriffsmatrix-/Lizenzprüfer, Format/Limits/Diff erfolgreich. +EN: Three actual list output unit tests also pass: borrowed schema/escaping, +terminal quoting and write/flush failures. Additional list/check/stream acceptance passes27 integrations in seven groups +on the same920 unchanged source hashes. Both source-bound commands pass. +Complete native report acceptance remains pending. diff --git a/docs/security/SECRET_LIFETIME_INVENTORY.md b/docs/security/SECRET_LIFETIME_INVENTORY.md index d9365b2..9ba972b 100644 --- a/docs/security/SECRET_LIFETIME_INVENTORY.md +++ b/docs/security/SECRET_LIFETIME_INVENTORY.md @@ -148,4 +148,15 @@ Quellslot-Kopien wird in WINDOWS_TRAVERSAL_VALIDATION.md separat abgenommen. EN: Do not infer whole M1/M2/M3 closure from directory enumeration. Top-level std::Path component scanning, API/CLI-owned ingress, output/temporary/original paths, cleanup/identity/handle records and report/transport remain in scope. + +DE: Der vollständige Report-Record hält Zähler, Rechenscratch und konkrete Skip-/ +Absenderpräsenz vor Befüllung gemeinsam gesperrt. Fallible Konstruktion vor Ausgabe; +explizite Getter statt öffentlicher Felder/Default. CLI-Kontext, gewöhnliche Summary-/ +Value-/Format-/Transportpuffer bleiben offen; geschützte Quelle ersetzt keinen +geschützten Empfänger. Nachweise: [Report](PROTECTED_REPORT_VALIDATION.md). +EN: The complete report record prelocks counts, arithmetic scratch and actual +skip/sender presence before population. Fallible construction precedes output; +explicit getters replace public fields/Default. CLI context and ordinary Summary, +Value, formatting and transport buffers remain open; protecting a source does +not protect its recipient. See [report evidence](PROTECTED_REPORT_VALIDATION.md). Source-race338 and complete process/helper/host contracts remain open. diff --git a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md index 90861d4..16fbd90 100644 --- a/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md +++ b/docs/security/WINDOWS_TRAVERSAL_VALIDATION.md @@ -137,3 +137,22 @@ checks and corrected full native acceptance still required. Versioned primary sources / Versionierte Primärquellen: - https://github.com/rust-lang/rust/blob/1.88.0/library/std/src/sys/path/windows.rs - https://github.com/rust-lang/rust/blob/1.100.0/library/std/src/sys/path/windows_prefix.rs + +## Integrated native acceptance / Integrierte native Abnahme + +DE: Korrigierter Windows-Produktionswalker einschließlich Main359–361 am signierten +feb4e2ea53430f27f1fdab066c50661e233dac95 vollständig abgenommen. Alle25 Checks +erfolgreich, einschließlich acht Fuzz-Zielen, MSRV, Audit-/Historienprüfung und +genehmigter eigener Windows-Zugriffsprobe. Vier vollständige native Rust-Logs +mit exaktem Job-Head und SHA-256 geprüft: Linux22/ARM je992 Tests/121 Gruppen, +latest1905/240, Windows1733/243, null Fehler. Windows-Zahl enthält das zusätzliche +frühe Pfadorakel; Kind-Einstiege bleiben sichtbar ignoriert und zählen nicht als +erfolgreiche Tests. Tatsächliche UTF16/WTF8-/Namens-/Pfad-/NT-/Walkerfälle und +begrenztes Cleanup-/Unwind-Kind in beiden Featurekonfigurationen ausgeführt. +EN: Original failures remain evidence. Public-only prefix policy preserves the +unchanged native std oracle under Rust1.100; no private path passed to std prefix +parsing. Exact integrated source has six strict lints and local17-command Main +acceptance plus five final policy checks. This accepts production traversal, +not all M1/M3 or process/helper/host/transport rows; source-race338 remains open. +Evidence: windows-main361-feb4-native-summary, four complete logs/job manifests, +final-checks and independent bundle restore/full strict fsck/tree/blob-mode proof. diff --git a/src/cli/check_cmd.rs b/src/cli/check_cmd.rs index 4c47208..82a9cd9 100644 --- a/src/cli/check_cmd.rs +++ b/src/cli/check_cmd.rs @@ -123,11 +123,11 @@ fn print_line( c.ok, src.display(), t.msg_summary, - r.files, - r.directories, - r.bytes + r.files(), + r.directories(), + r.bytes() ); - super::signing::print(lang, r.signer.as_ref()); + super::signing::print(lang, r.signer()); } Err(f) => eprintln!("{}: {}: {}", c.failed, src.display(), f.message), } @@ -173,8 +173,8 @@ pub fn json(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult<(Map json!({ "source": source, "ok": true, "files": r.files, - "directories": r.directories, "bytes": r.bytes, + Ok(r) => json!({ "source": source, "ok": true, "files": r.files(), + "directories": r.directories(), "bytes": r.bytes(), "signer": super::files_json::signer(r) }), Err(f) => json!({ "source": source, "ok": false, "error": super::json_out::error(f) }), diff --git a/src/cli/files_json.rs b/src/cli/files_json.rs index cfb4573..39f5f79 100644 --- a/src/cli/files_json.rs +++ b/src/cli/files_json.rs @@ -31,8 +31,8 @@ type Outcome = Result; fn entry(source: &Value, out: Option<&Path>, r: &Outcome) -> Value { let target = out.map(|p| p.to_string_lossy().into_owned()); match r { - Ok(r) => json!({ "source": source, "target": target, "ok": true, "files": r.files, - "directories": r.directories, "bytes": r.bytes, "skipped": r.skipped.len(), + Ok(r) => json!({ "source": source, "target": target, "ok": true, "files": r.files(), + "directories": r.directories(), "bytes": r.bytes(), "skipped": r.skipped().len(), "signer": signer(r) }), Err(f) => json!({ "source": source, "target": target, "ok": false, "error": super::json_out::error(f) }), @@ -63,7 +63,7 @@ fn body(entries: &[(Value, Option, Outcome)]) -> (Map, u /// DE: Geprüfter Absender als Schlüssel-ID (hex) oder `null` (#44). EN: Verified sender as key ID /// (hex) or `null` (#44). pub(super) fn signer(r: &Report) -> Value { - r.signer.as_ref().map_or(Value::Null, |s| { + r.signer().map_or(Value::Null, |s| { pqkeep::envelope::hex_encode(s.key_id()).into() }) } diff --git a/src/cli/list_cmd.rs b/src/cli/list_cmd.rs index 60c11d8..d3be400 100644 --- a/src/cli/list_cmd.rs +++ b/src/cli/list_cmd.rs @@ -79,9 +79,9 @@ fn write_text(out: &mut impl Write, listing: &Listing, lang: Lang) -> std::io::R out, "{}: {} / {} / {}", super::text::texts(lang).msg_summary, - r.files, - r.directories, - r.bytes + r.files(), + r.directories(), + r.bytes() )?; out.flush() } diff --git a/src/cli/list_cmd_tests.rs b/src/cli/list_cmd_tests.rs index 5502979..b8b61c8 100644 --- a/src/cli/list_cmd_tests.rs +++ b/src/cli/list_cmd_tests.rs @@ -26,7 +26,7 @@ impl Write for FailedWriter { fn text_and_json_propagate_write_and_flush_errors() { let listing = Listing { entries: files::ConfidentialEntries::default(), - report: files::Report::default(), + report: files::Report::empty().unwrap(), }; for flush in [false, true] { let mut writer = FailedWriter { flush }; @@ -48,12 +48,7 @@ fn borrowed_list_output_preserves_the_existing_envelope() { }] .try_into() .unwrap(), - report: files::Report { - files: 1, - directories: 0, - bytes: 17, - ..files::Report::default() - }, + report: files::Report::with_counts(1, 0, 17).unwrap(), }; let mut out = Vec::new(); super::super::list_json::write(&mut out, &listing, "source.pqkf").unwrap(); @@ -81,7 +76,7 @@ fn text_quotes_names_and_json_is_one_line() { }] .try_into() .unwrap(), - report: files::Report::default(), + report: files::Report::empty().unwrap(), }; let mut out = Vec::new(); write_text(&mut out, &listing, Lang::En).unwrap(); diff --git a/src/cli/list_json.rs b/src/cli/list_json.rs index 2252770..7388eb3 100644 --- a/src/cli/list_json.rs +++ b/src/cli/list_json.rs @@ -66,9 +66,9 @@ pub(super) fn write(out: &mut impl Write, listing: &Listing, source: &str) -> io schema: super::list_cmd::SCHEMA, source, summary: Summary { - bytes: report.bytes, - directories: report.directories, - files: report.files, + bytes: report.bytes(), + directories: report.directories(), + files: report.files(), }, }; serde_json::to_writer(&mut *out, &envelope).map_err(io::Error::other)?; diff --git a/src/cli/report.rs b/src/cli/report.rs index 463dccf..8d127ed 100644 --- a/src/cli/report.rs +++ b/src/cli/report.rs @@ -19,7 +19,7 @@ pub(super) fn print_report( report: &Report, ) -> CliResult { let fail = |error: pqkeep::Error| Failure::from_error(&error, lang); - let mut entries = report.skipped.try_iter().map_err(fail)?; + let mut entries = report.skipped().try_iter().map_err(fail)?; // DE: Alle Records vor der ersten Berichtsausgabe prüfen; Cursor ohne Allokation zurücksetzen. // EN: Validate every record before the first report output; rewind without allocating. for entry in entries.by_ref() { @@ -31,7 +31,10 @@ pub(super) fn print_report( println!("{verb}: {}", shown(out)); println!( "{}: {} / {} / {}", - t.msg_summary, report.files, report.directories, report.bytes + t.msg_summary, + report.files(), + report.directories(), + report.bytes() ); for skipped in entries { let skipped = skipped.map_err(fail)?; @@ -47,6 +50,6 @@ pub(super) fn print_report( skipped.path().map_err(fail)? ); } - super::signing::print(lang, report.signer.as_ref()); + super::signing::print(lang, report.signer()); Ok(()) } diff --git a/src/cli/stream_cmd.rs b/src/cli/stream_cmd.rs index 9424ccc..5c1e9f3 100644 --- a/src/cli/stream_cmd.rs +++ b/src/cli/stream_cmd.rs @@ -125,7 +125,12 @@ pub fn run(p: &OwnedProtection, m: &ArgMatches) -> pqkeep::Result<(Option>, BufReader>>; /// EN: Verifies the signature (if any) – call before publishing. pub(super) fn verify(check: Option, report: &mut Report) -> Result<()> { if let Some(check) = check { - report.signer = Some(check.verify()?); + report.set_signer(check.verify()?); } Ok(()) } @@ -215,6 +215,7 @@ pub(super) fn write_file( (temp, mut out): (TempOutput, crate::fsutil::OutputFile), check: Option, ) -> Result { + let mut report = Report::empty()?; let size = entry.size(); archive.copy_file(size, &mut out)?; if archive.next_entry()?.is_some() { @@ -222,11 +223,7 @@ pub(super) fn write_file( } finish_file(out)?; archive.finish()?; - let mut report = Report { - files: 1, - bytes: size, - ..Report::default() - }; + report.add_file(size)?; verify(check, &mut report)?; temp.publish()?; Ok(report) @@ -254,7 +251,7 @@ pub(super) fn fill_dir( mut each: impl FnMut(&str, bool) -> Result<()>, ) -> Result { let mut seen = PathSet::default(); - let mut report = Report::default(); + let mut report = Report::empty()?; while let Some(entry) = archive.next_entry()? { let path = entry.path()?.expose()?; let parts = paths::components(path)?; @@ -264,11 +261,10 @@ pub(super) fn fill_dir( let mut out = output::create_file(root, parts)?; archive.copy_file(entry.size(), &mut out)?; finish_file(out)?; - report.files += 1; - report.bytes += entry.size(); + report.add_file(entry.size())?; } else { output::create_dir(root, parts)?; - report.directories += 1; + report.add_directory()?; } } archive.finish()?; diff --git a/src/files/encrypt.rs b/src/files/encrypt.rs index 62502df..e21d2e5 100644 --- a/src/files/encrypt.rs +++ b/src/files/encrypt.rs @@ -213,6 +213,8 @@ fn write_archive( content: Content, job: &Job<'_>, ) -> Result { + let mut report = Report::empty()?; + report.set_skipped(skipped); let hidden = super::stream_v4::hidden_signer(job.signer, job.options)?; let file_key = aead::generate_key()?; let prefix = rng::array::()?; @@ -240,10 +242,6 @@ fn write_archive( enc.start_hash()?; } let mut archive = ArchiveWriter::new(enc)?; - let mut report = Report { - skipped, - ..Report::default() - }; for entry in entries.try_iter()? { write_entry(&mut archive, entry?, &mut report)?; } @@ -275,12 +273,11 @@ fn write_entry( ) -> Result<()> { if entry.is_directory() { archive.dir(entry.path()?)?; - report.directories += 1; + report.add_directory()?; } else { let mut reader = entry.open()?; archive.file(entry.path()?, &mut reader, entry.size())?; - report.files += 1; - report.bytes += entry.size(); + report.add_file(entry.size())?; } Ok(()) } diff --git a/src/files/fault_tests.rs b/src/files/fault_tests.rs index 42876bc..4a1fd32 100644 --- a/src/files/fault_tests.rs +++ b/src/files/fault_tests.rs @@ -112,7 +112,7 @@ fn rec007_boundary_sizes_roundtrip_without_faults() { for size in [0, 1, 65_535, 65_536, 65_537] { let case = ArchiveCase::new(v2, false, size); let report = case.encrypt().unwrap(); - assert_eq!(report.bytes, size as u64); + assert_eq!(report.bytes(), size as u64); case.assert_valid(&case.root.path().join("valid")); assert_no_temps(case.root.path()); } diff --git a/src/files/mod.rs b/src/files/mod.rs index b5406a0..a4f1164 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -56,6 +56,7 @@ pub mod random_name; #[cfg(test)] #[path = "recovery_v4_tests.rs"] mod recovery_v4_tests; +mod report; mod scan; mod signed_by; mod signed_io; @@ -93,6 +94,7 @@ pub use format_v2::{HeaderV2, Slot}; pub use list::{EntryKind, ListEntry, Listing, MAX_LIST_ENTRIES, MAX_LIST_PATH_BYTES, list}; pub use original::{ChooseTarget, decrypt_original}; pub use random_name::{is_random_name, random_name, random_target}; +pub use report::Report; pub use signed_by::SignedBy; pub use signer_v3::Signer; pub use skipped::Skipped; @@ -181,28 +183,6 @@ pub enum Unlock<'a> { Key(&'a UnlockedKey), } -/// DE: Bericht über einen Vorgang. EN: Report of an operation. -#[derive(Default, PartialEq, Eq)] -pub struct Report { - /// DE: Anzahl Dateien. EN: Number of files. - pub files: u64, - /// DE: Anzahl Ordner. EN: Number of directories. - pub directories: u64, - /// DE: Summe der Dateigrößen. EN: Total size of files. - pub bytes: u64, - /// DE: Übersprungene Einträge (nur beim Verschlüsseln). EN: Skipped entries (encrypting only). - pub skipped: SkippedEntries, - /// DE: Geprüfter Absender (nur Format v3, beim Entschlüsseln/Prüfen). - /// EN: Verified sender (format v3 only, when decrypting/checking). - pub signer: Option, -} - -impl std::fmt::Debug for Report { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Report([REDACTED])") - } -} - /// DE: Liest nur den Header (ohne Schlüssel): Inhaltstyp, Schutzart, KDF-Parameter /// bzw. Empfänger-ID – hilft, den richtigen Schlüssel zu finden. Nur v1; für v2 siehe /// [`inspect_v2`]. diff --git a/src/files/report.rs b/src/files/report.rs new file mode 100644 index 0000000..b1111c3 --- /dev/null +++ b/src/files/report.rs @@ -0,0 +1,146 @@ +//! DE: Berichtsrecord vor privaten Zählern/Präsenzflags sperren; Ausgabe bewusst ausleihen. +//! EN: Prelock report records before private counts/presence flags; disclose explicitly. +use super::{SignedBy, SkippedEntries}; +use crate::{Error, Result, crypto::secret_state::SecretState}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Default)] +struct State { + files: u64, + directories: u64, + bytes: u64, + next_files: u64, + next_bytes: u64, + skipped: SkippedEntries, + signer: Option, +} +impl Zeroize for State { + fn zeroize(&mut self) { + self.files.zeroize(); + self.directories.zeroize(); + self.bytes.zeroize(); + self.next_files.zeroize(); + self.next_bytes.zeroize(); + self.skipped = SkippedEntries::default(); + self.signer = None; + } +} +impl Drop for State { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for State {} + +/// DE: Geschützter Vorgangsbericht; nur ausdrückliche Getter geben Metadaten frei. +/// EN: Protected operation report; only explicit getters disclose metadata. +pub struct Report(SecretState); + +impl Report { + /// DE: Leeren vollständigen Record vor privaten Daten sperren, niemals Plaintext-Fallback. + /// EN: Lock the complete empty record before private data, never fall back to plaintext. + /// + /// # Errors + /// DE/EN: [`Error::MemoryLock`] bei verweigerter Sperre / when locking is denied. + pub fn empty() -> Result { + Ok(Self(SecretState::new(State::default())?)) + } + + /// DE: Caller-Zähler erst nach erfolgreicher Sperre übernehmen; keine Authentisierungszusage. + /// EN: Copy caller counts only after locking succeeds; this is no authentication proof. + /// + /// # Errors + /// DE/EN: wie / as [`Self::empty`]. + pub fn with_counts(files: u64, directories: u64, bytes: u64) -> Result { + let mut out = Self::empty()?; + let state = out.0.get_mut(); + state.files = files; + state.directories = directories; + state.bytes = bytes; + Ok(out) + } + + /// DE: Dateizahl bewusst offenlegen. EN: Explicitly disclose file count. + #[must_use] + pub fn files(&self) -> u64 { + self.0.get().files + } + + /// DE: Ordnerzahl bewusst offenlegen. EN: Explicitly disclose directory count. + #[must_use] + pub fn directories(&self) -> u64 { + self.0.get().directories + } + + /// DE: Nutzdatenumfang bewusst offenlegen. EN: Explicitly disclose payload byte count. + #[must_use] + pub fn bytes(&self) -> u64 { + self.0.get().bytes + } + + /// DE: Gesperrte Skip-Sammlung ausleihen. EN: Borrow the protected skipped collection. + #[must_use] + pub fn skipped(&self) -> &SkippedEntries { + &self.0.get().skipped + } + + /// DE: Geprüften Absender bewusst ausleihen. EN: Explicitly borrow the verified sender. + #[must_use] + pub fn signer(&self) -> Option<&SignedBy> { + self.0.get().signer.as_ref() + } + + pub(super) fn set_skipped(&mut self, skipped: SkippedEntries) { + self.0.get_mut().skipped = skipped; + } + pub(super) fn set_signer(&mut self, signer: SignedBy) { + self.0.get_mut().signer = Some(signer); + } + pub(super) fn add_file(&mut self, bytes: u64) -> Result<()> { + let state = self.0.get_mut(); + // DE: Beide Ergebnisse geschützt prüfen, bevor der bisherige Bericht geändert wird. + // EN: Check both results in protected storage before changing the original report. + state.next_files = state.files.checked_add(1).ok_or_else(overflow)?; + state.next_bytes = state.bytes.checked_add(bytes).ok_or_else(overflow)?; + state.files = state.next_files; + state.bytes = state.next_bytes; + state.next_files.zeroize(); + state.next_bytes.zeroize(); + Ok(()) + } + pub(super) fn add_directory(&mut self) -> Result<()> { + let state = self.0.get_mut(); + state.directories = state.directories.checked_add(1).ok_or_else(overflow)?; + Ok(()) + } + pub(super) fn add_bytes(&mut self, bytes: u64) -> Result<()> { + let state = self.0.get_mut(); + state.bytes = state.bytes.checked_add(bytes).ok_or_else(overflow)?; + Ok(()) + } +} + +fn overflow() -> Error { + Error::InvalidInput { field: "archive" } +} + +impl PartialEq for Report { + fn eq(&self, other: &Self) -> bool { + let (left, right) = (self.0.get(), other.0.get()); + left.files == right.files + && left.directories == right.directories + && left.bytes == right.bytes + && left.skipped == right.skipped + && left.signer == right.signer + } +} +impl Eq for Report {} +impl std::fmt::Debug for Report { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Report([REDACTED])") + } +} + +#[cfg(test)] +#[path = "report_tests.rs"] +mod tests; diff --git a/src/files/report_tests.rs b/src/files/report_tests.rs new file mode 100644 index 0000000..ee0b5af --- /dev/null +++ b/src/files/report_tests.rs @@ -0,0 +1,239 @@ +//! DE: Tatsächliche Berichtsrecords, Überläufe, Wipe, Verweigerung und Unwind prüfen. +//! EN: Check actual report records, overflow, wiping, refusal and unwind. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::{ + files::{ConfidentialText, SkipReason}, + locked_owner_test_support::locked, +}; + +fn physical(report: &Report) { + let state = report.0.get(); + locked(state); + locked(&state.files); + locked(&state.directories); + locked(&state.bytes); + locked(&state.skipped); + locked(&state.signer); + #[cfg(windows)] + { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(state).addr(); + for offset in (0..size_of_val(state)).step_by(region::page::size()) { + assert!(query.get_mut().is_locked(start + offset).unwrap()); + } + assert!( + query + .get_mut() + .is_locked(start + size_of_val(state) - 1) + .unwrap() + ); + } +} + +fn populated() -> Report { + let mut report = Report::with_counts(3, 5, 7).unwrap(); + let mut skipped = SkippedEntries::default(); + skipped + .push( + ConfidentialText::from_text("public fixture").unwrap(), + SkipReason::InvalidName, + ) + .unwrap(); + report.set_skipped(skipped); + report.set_signer(SignedBy::from_public_key(b"public key fixture").unwrap()); + report +} + +#[test] +fn actual_complete_report_record_stays_locked_through_population_move_and_disclosure() { + let report = populated(); + physical(&report); + let moved = Box::new(report); + physical(&moved); + assert_eq!( + (moved.files(), moved.directories(), moved.bytes()), + (3, 5, 7) + ); + assert_eq!(moved.skipped().len(), 1); + assert!(moved.signer().is_some()); + assert_eq!(format!("{moved:?}"), "Report([REDACTED])"); + let expected = populated(); + assert_eq!(*moved, expected); + locked(moved.signer().unwrap().key_id()); +} + +#[test] +fn checked_summary_arithmetic_preserves_visible_original_on_overflow() { + let mut report = Report::with_counts(3, u64::MAX, u64::MAX).unwrap(); + assert!(matches!( + report.add_file(1), + Err(Error::InvalidInput { field: "archive" }) + )); + assert!(report.add_directory().is_err()); + assert!(report.add_bytes(1).is_err()); + assert_eq!( + (report.files(), report.directories(), report.bytes()), + (3, u64::MAX, u64::MAX) + ); + physical(&report); + let mut report = Report::with_counts(u64::MAX, 0, 0).unwrap(); + assert!(report.add_file(0).is_err()); + assert_eq!(report.files(), u64::MAX); +} + +#[test] +fn complete_record_zeroization_clears_counts_scratch_and_nested_presence_while_locked() { + let mut report = populated(); + report.0.get_mut().next_files = 11; + report.0.get_mut().next_bytes = 13; + report.0.get_mut().zeroize(); + physical(&report); + assert_eq!( + (report.files(), report.directories(), report.bytes()), + (0, 0, 0) + ); + assert!(report.skipped().is_empty() && report.signer().is_none()); + assert_eq!(report.0.get().next_files, 0); + assert_eq!(report.0.get().next_bytes, 0); +} + +#[test] +fn actual_report_unwind_and_cleanup_are_verified_in_a_bounded_own_child() { + crate::locked_owner_test_support::isolated_test( + "files::report::tests::report_cleanup_child", + "PQKEEP_REPORT_CLEANUP_CHILD", + ); +} + +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn report_cleanup_child() { + assert_eq!(std::env::var("PQKEEP_REPORT_CLEANUP_CHILD").unwrap(), "1"); + drop(populated()); + let baseline = snapshot(); + let result = std::panic::catch_unwind(|| { + let report = populated(); + physical(&report); + std::panic::resume_unwind(Box::new(())); + }); + assert!(result.is_err()); + assert_eq!(snapshot(), baseline); +} + +fn snapshot() -> (usize, usize) { + let pages = crate::hardening::memlock::stats().locked_pages; + #[cfg(target_os = "linux")] + { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let bytes = status + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024; + (pages, bytes) + } + #[cfg(not(target_os = "linux"))] + { + (pages, 0) + } +} + +#[cfg(target_os = "linux")] +#[test] +fn actual_report_factory_refuses_real_kernel_lock_denial_without_changing_parent() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + crate::locked_owner_test_support::isolated_test( + "files::report::tests::report_denial_child", + "PQKEEP_REPORT_DENIAL_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur eigenes begrenztes Kind / bounded own child only"] +fn report_denial_child() { + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!(std::env::var("PQKEEP_REPORT_DENIAL_CHILD").unwrap(), "1"); + let original = populated(); + let passphrase = + crate::security::generator::generate(&crate::security::generator::Options::default()) + .unwrap(); + let params = crate::crypto::kdf::KdfProfile::Standard.params(); + let mut retained = Vec::with_capacity(2048); + let baseline = snapshot(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + let mut denied = false; + for _ in 0..2048 { + match Report::empty() { + Ok(report) => retained.push(report), + Err(error) => { + assert_eq!(error, Error::MemoryLock); + denied = true; + break; + } + } + } + assert!(denied); + stream_cannot_read_or_write_under_denial(&passphrase, params); + physical(&original); + assert_eq!( + (original.files(), original.directories(), original.bytes()), + (3, 5, 7) + ); + assert!(original.signer().is_some()); + assert_eq!(original.skipped().len(), 1); + drop(retained); + assert_eq!(snapshot(), baseline); +} + +#[cfg(target_os = "linux")] +#[derive(Default)] +struct Untouched(usize); +#[cfg(target_os = "linux")] +impl std::io::Read for Untouched { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + self.0 += 1; + Err(std::io::ErrorKind::BrokenPipe.into()) + } +} +#[cfg(target_os = "linux")] +impl std::io::Write for Untouched { + fn write(&mut self, _: &[u8]) -> std::io::Result { + self.0 += 1; + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + self.0 += 1; + Err(std::io::ErrorKind::BrokenPipe.into()) + } +} + +#[cfg(target_os = "linux")] +fn stream_cannot_read_or_write_under_denial( + passphrase: &crate::security::StrongPassphrase, + params: crate::crypto::kdf::KdfParams, +) { + let mut source = Untouched::default(); + let mut target = Untouched::default(); + let protection = crate::files::Protection::Passphrase { passphrase, params }; + let result = crate::files::encrypt_stream( + &mut source, + &mut target, + &protection, + None, + crate::files::EncryptOptions::default(), + ); + assert_eq!(result, Err(Error::MemoryLock)); + assert_eq!((source.0, target.0), (0, 0)); +} diff --git a/src/files/scan.rs b/src/files/scan.rs index 4c2a02f..efc5bcc 100644 --- a/src/files/scan.rs +++ b/src/files/scan.rs @@ -17,19 +17,16 @@ pub(super) fn read( signer: Option<&PublicKeyFile>, mut visit: impl FnMut(&Entry) -> Result<()>, ) -> Result { + let mut report = Report::empty()?; let (archive, content, check) = decrypt::open(source, unlock, signer)?; - let mut report = match content { - Content::File => file(archive, &mut visit)?, - Content::Directory => directory(archive, &mut visit)?, - Content::Stream => Report { - files: 1, - bytes: { - let (dec, tail) = archive.into_stream(); - super::tail_v4::copy_payload(dec, &mut sink(), &tail)?.0 - }, - ..Report::default() - }, - }; + match content { + Content::File => file(archive, &mut visit, &mut report)?, + Content::Directory => directory(archive, &mut visit, &mut report)?, + Content::Stream => { + let (dec, tail) = archive.into_stream(); + report.add_file(super::tail_v4::copy_payload(dec, &mut sink(), &tail)?.0)?; + } + } decrypt::verify(check, &mut report)?; Ok(report) } @@ -37,7 +34,8 @@ pub(super) fn read( fn file( mut archive: ArchiveReader, visit: &mut impl FnMut(&Entry) -> Result<()>, -) -> Result { + report: &mut Report, +) -> Result<()> { let entry = archive .next_entry()? .ok_or(Error::InvalidInput { field: "archive" })?; @@ -52,19 +50,16 @@ fn file( return Err(Error::InvalidInput { field: "archive" }); } archive.finish()?; - Ok(Report { - files: 1, - bytes: size, - ..Report::default() - }) + report.add_file(size)?; + Ok(()) } fn directory( mut archive: ArchiveReader, visit: &mut impl FnMut(&Entry) -> Result<()>, -) -> Result { + report: &mut Report, +) -> Result<()> { let mut seen = PathSet::default(); - let mut report = Report::default(); while let Some(entry) = archive.next_entry()? { // DE: List-Budget vor PathSet/Kopien prüfen; kein öffentlicher Callback. // EN: Check listing budget before PathSet/copies; no public callback. @@ -72,15 +67,11 @@ fn directory( seen.insert_components(paths::components(entry.path()?.expose()?)?, entry.is_file())?; if entry.is_file() { archive.copy_file(entry.size(), &mut sink())?; - report.files += 1; - report.bytes = report - .bytes - .checked_add(entry.size()) - .ok_or(Error::InvalidInput { field: "archive" })?; + report.add_file(entry.size())?; } else { - report.directories += 1; + report.add_directory()?; } } archive.finish()?; - Ok(report) + Ok(()) } diff --git a/src/files/stream_v4.rs b/src/files/stream_v4.rs index 31e836e..9a77287 100644 --- a/src/files/stream_v4.rs +++ b/src/files/stream_v4.rs @@ -41,6 +41,8 @@ pub fn encrypt_stream( signer: Option<&UnlockedKey>, options: EncryptOptions, ) -> Result { + let mut report = Report::empty()?; + report.add_file(0)?; if let Some(key) = signer { check_signing_key(key)?; } @@ -63,7 +65,6 @@ pub fn encrypt_stream( enc.start_hash()?; } let mut buf = SecretBytes::zeroed(CHUNK_SIZE)?; - let mut total = 0u64; loop { let n = match source.read(buf.expose_mut()) { Ok(0) => break, @@ -72,7 +73,7 @@ pub fn encrypt_stream( Err(e) => return Err(e.into()), }; enc.push(&buf.expose()[..n])?; - total = total.checked_add(n as u64).ok_or(Error::Crypto)?; + report.add_bytes(n as u64)?; } let tail = TailWrite { padded: options.pad, @@ -85,11 +86,7 @@ pub fn encrypt_stream( _ => body.into_inner(), }; out.flush()?; - Ok(Report { - files: 1, - bytes: total, - ..Report::default() - }) + Ok(report) } /// DE: Signaturschlüssel für den verborgenen Absender; `hide_sender` ohne Schlüssel ist ein Fehler. @@ -134,6 +131,7 @@ pub(super) fn extract( target: &Path, check: Option, ) -> Result { + let mut report = Report::empty()?; let (temp, file) = TempOutput::file(target)?; let mut out = file; let (bytes, written) = copy_payload(dec, &mut out, &tail)?; @@ -142,11 +140,7 @@ pub(super) fn extract( out.set_len(bytes)?; } finish_file(out)?; - let mut report = Report { - files: 1, - bytes, - ..Report::default() - }; + report.add_file(bytes)?; verify(check, &mut report)?; temp.publish()?; Ok(report) diff --git a/tests/files_anonymous.rs b/tests/files_anonymous.rs index 49ad553..bcb84ce 100644 --- a/tests/files_anonymous.rs +++ b/tests/files_anonymous.rs @@ -141,5 +141,5 @@ fn combines_with_passphrase_signature_and_padding() { let (file, pass, _) = &all[2]; assert_eq!(opens(&enc, file, pass).unwrap(), plain); let report = files::check(&enc, &Unlock::Passphrase(own.as_ref())).unwrap(); - assert!(report.signer.is_some()); + assert!(report.signer().is_some()); } diff --git a/tests/files_check.rs b/tests/files_check.rs index 6b41fcb..c61a9ef 100644 --- a/tests/files_check.rs +++ b/tests/files_check.rs @@ -41,7 +41,7 @@ fn v1_file_and_directory_pass_and_nothing_is_written() { let before = listing(&w.work); let unlock = Unlock::Passphrase(pass.as_ref()); let report = files::check(&enc, &unlock).unwrap(); - assert_eq!((report.files, report.bytes), (1, CONTENT.len() as u64)); + assert_eq!((report.files(), report.bytes()), (1, CONTENT.len() as u64)); let decrypted = files::decrypt(&enc_dir, &w.dir.path().join("zurueck"), &unlock).unwrap(); let checked = files::check(&enc_dir, &unlock).unwrap(); assert_eq!(checked, decrypted); @@ -79,7 +79,7 @@ fn v2_factor_and_several_recipients() { factor: &f, }; for unlock in [with_factor, Unlock::Key(&anna_key), Unlock::Key(&ben_key)] { - assert_eq!(files::check(&enc, &unlock).unwrap().files, 1); + assert_eq!(files::check(&enc, &unlock).unwrap().files(), 1); } let without = files::check(&enc, &Unlock::Passphrase(pass.as_ref())).unwrap_err(); assert_eq!( diff --git a/tests/files_hidden_sender.rs b/tests/files_hidden_sender.rs index 830dacd..b4b00ff 100644 --- a/tests/files_hidden_sender.rs +++ b/tests/files_hidden_sender.rs @@ -70,8 +70,8 @@ fn opened( result } -fn assert_sender(report: files::Report, public: &PublicKeyFile) { - assert_eq!(report.signer.unwrap().key_id(), public.key_id()); +fn assert_sender(report: &files::Report, public: &PublicKeyFile) { + assert_eq!(report.signer().unwrap().key_id(), public.key_id()); } #[test] @@ -95,8 +95,8 @@ fn file_directory_and_stream_roundtrip_with_hidden_sender() { let _ = std::fs::remove_file(&enc); files::encrypt_with_options(src, &enc, &p, Some(&key), options).unwrap(); assert_hidden(&enc, &key, content); - assert_sender(opened(&enc, &unlock, None).unwrap(), &public); - assert_sender(files::check(&enc, &unlock).unwrap(), &public); + assert_sender(&opened(&enc, &unlock, None).unwrap(), &public); + assert_sender(&files::check(&enc, &unlock).unwrap(), &public); assert!(files::list(&enc, &unlock).is_ok()); } let enc = dir.path().join("s.pqkf"); @@ -104,7 +104,7 @@ fn file_directory_and_stream_roundtrip_with_hidden_sender() { let plain = vec![9u8; 70_000]; files::encrypt_stream_to(&mut &plain[..], &enc, &p, Some(&key), options).unwrap(); assert_hidden(&enc, &key, Content::Stream); - assert_sender(opened(&enc, &unlock, None).unwrap(), &public); + assert_sender(&opened(&enc, &unlock, None).unwrap(), &public); assert_eq!(std::fs::read(enc.with_file_name("klar")).unwrap(), plain); let header = files::inspect_v2(&enc).unwrap(); assert_eq!( @@ -142,7 +142,7 @@ fn anonymous_recipient_with_hidden_sender() { let header = files::inspect_v2(&enc).unwrap(); assert_eq!(header.v4.unwrap().options & OPT_ANON, OPT_ANON); let report = opened(&enc, &Unlock::Key(&unlocked), Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id(), public.key_id()); + assert_eq!(report.signer().unwrap().key_id(), public.key_id()); } #[test] diff --git a/tests/files_list_limits.rs b/tests/files_list_limits.rs index 840cc1f..b8ef86f 100644 --- a/tests/files_list_limits.rs +++ b/tests/files_list_limits.rs @@ -39,7 +39,7 @@ fn ten_thousand_entries_are_valid_but_the_next_is_listing_only_error() { raw.extend(end(MAX_LIST_ENTRIES as u64 + 1)); build(&key, Content::Directory, &raw, &enc); expect_limit(&files::list(&enc, &unlock)); - assert_eq!(files::check(&enc, &unlock).unwrap().directories, 10_001); + assert_eq!(files::check(&enc, &unlock).unwrap().directories(), 10_001); assert_eq!(common::dir_names(dir.path()), ["input.pqkf"]); } @@ -71,7 +71,7 @@ fn sixteen_mib_path_bytes_are_valid_but_one_more_byte_is_rejected() { build(&key, Content::Directory, &raw, &enc); expect_limit(&files::list(&enc, &unlock)); assert_eq!( - files::check(&enc, &unlock).unwrap().directories, + files::check(&enc, &unlock).unwrap().directories(), count as u64 + 1 ); } @@ -84,5 +84,5 @@ fn empty_directory_is_a_valid_empty_listing() { build(&key, Content::Directory, &end(0), &enc); let listing = files::list(&enc, &Unlock::Key(&key.unlocked)).unwrap(); assert!(listing.entries.is_empty()); - assert_eq!(listing.report, files::Report::default()); + assert_eq!(listing.report, files::Report::empty().unwrap()); } diff --git a/tests/files_malicious.rs b/tests/files_malicious.rs index 2b3b3f8..584acdc 100644 --- a/tests/files_malicious.rs +++ b/tests/files_malicious.rs @@ -52,7 +52,10 @@ fn control_case_is_accepted() { let plain = [dir_entry("a"), file_entry("a/b.txt", b"hi", true), end(2)].concat(); build(&key, Content::Directory, &plain, &enc); let report = files::check(&enc, &Unlock::Key(&key.unlocked)).unwrap(); - assert_eq!((report.files, report.directories, report.bytes), (1, 1, 2)); + assert_eq!( + (report.files(), report.directories(), report.bytes()), + (1, 1, 2) + ); let listed = files::list(&enc, &Unlock::Key(&key.unlocked)).unwrap(); assert_eq!(listed.report, report); assert_eq!(listed.entries.len(), 2); diff --git a/tests/files_many.rs b/tests/files_many.rs index 331a2b4..d5ae95c 100644 --- a/tests/files_many.rs +++ b/tests/files_many.rs @@ -42,7 +42,7 @@ fn container_roundtrip_with_passphrase() { }; let enc = dir.path().join("auswahl.pqkf"); let report = files::encrypt_many(&refs(&sources), &enc, &protection).unwrap(); - assert_eq!((report.files, report.directories), (7, 5)); + assert_eq!((report.files(), report.directories()), (7, 5)); assert_eq!(files::inspect(&enc).unwrap().content, Content::Directory); let out = dir.path().join("zurück"); files::decrypt(&enc, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); @@ -104,9 +104,9 @@ fn selected_symlink_is_skipped_and_reported() { }; let report = files::encrypt_many(&refs(&sources), &dir.path().join("y.pqkf"), &protection).unwrap(); - assert_eq!(report.files, 1); - assert_eq!(report.skipped.len(), 1); - assert_eq!(report.skipped.get(0).unwrap().path().unwrap(), "link"); + assert_eq!(report.files(), 1); + assert_eq!(report.skipped().len(), 1); + assert_eq!(report.skipped().get(0).unwrap().path().unwrap(), "link"); } #[test] diff --git a/tests/files_original.rs b/tests/files_original.rs index 1ee8f85..caaef9f 100644 --- a/tests/files_original.rs +++ b/tests/files_original.rs @@ -47,7 +47,7 @@ fn file_name_restored_from_archive() { let (target, report) = files::decrypt_original(&enc, &out, &unlock, None, &same).unwrap(); assert_eq!(target, out.join("steuer-2026.pdf")); assert_eq!(std::fs::read(&target).unwrap(), b"geheim"); - assert_eq!(report.files, 1); + assert_eq!(report.files(), 1); // DE: Zweites Mal: Ziel existiert, nichts überschrieben, keine Reste. // EN: Second time: target exists, nothing overwritten, no leftovers. let again = files::decrypt_original(&enc, &out, &unlock, None, &same); @@ -87,7 +87,7 @@ fn directory_and_container_restored() { let (target, report) = files::decrypt_original(&enc2, &out, &unlock, None, &same).unwrap(); assert_eq!(target, out.join("Auswahl")); assert_eq!(std::fs::read(target.join("notiz.txt")).unwrap(), b"n"); - assert_eq!(report.files, 6); + assert_eq!(report.files(), 6); assert_eq!(common::dir_names(&out), vec!["Auswahl", "Urlaub 2026"]); // DE: Ungültiger Containername. EN: Invalid container name. for bad in ["a/b", "..", "CON", ""] { diff --git a/tests/files_output.rs b/tests/files_output.rs index 80d23a1..0b3422f 100644 --- a/tests/files_output.rs +++ b/tests/files_output.rs @@ -109,9 +109,9 @@ fn permissions_and_skipped_entries() { &Protection::Recipient(&key_file.public_part().unwrap()), ) .unwrap(); - assert_eq!((report.files, report.directories), (1, 1)); + assert_eq!((report.files(), report.directories()), (1, 1)); let mut reasons: Vec<_> = report - .skipped + .skipped() .try_iter() .unwrap() .map(|s| { diff --git a/tests/files_padding.rs b/tests/files_padding.rs index d068965..cee5613 100644 --- a/tests/files_padding.rs +++ b/tests/files_padding.rs @@ -53,7 +53,7 @@ fn padded_stream_size_follows_padme_and_hides_small_differences() { let out = dir.path().join(format!("s{len}.bin")); files::decrypt(&enc, &out, &unlock).unwrap(); assert_eq!(std::fs::read(&out).unwrap(), plain); - assert_eq!(files::check(&enc, &unlock).unwrap().bytes, len as u64); + assert_eq!(files::check(&enc, &unlock).unwrap().bytes(), len as u64); } // DE: 1001 und 1050 Byte liegen in derselben PADMÉ-Stufe (1088). EN: same PADMÉ bucket. assert_eq!(sizes[0], sizes[1]); diff --git a/tests/files_roundtrip.rs b/tests/files_roundtrip.rs index 28330e8..eaa2c33 100644 --- a/tests/files_roundtrip.rs +++ b/tests/files_roundtrip.rs @@ -40,9 +40,9 @@ fn single_file_sizes_with_passphrase() { let out = dir.path().join(format!("out-{size}.bin")); std::fs::write(&src, &data).unwrap(); let report = files::encrypt(&src, &enc, &protection).unwrap(); - assert_eq!((report.files, report.bytes), (1, size as u64)); + assert_eq!((report.files(), report.bytes()), (1, size as u64)); let report = files::decrypt(&enc, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); - assert_eq!(report.bytes, size as u64); + assert_eq!(report.bytes(), size as u64); assert_eq!(std::fs::read(&out).unwrap(), data, "size {size}"); } } @@ -60,14 +60,14 @@ fn directory_with_passphrase() { }; let enc = dir.path().join("quelle.pqkf"); let report = files::encrypt(&src, &enc, &protection).unwrap(); - assert_eq!((report.files, report.directories), (5, 4)); - assert_eq!(report.skipped, files::SkippedEntries::default()); + assert_eq!((report.files(), report.directories()), (5, 4)); + assert_eq!(report.skipped(), &files::SkippedEntries::default()); let out = dir.path().join("ziel"); let back = files::decrypt(&enc, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); assert_eq!( - (back.files, back.directories, back.bytes), - (5, 4, report.bytes) + (back.files(), back.directories(), back.bytes()), + (5, 4, report.bytes()) ); assert_eq!(common::read_tree(&out), common::read_tree(&src)); } @@ -139,7 +139,7 @@ fn empty_directory_roundtrip() { files::encrypt(&src, &enc, &protection).unwrap(); let out = dir.path().join("leer-zurück"); let report = files::decrypt(&enc, &out, &Unlock::Passphrase(pass.as_ref())).unwrap(); - assert_eq!((report.files, report.directories), (0, 0)); + assert_eq!((report.files(), report.directories()), (0, 0)); assert!(out.is_dir()); assert_eq!(common::read_tree(&out).len(), 0); } diff --git a/tests/files_signed.rs b/tests/files_signed.rs index f28a741..94f2a0c 100644 --- a/tests/files_signed.rs +++ b/tests/files_signed.rs @@ -72,7 +72,7 @@ fn signed_passphrase_file_is_v3_and_names_the_sender() { assert_eq!(v2::version(&bytes), 3); let unlock = Unlock::Passphrase(pass.as_ref()); let report = open(&w, &bytes, &unlock, None).unwrap(); - assert_eq!(report.signer.unwrap().key_id(), public.key_id()); + assert_eq!(report.signer().unwrap().key_id(), public.key_id()); // DE: Verlangter, richtiger Absender. EN: Required, correct sender. assert!(open(&w, &bytes, &unlock, Some(&public)).is_ok()); // DE: Header zeigt den Absender ungeprüft. EN: Header shows the sender unverified. @@ -111,12 +111,12 @@ fn signed_works_with_recipients_factor_and_check() { }, ] { let report = open(&w, &bytes, &unlock, Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id(), public.key_id()); + assert_eq!(report.signer().unwrap().key_id(), public.key_id()); } let input = w.work.join("check.pqkf"); std::fs::write(&input, &bytes).unwrap(); let report = files::check_with(&input, &Unlock::Key(&anna), Some(&public)).unwrap(); - assert_eq!(report.signer.unwrap().key_id(), public.key_id()); + assert_eq!(report.signer().unwrap().key_id(), public.key_id()); assert!(files::list(&input, &Unlock::Key(&ben)).is_ok()); std::fs::remove_file(&input).unwrap(); } @@ -137,7 +137,7 @@ fn unsigned_files_keep_v1_and_v2_and_carry_no_sender() { std::fs::remove_file(&target).unwrap(); assert_eq!(v2::version(&bytes), version); let report = open(&w, &bytes, &Unlock::Key(&anna), None).unwrap(); - assert_eq!(report.signer, None); + assert_eq!(report.signer(), None); // DE: Verlangter Absender, Datei unsigniert. EN: Required sender, file unsigned. let (_, public) = signer(); let err = open(&w, &bytes, &Unlock::Key(&anna), Some(&public)); diff --git a/tests/files_stream_v4.rs b/tests/files_stream_v4.rs index 056af83..1e66251 100644 --- a/tests/files_stream_v4.rs +++ b/tests/files_stream_v4.rs @@ -43,7 +43,7 @@ fn sealed(dir: &Path, plain: &[u8], p: &Protection<'_>, signer: Option<&Unlocked files::EncryptOptions::default(), ) .unwrap(); - assert_eq!(report.bytes, plain.len() as u64); + assert_eq!(report.bytes(), plain.len() as u64); enc } @@ -76,7 +76,7 @@ fn passphrase_roundtrip_at_chunk_boundaries() { plain, "Länge / length {len}" ); - assert_eq!(files::check(&enc, &unlock).unwrap().bytes, len as u64); + assert_eq!(files::check(&enc, &unlock).unwrap().bytes(), len as u64); } } @@ -106,7 +106,7 @@ fn recipients_and_signature_roundtrip() { assert_eq!(opened(&enc, &Unlock::Key(&unlocked)).unwrap(), plain); } let report = files::check(&enc, &Unlock::Passphrase(own.as_ref())).unwrap(); - assert!(report.signer.is_some()); + assert!(report.signer().is_some()); let other = files::check_with( &enc, &Unlock::Passphrase(own.as_ref()), diff --git a/tests/files_v2_kat.rs b/tests/files_v2_kat.rs index b72aa0b..9946d60 100644 --- a/tests/files_v2_kat.rs +++ b/tests/files_v2_kat.rs @@ -63,7 +63,7 @@ fn c02_independent_file_opens() { }; let report = files::decrypt(&input, &out, &unlock).unwrap(); assert_eq!(std::fs::read(&out).unwrap(), bytes(&vector, "plain_hex")); - assert_eq!((report.files, report.directories), (1, 0)); + assert_eq!((report.files(), report.directories()), (1, 0)); // DE: Anderer Faktor oder andere Passphrase öffnen nicht. EN: Other factor/passphrase fail. let other = Factor::from_bytes(&[0x5a; 32]).unwrap(); diff --git a/tests/files_v2_roundtrip.rs b/tests/files_v2_roundtrip.rs index 9fda943..d629a4c 100644 --- a/tests/files_v2_roundtrip.rs +++ b/tests/files_v2_roundtrip.rs @@ -339,7 +339,7 @@ fn directory_and_several_sources_with_slots() { files::encrypt_many(&[&tree, &extra], &many, &protection).unwrap(); let out = dir.path().join("mehrere"); let report = files::decrypt(&many, &out, &Unlock::Key(&unlocked)).unwrap(); - assert_eq!(report.files, 6); + assert_eq!(report.files(), 6); assert_eq!( std::fs::read(out.join("einzeln.txt")).unwrap(), b"einzeln / single" diff --git a/tests/integrity_headers.rs b/tests/integrity_headers.rs index 411169b..558c41d 100644 --- a/tests/integrity_headers.rs +++ b/tests/integrity_headers.rs @@ -74,7 +74,7 @@ fn unchanged_files_open_on_every_path() { assert_eq!( pqkeep::files::check(&input, &keys.unlock(kind)) .unwrap() - .bytes, + .bytes(), 2 ); std::fs::remove_file(&input).unwrap(); From 968684f311fd5645f78ad90bd5aac96700c4ba7c Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:30:05 +0100 Subject: [PATCH 26/26] Protect listing JSON formatting and native feature coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DE: Tatsächlichen Cursor und Zahlen-/Escape-/Ausgabestatus vor privaten Daten sperren; keine gewöhnlichen Summary-/Serialize-Records. Echte Verweigerung vor jedem Sink-Callback, bestehende Authentisierungs-/Schema-/Grenztests erhalten. No-API-Laufzeitprüfung auf alle vier nativen Plattformen erweitern; Rechte und genehmigtes eigenes CI-Lockbudget unverändert. EN: Source-bound strict integrated acceptance; same CLI/JSON/archive contracts, no new unsafe/dependency. Joint R7/R8 remains Draft; other text/CLI/API/process/helper/host obligations remain open. Refs #147. --- .github/workflows/ci.yml | 5 +- docs/ROADMAP.md | 4 +- docs/SPEC.en.md | 5 + docs/SPEC.md | 5 + .../PROTECTED_LIST_OUTPUT_VALIDATION.md | 103 +++++++ docs/security/PROTECTED_REPORT_VALIDATION.md | 31 ++- docs/security/SECRET_LIFETIME_INVENTORY.md | 8 + docs/security/SECRET_LIFETIME_REMEDIATION.md | 8 + src/cli/list_cmd.rs | 10 +- src/cli/list_cmd_tests.rs | 131 +++++++++ src/cli/list_json.rs | 119 ++++----- src/files/confidential_entries.rs | 4 + src/files/confidential_entries_iter.rs | 56 ++++ src/files/confidential_entries_iter_tests.rs | 161 +++++++++++ src/files/confidential_os_text.rs | 2 - src/files/confidential_os_text_tests.rs | 6 + src/files/confidential_os_text_windows.rs | 4 + src/files/confidential_text.rs | 8 + src/files/mod.rs | 2 +- src/security/output.rs | 4 + src/security/output_metadata.rs | 209 +++++++++++++++ src/security/output_metadata_tests.rs | 251 ++++++++++++++++++ 22 files changed, 1056 insertions(+), 80 deletions(-) create mode 100644 docs/security/PROTECTED_LIST_OUTPUT_VALIDATION.md create mode 100644 src/files/confidential_entries_iter.rs create mode 100644 src/files/confidential_entries_iter_tests.rs create mode 100644 src/security/output_metadata.rs create mode 100644 src/security/output_metadata_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index deefb57..9c95502 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,10 +87,9 @@ jobs: run: | if command -v python3 >/dev/null; then py=python3; else py=python; fi "$py" scripts/ci_locked_exec.py test - # DE: Laufzeit ohne API auf je einer nativen Linux-/Windows-Plattform (#151). - # EN: Runtime without API on one native Linux/Windows platform each (#151). + # DE: Ohne API ebenfalls auf allen vier nativen Plattformen prüfen (#147, #151). + # EN: Also test without API on all four native platforms (#147, #151). - name: Tests ohne API / tests without API - if: matrix.os == 'ubuntu-latest' || matrix.os == 'windows-latest' shell: bash run: | if command -v python3 >/dev/null; then py=python3; else py=python; fi diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2ce8b02..d1b24de 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -225,5 +225,5 @@ EN: No partial Main merge or overall R7/R8 closure; Windows traversal/output/rep DE: R7/R8 weiter In progress in genau Draft355. Linux-Traversierung8ca6fb7 lokal vollständig geprüft und veröffentlicht, native Gesamtabnahme läuft. Windows-NT-Caller/echte gesperrte SDK-Fixtures lokal in Prüfung; keine vorgezogene Windows-Walker-/Helper-/Host-Abnahme. EN: Same joint PR, no partial Main merge or scope closure. -DE: R7/R8 weiter In progress: Windows-NT-Adapter aae9a vollständig nativ abgenommen, alle25 Checks erfolgreich. Produktive Windows-Traversierung mit geschützten WTF8-/UTF16-/Namensarenen lokal angebunden; vollständiger lokaler Quellencheckpoint mit16 Kommandos/918 unveränderten Quellen bestanden; native Produktionsabnahme ausstehend. Verbindlicher Stand und offene Gesamtverträge: security/WINDOWS_TRAVERSAL_VALIDATION.md. -EN: Same Draft355; native production acceptance pending, no whole R7/R8 closure. +DE: R7/R8 weiter In progress in genau Draft355: produktive Windows-Traversierung samt Main361 an feb4e2e und vollständiger gesperrter Report-Record an dd36dc5 jeweils mit allen25 Checks und vier vollständigen nativen Rust-Logs abgenommen. Erfolgreiches Listing-JSON erhält geschützten Cursor/Zahlen-/Escape-Encoder; neue native Abnahme ausstehend. Aktuelle Teilnachweise: security/WINDOWS_TRAVERSAL_VALIDATION.md, PROTECTED_REPORT_VALIDATION.md und PROTECTED_LIST_OUTPUT_VALIDATION.md. +EN: Same joint Draft355, no partial Main merge or whole R7/R8 closure. Text/other CLI/API/outer listing, target/temp/identity, verified platform/native-helper/host contracts and source-race338 remain open. Expand existing no-API native runtime checks to all four platforms; unchanged permissions and approved own-CI lock budget. diff --git a/docs/SPEC.en.md b/docs/SPEC.en.md index f689869..b4b82fe 100644 --- a/docs/SPEC.en.md +++ b/docs/SPEC.en.md @@ -13,6 +13,11 @@ > no `Default`. Prepare the report before producer output; lock refusal is an error. > Ordinary CLI/JSON/transport buffers remain open. [Evidence and migration](security/PROTECTED_REPORT_VALIDATION.md). +> R8 listing JSON: prelock actual borrow cursor, number/escape/output state before +> private population; no ordinary Summary/Value/Serialize records in this success +> caller. Convert the source lossily directly into protected storage. Text/other +> CLI/API paths remain open; [scope and acceptance](security/PROTECTED_LIST_OUTPUT_VALIDATION.md). + > R8 follow-up in PR355: hidden signing-key construction, encoding and verification > use prelocked workspaces including identity-derived matrices and SHAKE128 scratch, > without ordinary Signature/cache copies in these paths. Implemented in the joint draft; diff --git a/docs/SPEC.md b/docs/SPEC.md index 616368e..f94fc05 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -13,6 +13,11 @@ > Bericht vor Produzentenausgabe vorbereiten; Speicherverweigerung ist ein Fehler. > Gewöhnliche CLI-/JSON-/Transportpuffer bleiben offen. [Nachweise und Migration](security/PROTECTED_REPORT_VALIDATION.md). +> R8-Listing-JSON: Tatsächlichen Borrow-Cursor, Zahlen-/Escape-/Ausgabestatus vor +> privater Befüllung sperren; keine gewöhnlichen Summary-/Value-/Serialize- +> Records in diesem erfolgreichen Aufrufer. Quelle direkt gesperrt verlustbehaftet +> konvertieren. Text-/übrige CLI-/API-Pfade bleiben offen; [Umfang und Abnahme](security/PROTECTED_LIST_OUTPUT_VALIDATION.md). + > R8-Folgebaustein in PR355: Verborgener Signierschlüssel-Aufbau, Kodierung und > Verifikation verwenden vorab gesperrte Arbeitsflächen einschließlich Identitäts- > matrix und SHAKE128-Scratch; keine gewöhnlichen Signature-/Cache-Kopien in diff --git a/docs/security/PROTECTED_LIST_OUTPUT_VALIDATION.md b/docs/security/PROTECTED_LIST_OUTPUT_VALIDATION.md new file mode 100644 index 0000000..7efa86a --- /dev/null +++ b/docs/security/PROTECTED_LIST_OUTPUT_VALIDATION.md @@ -0,0 +1,103 @@ +# Protected listing output / Geschützte Listing-Ausgabe + +DE: M5-Teil des gemeinsamen R7/R8-Draft355. Der tatsächliche erfolgreiche +JSON-Listing-Aufrufer verwendet keine gewöhnlichen Summary-/Entry-Serialize- +Records und keinen privaten itoa-/JSON-Escape-Scratch mehr. Das ist kein +Gesamtabschluss von Listing/Text/CLI/API/Prozess-/Helper-/Host-Verträgen. +EN: Protect reached internal formatter retention, not merely borrowed source +path bytes. Preserve the existing pqkeep-list/1 bytes and authentication gate. + +## Actual ownership / Tatsächliches Eigentum + +DE: DisclosureWriter sperrt den vollständigen leeren State, bevor Zielwriter, +private Zahl oder Cursor übernommen werden. Zielborrow, Quotient, Positionen, +20 Dezimalstellen, sechs Escape-Bytes und Fehlerstatus gemeinsam in SecretState. +Nur öffentliche None-/Nullwerte vor der Sperre; niemals private Daten in einen +gewöhnlichen Puffer schreiben und ihn erst danach sperren. +EN: The existing output adapter supplies an owned unbuffered Unix stdout handle +or the verified locked Windows Unicode/redirected output path. Generic callers +must separately own their input and sink policy; this helper cannot protect an +external BufWriter, caller allocation, OS queue or kernel memory retrospectively. + +DE: Dezimalziffern ausschließlich in gesperrten Scratch schreiben, danach löschen. +JSON-UTF8 direkt ausleihen; Anführungszeichen, Backslash und ASCII-Steuerzeichen +ohne privaten String oder Stack-Escapearray kodieren. UTF8 jenseits der ASCII- +Steuerzeichen unverändert ausleihen. Keine neue Normalisierung oder Decoderlogik. +EN: Actual formatter arrays and cursor records stay locked throughout output. +Scalar ABI/compiler copies remain explicit boundaries; ordinary retained +application records are not renamed as compiler temporaries. + +DE: Vor jedem Write/Flush Fehlerstatus setzen und erst nach Erfolg zurücksetzen. +Fehler oder Unwind vergiften diesen Writer; nachfolgende Write-/Flush-Aufrufe +verweigern ohne erneuten Sink-Callback. Drop löscht alle Scratch-/Cursorfelder +und den Borrow; SecretState löscht die vollständige Allokation samt Padding +vor Unlock/Free. Bei Lockfehler erfolgt kein Zielcallback. +EN: External I/O may fail after already authorized bytes were delivered. The +operation returns that failure and does not attempt a second JSON envelope. + +## Actual listing caller / Tatsächlicher Listing-Aufrufer + +DE: ConfidentialEntries::try_iter() sperrt den konkreten Quellborrow und die +laufende Position vor Nutzung; rewind() benötigt keine neue Allokation. Alter +Deref-/Borrow-Vertrag bleibt für externe Rust-Caller kompatibel. Der interne +JSON-Aufrufer verwendet den geschützten Cursor, prüft sämtliche Pfad-Borrows +vorab und sperrt auch den Encoder vor der ersten Ausgabe. Erster Eintrag und +Restiteration vermeiden einen zusätzlichen gewöhnlichen privaten Kommazähler. +EN: Serialize borrowed entry fields and report getters directly. No ordinary +Summary/Entry struct, Value tree, output collection or serializer scratch is +created in this successful listing path. Preserve null sizes, full-width u64, +field order, source, authentication marker, schema and the terminating newline. + +DE: ConfidentialText::from_os_lossy() verwendet die vorhandene geschützte +OS-Text-Konvertierung statt to_string_lossy()-Cow. Windows: vorhandenen vorab +gesperrten EncodeWide-/Pending-Surrogate-Zustand wiederverwenden; kein privater +UTF16-Vec oder gewöhnlicher Verlusttext. Quell-ArgMatches/PathBuf sind dadurch +nicht nachträglich geschützt und bleiben Teil des offenen CLI-Ingress-Vertrags. +EN: This is an additive fallible Rust API, with no CLI/JSON/archive schema change. +Existing root unsafe prohibition and provider/platform/dependency bytes remain. + +## Verification / Prüfung + +DE: Öffentliche Referenzfixtures vergleichen sämtliche u16-Zahlen, Zehnergrenzen, +u64::MAX und10.000 vollständige u64-Stichproben exakt mit std-Dezimalbytes. Alle +Unicode-Skalare einschließlich sämtlicher ASCII-Kontrollzeichen exakt gegen +serde_json escapen und wieder decodieren. Keine privaten Nutzerwerte im Oracle. +EN: Actual record/field/page observations, move, explicit locked wipe, writer +failure/flush/panic poison and bounded own-child cleanup/denial are required. +Retain allocations until real MemoryLock rather than inferring denial from a +zero budget. Parent limits stay unchanged; no privilege or host-policy increase. + +DE: Echte CLI-Ausgabe prüft exakte Schema-Bytes für Ordner/null, u64-Maxima und +Steuerzeichen. Eigenes begrenztes Kind ruft denselben list_json::write unter +nachgewiesener Sperrverweigerung auf: kein Write/Flush-Callback und unveränderter +Bericht, anschließend exakte Registry-Baseline. Pfad-/Iterator-/Writer-Unwind +und reale Kernel-Baselines zusätzlich im Bibliothekstest prüfen. +EN: Existing late-authentication/tamper/no-partial-list, both languages, sandbox, +write/flush/broken-pipe, source access and listing limits remain acceptance gates. + +DE: Integrierter protected-disclosure-integrated-v2 besteht alle15 Kommandos +auf924 unveränderten Rust-/Manifest-Hashes: vier strenge Root-Lints für Linux/ +Windows mit/ohne API, fünf echte CLI-Ausgabegruppen, je sechs Encodergruppen +und119 Dateigruppen pro Featurekonfiguration sowie15 Integrationen in vier +Gruppen. Tatsächliche Zero-output-Verweigerung und maximale Listengrenzen +bestanden; explizite Kind-Einstiege bleiben sichtbar ignoriert. Test-Formlints +ohne neue Allow-Ausnahme korrigiert und fehlgeschlagene Protokolle behalten. +Noch keine vollständige native Encoder-/Caller-Abnahme behauptet. +EN: Full Windows/Linux/ARM64 native acceptance and exact source-bound strict +lint/format/limits/audit checks remain required before accepting this component. + +## Still open / Weiter offen + +DE/EN: Listing text/Debug formatting, general CLI/context/progress/check/files +JSON, API serialization/transport and outer listing ownership; other source +ingress, target/temp/cleanup/identity and full platform/native-helper/library- +host contracts remain open. Source-race338 and final joint R7/R8 acceptance +remain open. No partial Main merge, release/install/deletion or host change. + +DE: Bestehenden No-API-Laufzeitschritt auf alle vier nativen CI-Plattformen +erweitert, bisher nur latest/Windows. Keine Rechte-/Pinning-/Budgetänderung. +Eigene Workflow-Regeln, Regeltests und vorhandene Runner-Tests bestehen drei +quellgebundene Prüfungen; erster falscher Python-Importaufruf erhalten und +durch den vorgesehenen Discovery-Aufruf ersetzt, keine Code-/Regelabschwächung. +EN: Full native acceptance now requires both feature configurations on Ubuntu22, +ARM64, latest and Windows; keep the scoped own Linux-CI2GiB memlock allowance. diff --git a/docs/security/PROTECTED_REPORT_VALIDATION.md b/docs/security/PROTECTED_REPORT_VALIDATION.md index 4e7cc8d..e99077d 100644 --- a/docs/security/PROTECTED_REPORT_VALIDATION.md +++ b/docs/security/PROTECTED_REPORT_VALIDATION.md @@ -1,6 +1,6 @@ # Protected report retention / Geschützte Berichtsretention -DE: Lokaler M5-Teil des gemeinsamen R7/R8-Draft355. Keine Gesamtfreigabe: +DE: M5-Teil des gemeinsamen R7/R8-Draft355. Keine Gesamtfreigabe: CLI-/JSON-/Format-/Transportpuffer und übrige Prozess-/Helper-/Host-Verträge bleiben ausdrücklich erforderlich. Implementierung und Abnahme unterscheiden. EN: Protect the actual retained report, not only its nested identity/path bytes. @@ -42,7 +42,7 @@ and text counts. They still require separate protected formatting/escaping and transport workspaces. Copying a count into an ordinary serialization Summary or serde_json::Value is not declared safe by protecting its source report. -## Evidence still required / Noch erforderliche Nachweise +## Checks and local evidence / Prüfungen und lokale Nachweise DE: Neue Tests prüfen den tatsächlichen vollständigen Record und seine Felder, Move, bewusstes Ausleihen, redigiertes Debug, Gleichheit, Überläufe und expliziten @@ -62,8 +62,8 @@ begrenzten Kindern, vier strenge Root-Lints für Linux/Windows mit/ohne API, Fmt/Limits/Diff. Reale Stream-API unter echter Sperrverweigerung aufgerufen: kein Source-Read, Target-Write oder Flush, Standard-KDF-Parameter unverändert. Vorherige Lintfehler in Testaufrufern ohne neue Allow-Ausnahmen behoben und -Fehlerprotokolle behalten. Integrierte Gesamt-/native Abnahme steht aus; noch -nicht veröffentlicht. Kein R7/R8-Gesamtabschluss. +Fehlerprotokolle behalten. Die folgenden Abschnitte ersetzen diesen lokalen +Zwischenstand durch integrierte/native Nachweise. Kein R7/R8-Gesamtabschluss. EN: No new dependency, unsafe, privileged test, installation or Main merge. DE: Integrierter protected-report-integrated-v1 besteht alle17 Kommandos auf920 @@ -76,4 +76,25 @@ Vendor-/Angriffsmatrix-/Lizenzprüfer, Format/Limits/Diff erfolgreich. EN: Three actual list output unit tests also pass: borrowed schema/escaping, terminal quoting and write/flush failures. Additional list/check/stream acceptance passes27 integrations in seven groups on the same920 unchanged source hashes. Both source-bound commands pass. -Complete native report acceptance remains pending. +The following section records the native acceptance of this component. + +## Native acceptance / Native Abnahme + +DE: Signierter dd36dc57cf707de04da3c5a36e81cb1eed21a269 besteht alle25 Checks, +einschließlich acht Fuzz-Zielen, MSRV, Audit-/Historienprüfung und genehmigter +eigener Windows-Zugriffsprobe. Vier vollständige native Logs mit Job-Head und +SHA-256 geprüft: Linux22/ARM je997 Tests/121 Gruppen, latest1915/240, +Windows1741/243, null Fehler. Tatsächliche Reportfälle: Linux22/ARM je fünf +im Default-Lauf, latest zehn in beiden Konfigurationen und Windows acht in +beiden Konfigurationen; dort ist die Linux-Verweigerung nicht ausführbar. +EN: Physical Windows record/field/page observations, move/disclosure, checked +overflow, locked wipe and bounded own cleanup/unwind actually run in both +configurations. Ignored child entries are not counted as passed tests. Real +Linux factory denial and zero-I/O stream refusal execute through their parent. +Full CLI/JSON/transport and joint R7/R8 acceptance remain open. + +DE: Vollständiges dd36-Bundle unabhängig wiederhergestellt: strict fsck und +komplette Head-/Main-Baum-/Blob-/Modusvergleiche erfolgreich. Separater Reverse- +Index stellt exakt Main361-Baum9959b2be wieder her; keine Arbeitsdatei gelöscht. +EN: protected-report-dd36-independent-restore-proof and retained reverse patch +record the practical code rollback; no production revert or partial Main merge. diff --git a/docs/security/SECRET_LIFETIME_INVENTORY.md b/docs/security/SECRET_LIFETIME_INVENTORY.md index 9ba972b..e60979a 100644 --- a/docs/security/SECRET_LIFETIME_INVENTORY.md +++ b/docs/security/SECRET_LIFETIME_INVENTORY.md @@ -159,4 +159,12 @@ skip/sender presence before population. Fallible construction precedes output; explicit getters replace public fields/Default. CLI context and ordinary Summary, Value, formatting and transport buffers remain open; protecting a source does not protect its recipient. See [report evidence](PROTECTED_REPORT_VALIDATION.md). + +DE: Erfolgreiches Listing-JSON verwendet nun den vorab gesperrten tatsächlichen +Borrow-Cursor sowie Zahlen-/Escape-/Ausgabestatus statt gewöhnlicher Summary-/ +Serialize-Records und privatem itoa-/Escape-Scratch. Quellname direkt geschützt +verlustbehaftet konvertieren; gemeinsamer R7/R8-Draft, native Abnahme ausstehend. +EN: Successful listing JSON borrows protected records directly through a prelocked +cursor and encoder, with no ordinary result collection. Text/other CLI/API paths +and outer listing ownership remain open; [scope](PROTECTED_LIST_OUTPUT_VALIDATION.md). Source-race338 and complete process/helper/host contracts remain open. diff --git a/docs/security/SECRET_LIFETIME_REMEDIATION.md b/docs/security/SECRET_LIFETIME_REMEDIATION.md index 86fee5f..a8ee181 100644 --- a/docs/security/SECRET_LIFETIME_REMEDIATION.md +++ b/docs/security/SECRET_LIFETIME_REMEDIATION.md @@ -125,6 +125,14 @@ vor Ausgabe erhalten. Keine globale JSON-/Pfadtypänderung ohne gesonderten Komp EN: Define a reviewed confidential-metadata contract; preserve current authenticated listing and opt-in disclosure. A key-material wrapper alone does not settle metadata policy. +DE: Gemeinsamer genehmigter Plan: PROCESS_METADATA_COMPLETION_PLAN. Tatsächlicher +Report-Record an dd36dc5 mit vier vollständigen nativen Läufen abgenommen; neue +Listing-JSON-Arbeit schützt konkreten Cursor sowie Zahlen-/Escape-/Ausgabestatus +und entfernt gewöhnliche Summary-/Serialize-Records in diesem Aufrufer. +EN: See PROTECTED_REPORT_VALIDATION and PROTECTED_LIST_OUTPUT_VALIDATION for +exact sources, caller/denial evidence and remaining boundaries. Text/other CLI, +API/transport and outer listing ownership remain open; no whole R8 closure. + ## Release gates and rollback / Abnahme und Rückweg DE: Für jede Laufzeitnacharbeit: fmt, beide Clippy-/Feature-Konfigurationen, echte native diff --git a/src/cli/list_cmd.rs b/src/cli/list_cmd.rs index d3be400..71d18d9 100644 --- a/src/cli/list_cmd.rs +++ b/src/cli/list_cmd.rs @@ -94,10 +94,16 @@ pub fn run_json(t: &Texts, lang: Lang, m: &ArgMatches) -> CliResult { Err(error) => return super::json_out::failed("list", &error), }; let source = super::files_cmd::source(m); + let source = files::ConfidentialText::from_os_lossy(source.as_os_str()) + .map_err(|e| Failure::from_error(&e, lang))?; let mut out = super::secret_input::stdout_file().map_err(|e| Failure::from_error(&e.into(), lang))?; - super::list_json::write(&mut out, &listing, &source.to_string_lossy()) - .map_err(|_| Failure::new(code::ERROR, "Ausgabe fehlgeschlagen / output failed")) + super::list_json::write( + &mut out, + &listing, + source.expose().map_err(|e| Failure::from_error(&e, lang))?, + ) + .map_err(|_| Failure::new(code::ERROR, "Ausgabe fehlgeschlagen / output failed")) } /// DE: Fallible Ausgabe auch für frühe JSON-Fehler. EN: Fallible output for early JSON errors too. diff --git a/src/cli/list_cmd_tests.rs b/src/cli/list_cmd_tests.rs index b8b61c8..fa3ca79 100644 --- a/src/cli/list_cmd_tests.rs +++ b/src/cli/list_cmd_tests.rs @@ -90,3 +90,134 @@ fn text_quotes_names_and_json_is_one_line() { "ä/b" ); } + +#[test] +fn locked_listing_json_matches_exact_schema_bytes_for_null_maxima_and_controls() { + let path = "line\0\n\t\"\\\u{202e}😀"; + let source = "public\nsource"; + let listing = Listing { + entries: vec![ + files::ListEntry { + path: files::ConfidentialText::from_text("directory").unwrap(), + kind: EntryKind::Directory, + bytes: None, + }, + files::ListEntry { + path: files::ConfidentialText::from_text(path).unwrap(), + kind: EntryKind::File, + bytes: Some(u64::MAX), + }, + ] + .try_into() + .unwrap(), + report: files::Report::with_counts(u64::MAX, u64::MAX, u64::MAX).unwrap(), + }; + let value = json!({ + "authentication":"container_integrity", "command":"list", "exit_code":0, + "ok":true, "schema":SCHEMA, "source":source, + "entries":[{"bytes":null,"kind":"directory","path":"directory"}, + {"bytes":u64::MAX,"kind":"file","path":path}], + "summary":{"bytes":u64::MAX,"directories":u64::MAX,"files":u64::MAX} + }); + let mut expected = serde_json::to_vec(&value).unwrap(); + expected.push(b'\n'); + let mut actual = Vec::new(); + super::super::list_json::write(&mut actual, &listing, source).unwrap(); + assert_eq!(actual, expected); +} + +#[cfg(target_os = "linux")] +#[test] +fn actual_listing_output_lock_denial_runs_bounded_and_preserves_parent_limit() { + use rustix::process::{Resource, getrlimit}; + use std::{ + process::{Command, Stdio}, + time::{Duration, Instant}, + }; + let before = getrlimit(Resource::Memlock); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "cli::list_cmd::tests::locked_list_denial_child", + "--ignored", + "--test-threads=1", + ]) + .env("PQKEEP_LOCKED_LIST_DENIAL_CHILD", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success()); + let output = child.wait_with_output().unwrap(); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed")); + break; + } + if Instant::now() >= deadline { + child.kill().unwrap(); + child.wait().unwrap(); + assert!( + Instant::now() < deadline, + "own listing denial child timed out" + ); + } + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[derive(Default)] +struct Untouched(usize); +#[cfg(target_os = "linux")] +impl Write for Untouched { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 += 1; + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + self.0 += 1; + Ok(()) + } +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur begrenztes eigenes Kind / bounded own child only"] +fn locked_list_denial_child() { + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!( + std::env::var("PQKEEP_LOCKED_LIST_DENIAL_CHILD").unwrap(), + "1" + ); + let listing = Listing { + entries: files::ConfidentialEntries::default(), + report: files::Report::with_counts(3, 5, 7).unwrap(), + }; + let mut retained = Vec::with_capacity(4096); + let mut output = Untouched::default(); + drop(listing.entries.try_iter().unwrap()); + let baseline = pqkeep::hardening::memlock::stats().locked_pages; + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + let mut denied = false; + for _ in 0..4096 { + match listing.entries.try_iter() { + Ok(iter) => retained.push(iter), + Err(error) => { + assert_eq!(error, pqkeep::Error::MemoryLock); + denied = true; + break; + } + } + } + assert!(denied); + assert!(super::super::list_json::write(&mut output, &listing, "public fixture").is_err()); + assert_eq!(output.0, 0); + assert_eq!(listing.report.bytes(), 7); + drop(retained); + assert_eq!(pqkeep::hardening::memlock::stats().locked_pages, baseline); +} diff --git a/src/cli/list_json.rs b/src/cli/list_json.rs index 7388eb3..9a347e8 100644 --- a/src/cli/list_json.rs +++ b/src/cli/list_json.rs @@ -1,77 +1,66 @@ -//! DE: Geprüfte Pfade als Borrowed Views direkt serialisieren, ohne Value-Kopien. -//! EN: Serialize verified paths as borrowed views directly, without Value copies. - -use pqkeep::files::{EntryKind, ListEntry, Listing}; -use serde::{Serialize, Serializer, ser::SerializeSeq}; +//! DE: Geprüfte Metadaten ohne gewöhnliche Summary-/Value-/Zahlen-/Escape-Records ausgeben. +//! EN: Disclose verified metadata without ordinary summary/value/number/escape records. +use pqkeep::{ + files::{EntryKind, ListEntry, Listing, Report}, + security::output::DisclosureWriter, +}; use std::io::{self, Write}; -struct Entries<'a>(&'a [ListEntry]); - -#[derive(Serialize)] -struct Entry<'a> { - bytes: Option, - kind: &'static str, - path: &'a str, +fn unavailable() -> io::Error { + io::Error::other("protected listing output unavailable") } -impl Serialize for Entries<'_> { - fn serialize(&self, serializer: S) -> Result { - let mut sequence = serializer.serialize_seq(Some(self.0.len()))?; - for entry in self.0 { - let path = entry - .path - .expose() - .map_err(|_| serde::ser::Error::custom("invalid protected archive path"))?; - let kind = match entry.kind { - EntryKind::File => "file", - EntryKind::Directory => "directory", - }; - sequence.serialize_element(&Entry { - bytes: entry.bytes, - kind, - path, - })?; - } - sequence.end() +fn entry(out: &mut DisclosureWriter<'_, W>, entry: &ListEntry) -> io::Result<()> { + out.write_text("{\"bytes\":")?; + match entry.bytes { + Some(bytes) => out.write_u64(bytes)?, + None => out.write_text("null")?, } + out.write_text(",\"kind\":")?; + out.write_json_string(match entry.kind { + EntryKind::File => "file", + EntryKind::Directory => "directory", + })?; + out.write_text(",\"path\":")?; + out.write_json_string(entry.path.expose().map_err(|_| unavailable())?)?; + out.write_text("}") } -#[derive(Serialize)] -struct Summary { - bytes: u64, - directories: u64, - files: u64, -} - -#[derive(Serialize)] -struct Envelope<'a> { - authentication: &'static str, - command: &'static str, - entries: Entries<'a>, - exit_code: u8, - ok: bool, - schema: &'static str, - source: &'a str, - summary: Summary, +fn summary(out: &mut DisclosureWriter<'_, W>, report: &Report) -> io::Result<()> { + out.write_text("{\"bytes\":")?; + out.write_u64(report.bytes())?; + out.write_text(",\"directories\":")?; + out.write_u64(report.directories())?; + out.write_text(",\"files\":")?; + out.write_u64(report.files())?; + out.write_text("}") } pub(super) fn write(out: &mut impl Write, listing: &Listing, source: &str) -> io::Result<()> { - let report = &listing.report; - let envelope = Envelope { - authentication: "container_integrity", - command: "list", - entries: Entries(&listing.entries), - exit_code: 0, - ok: true, - schema: super::list_cmd::SCHEMA, - source, - summary: Summary { - bytes: report.bytes(), - directories: report.directories(), - files: report.files(), - }, - }; - serde_json::to_writer(&mut *out, &envelope).map_err(io::Error::other)?; - out.write_all(b"\n")?; + // DE: Cursor und Encoder vor Ausgabe sperren, alle Pfad-Borrows vorab prüfen. + // EN: Lock cursor/encoder before output and validate every path borrow first. + let mut entries = listing.entries.try_iter().map_err(|_| unavailable())?; + for entry in entries.by_ref() { + entry.path.expose().map_err(|_| unavailable())?; + } + entries.rewind(); + let mut out = DisclosureWriter::new(out).map_err(|_| unavailable())?; + out.write_text( + "{\"authentication\":\"container_integrity\",\"command\":\"list\",\"entries\":[", + )?; + if let Some(first) = entries.next() { + entry(&mut out, first)?; + for item in entries { + out.write_text(",")?; + entry(&mut out, item)?; + } + } + out.write_text("],\"exit_code\":0,\"ok\":true,\"schema\":")?; + out.write_json_string(super::list_cmd::SCHEMA)?; + out.write_text(",\"source\":")?; + out.write_json_string(source)?; + out.write_text(",\"summary\":")?; + summary(&mut out, &listing.report)?; + out.write_text("}\n")?; out.flush() } diff --git a/src/files/confidential_entries.rs b/src/files/confidential_entries.rs index 5a30cf3..a9c5ba8 100644 --- a/src/files/confidential_entries.rs +++ b/src/files/confidential_entries.rs @@ -5,6 +5,10 @@ use super::{ConfidentialText, EntryKind, ListEntry, MAX_LIST_ENTRIES, archive::E use crate::{Error, Result, crypto::secret_workspace::SecretWorkspace}; use std::{fmt, ops::Deref, slice}; +#[path = "confidential_entries_iter.rs"] +mod iterator; +pub use iterator::ConfidentialIter; + /// DE: Vertrauliche Listeneinträge; Ausleihen ist eine bewusste Ausgabegrenze. /// EN: Confidential listing records; borrowing is an explicit disclosure boundary. #[derive(Default)] diff --git a/src/files/confidential_entries_iter.rs b/src/files/confidential_entries_iter.rs new file mode 100644 index 0000000..05679bf --- /dev/null +++ b/src/files/confidential_entries_iter.rs @@ -0,0 +1,56 @@ +//! DE: Tatsächlichen Listen-Borrow-Cursor vor privater Quelle/Position sperren. +//! EN: Prelock the actual listing borrow cursor before private source/position. +use super::{ConfidentialEntries, ListEntry}; +use crate::{Result, crypto::secret_state::SecretState}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +struct State<'a> { + source: Option<&'a ConfidentialEntries>, + position: usize, +} +impl Drop for State<'_> { + fn drop(&mut self) { + self.source = None; + self.position.zeroize(); + } +} +impl ZeroizeOnDrop for State<'_> {} + +/// DE: Gesperrter fallibler Listen-Cursor; Einträge nur bewusst ausleihen. +/// EN: Locked fallible listing cursor; explicitly borrow entries only. +pub struct ConfidentialIter<'a>(SecretState>); + +impl ConfidentialEntries { + /// DE: Leeren Cursor sperren, bevor Quelle/Position übernommen werden. + /// EN: Lock the empty cursor before assigning its source/position. + /// # Errors + /// DE/EN: [`crate::Error::MemoryLock`] bei Sperrverweigerung / on lock refusal. + pub fn try_iter(&self) -> Result> { + let mut out = ConfidentialIter(SecretState::new(State { + source: None, + position: 0, + })?); + out.0.get_mut().source = Some(self); + Ok(out) + } +} +impl ConfidentialIter<'_> { + /// DE: Bereits gesperrten Cursor ohne Allokation zurücksetzen. + /// EN: Rewind the already locked cursor without allocation. + pub fn rewind(&mut self) { + self.0.get_mut().position = 0; + } +} +impl<'a> Iterator for ConfidentialIter<'a> { + type Item = &'a ListEntry; + fn next(&mut self) -> Option { + let state = self.0.get_mut(); + let entry = state.source?.get(state.position)?; + state.position += 1; + Some(entry) + } +} + +#[cfg(test)] +#[path = "confidential_entries_iter_tests.rs"] +mod tests; diff --git a/src/files/confidential_entries_iter_tests.rs b/src/files/confidential_entries_iter_tests.rs new file mode 100644 index 0000000..19b933f --- /dev/null +++ b/src/files/confidential_entries_iter_tests.rs @@ -0,0 +1,161 @@ +//! DE: Tatsächlichen Listen-Cursor, Move, Verweigerung und Cleanup prüfen. +//! EN: Check actual listing cursor, moves, refusal and cleanup. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::{ + files::{ConfidentialText, EntryKind}, + locked_owner_test_support::{isolated_test, locked}, +}; + +fn fixture() -> ConfidentialEntries { + vec![ListEntry { + path: ConfidentialText::from_text("public fixture").unwrap(), + kind: EntryKind::File, + bytes: Some(u64::MAX), + }] + .try_into() + .unwrap() +} + +fn physical(iter: &ConfidentialIter<'_>) { + let state = iter.0.get(); + locked(state); + locked(&state.source); + locked(&state.position); + #[cfg(windows)] + { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(state).addr(); + for offset in (0..size_of_val(state)).step_by(region::page::size()) { + assert!(query.get_mut().is_locked(start + offset).unwrap()); + } + assert!( + query + .get_mut() + .is_locked(start + size_of_val(state) - 1) + .unwrap() + ); + } +} + +#[test] +fn actual_cursor_source_position_and_borrowed_records_stay_locked_through_move_and_rewind() { + let source = fixture(); + let mut iter = source.try_iter().unwrap(); + physical(&iter); + let first = iter.next().unwrap(); + locked(first); + first.path.assert_owner_locked(); + assert_eq!(first.bytes, Some(u64::MAX)); + assert!(iter.next().is_none()); + let mut moved = Box::new(iter); + physical(&moved); + moved.rewind(); + assert!(std::ptr::eq(moved.next().unwrap(), first)); + let empty = ConfidentialEntries::default(); + let mut empty = empty.try_iter().unwrap(); + physical(&empty); + assert!(empty.next().is_none()); + empty.rewind(); + assert!(empty.next().is_none()); +} + +#[test] +fn actual_cursor_unwind_and_cleanup_execute_in_bounded_own_child() { + isolated_test( + "files::confidential_entries::iterator::tests::cleanup_child", + "PQKEEP_LIST_CURSOR_CLEANUP_CHILD", + ); +} + +#[test] +#[ignore = "DE/EN: Nur begrenztes eigenes Kind / bounded own child only"] +fn cleanup_child() { + assert_eq!( + std::env::var("PQKEEP_LIST_CURSOR_CLEANUP_CHILD").unwrap(), + "1" + ); + let source = fixture(); + drop(source.try_iter().unwrap()); + let baseline = snapshot(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut iter = source.try_iter().unwrap(); + assert!(iter.next().is_some()); + physical(&iter); + std::panic::resume_unwind(Box::new(())); + })); + assert!(result.is_err()); + assert_eq!(snapshot(), baseline); +} + +fn snapshot() -> (usize, usize) { + let pages = crate::hardening::memlock::stats().locked_pages; + #[cfg(target_os = "linux")] + { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let bytes = status + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024; + (pages, bytes) + } + #[cfg(not(target_os = "linux"))] + { + (pages, 0) + } +} + +#[cfg(target_os = "linux")] +#[test] +fn real_cursor_denial_preserves_existing_source_and_parent_limits() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + isolated_test( + "files::confidential_entries::iterator::tests::denial_child", + "PQKEEP_LIST_CURSOR_DENIAL_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur begrenztes eigenes Kind / bounded own child only"] +fn denial_child() { + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!( + std::env::var("PQKEEP_LIST_CURSOR_DENIAL_CHILD").unwrap(), + "1" + ); + let source = fixture(); + let mut original = source.try_iter().unwrap(); + let mut retained = Vec::with_capacity(2048); + let baseline = snapshot(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + let mut denied = false; + for _ in 0..2048 { + match source.try_iter() { + Ok(iter) => retained.push(iter), + Err(error) => { + assert_eq!(error, crate::Error::MemoryLock); + denied = true; + break; + } + } + } + assert!(denied); + physical(&original); + assert_eq!(original.next().unwrap().bytes, Some(u64::MAX)); + assert!(original.next().is_none()); + source[0].path.assert_owner_locked(); + drop(retained); + assert_eq!(snapshot(), baseline); +} diff --git a/src/files/confidential_os_text.rs b/src/files/confidential_os_text.rs index 7916a69..1e0dcb1 100644 --- a/src/files/confidential_os_text.rs +++ b/src/files/confidential_os_text.rs @@ -5,7 +5,6 @@ use crate::{ Error, Result, crypto::{SecretBytes, secret_state::SecretState}, }; -#[cfg(any(not(windows), test))] use std::ffi::OsStr; use zeroize::{Zeroize, ZeroizeOnDrop}; @@ -28,7 +27,6 @@ impl Drop for Position { } impl ZeroizeOnDrop for Position {} -#[cfg(not(windows))] pub(super) fn joined_lossy(prefix: &str, name: &OsStr) -> Result { if let Some(valid) = name.to_str() { return ConfidentialText::joined(prefix, valid); diff --git a/src/files/confidential_os_text_tests.rs b/src/files/confidential_os_text_tests.rs index 16631dd..8aaabc0 100644 --- a/src/files/confidential_os_text_tests.rs +++ b/src/files/confidential_os_text_tests.rs @@ -5,6 +5,12 @@ use super::*; fn check(name: &OsStr) { let expected = format!("prefix/{}", name.to_string_lossy()); + let disclosed = ConfidentialText::from_os_lossy(name).unwrap(); + disclosed.assert_owner_locked(); + assert_eq!(disclosed.expose().unwrap(), name.to_string_lossy()); + let joined = joined_lossy("prefix/", name).unwrap(); + joined.assert_owner_locked(); + assert_eq!(joined.expose().unwrap(), expected); #[cfg(not(windows))] let actual = joined_lossy("prefix/", name).unwrap(); #[cfg(windows)] diff --git a/src/files/confidential_os_text_windows.rs b/src/files/confidential_os_text_windows.rs index 974b162..bd811bd 100644 --- a/src/files/confidential_os_text_windows.rs +++ b/src/files/confidential_os_text_windows.rs @@ -3,6 +3,10 @@ use super::{ConfidentialText, Error, Position, Result, SecretState, output}; use crate::files::locked_wide::LockedWide; +pub(super) fn wide_lossy(prefix: &str, source: &std::ffi::OsStr) -> Result { + wide_source(prefix, LockedWide::new(source)?) +} + pub(super) fn wide_lossy_units(prefix: &str, units: &[u16]) -> Result { wide_source(prefix, LockedWide::from_units(units)?) } diff --git a/src/files/confidential_text.rs b/src/files/confidential_text.rs index 22ecea6..d3c7dd4 100644 --- a/src/files/confidential_text.rs +++ b/src/files/confidential_text.rs @@ -47,6 +47,14 @@ impl ConfidentialText { Ok(out) } + /// DE: OS-Text verlustbehaftet direkt gesperrt konvertieren, ohne Cow/String-Kopie. + /// EN: Convert OS text lossily directly in locked storage, without Cow/String staging. + /// # Errors + /// DE/EN: [`Error::MemoryLock`] bei Sperrverweigerung / on lock refusal. + pub fn from_os_lossy(source: &std::ffi::OsStr) -> Result { + super::confidential_os_text::joined_lossy("", source) + } + pub(crate) fn from_locked(bytes: SecretBytes) -> Result { let mut out = Self::prepare()?; *out.0.get_mut() = bytes; diff --git a/src/files/mod.rs b/src/files/mod.rs index a4f1164..bc0772d 100644 --- a/src/files/mod.rs +++ b/src/files/mod.rs @@ -82,7 +82,7 @@ use std::path::Path; pub use crate::fsutil::set_temp_tag; pub use check::{check, check_with}; -pub use confidential_entries::ConfidentialEntries; +pub use confidential_entries::{ConfidentialEntries, ConfidentialIter}; pub use confidential_text::ConfidentialText; pub use decrypt::{decrypt, decrypt_with}; pub use encrypt::{ diff --git a/src/security/output.rs b/src/security/output.rs index d2162ec..ad72c63 100644 --- a/src/security/output.rs +++ b/src/security/output.rs @@ -3,6 +3,10 @@ use std::{fs::File, io}; +#[path = "output_metadata.rs"] +mod metadata; +pub use metadata::DisclosureWriter; + #[cfg(any(windows, test))] #[path = "output_unicode.rs"] mod unicode; diff --git a/src/security/output_metadata.rs b/src/security/output_metadata.rs new file mode 100644 index 0000000..0d7018f --- /dev/null +++ b/src/security/output_metadata.rs @@ -0,0 +1,209 @@ +//! DE: Bewusste Metadatenausgabe mit vorab gesperrtem Zahlen-/Escape-/Cursorzustand. +//! EN: Explicit metadata disclosure with prelocked number/escape/cursor state. +use std::io::{self, Write}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +use crate::{Result, crypto::secret_state::SecretState}; + +const HEX: &[u8; 16] = b"0123456789abcdef"; + +struct State<'a, W: Write> { + output: Option<&'a mut W>, + number: u64, + cursor: usize, + start: usize, + digits: [u8; 20], + escape: [u8; 6], + poisoned: bool, +} + +impl Zeroize for State<'_, W> { + fn zeroize(&mut self) { + self.output = None; + self.number.zeroize(); + self.cursor.zeroize(); + self.start.zeroize(); + self.digits.zeroize(); + self.escape.zeroize(); + self.poisoned.zeroize(); + } +} +impl Drop for State<'_, W> { + fn drop(&mut self) { + self.zeroize(); + } +} +impl ZeroizeOnDrop for State<'_, W> {} + +/// DE: Autorisierte Metadaten ohne gewöhnliche Format-/Zahlen-/Escape-Puffer ausgeben. +/// EN: Disclose authorized metadata without ordinary formatting/number/escape buffers. +/// +/// DE: Erst nach Authentisierung verwenden. Caller verantwortet seine Eingaben und +/// den Zielwriter; dessen eigene Puffer werden hier nicht nachträglich gesperrt. +/// EN: Use only after authentication. The caller owns input and destination policy; +/// this does not retrospectively protect an external writer's own buffers. +pub struct DisclosureWriter<'a, W: Write>(SecretState>); + +impl<'a, W: Write> DisclosureWriter<'a, W> { + /// DE: Vollständigen leeren Record vor Zielzuweisung und erster Ausgabe sperren. + /// EN: Lock the complete empty record before assigning the sink or writing. + /// # Errors + /// DE/EN: [`crate::Error::MemoryLock`] bei Sperrverweigerung / when locking is denied. + pub fn new(output: &'a mut W) -> Result { + let mut state = SecretState::new(State { + output: None, + number: 0, + cursor: 0, + start: 0, + digits: [0; 20], + escape: [0; 6], + poisoned: false, + })?; + state.get_mut().output = Some(output); + Ok(Self(state)) + } + + /// DE: Geschützte Quelle direkt ausleihen; kein Format-/LineWriter-Zwischenpuffer. + /// EN: Borrow the protected source directly, without formatting/LineWriter staging. + /// # Errors + /// DE/EN: Ausgabe- oder vergifteter Zustand / output failure or poisoned state. + pub fn write_text(&mut self, text: &str) -> io::Result<()> { + self.0.get_mut().write(text.as_bytes()) + } + + /// DE: Dezimalzahl ausschließlich im gesperrten Record kodieren. + /// EN: Encode a decimal integer entirely in the locked record. + /// # Errors + /// DE/EN: Ausgabe- oder vergifteter Zustand / output failure or poisoned state. + pub fn write_u64(&mut self, value: u64) -> io::Result<()> { + self.0.get_mut().decimal(value) + } + + /// DE: UTF8 als JSON-String ausleihen; Kontrollzeichen im gesperrten Scratch escapen. + /// EN: Borrow UTF8 as a JSON string; escape controls in locked scratch. + /// # Errors + /// DE/EN: Ausgabe- oder vergifteter Zustand / output failure or poisoned state. + pub fn write_json_string(&mut self, value: &str) -> io::Result<()> { + self.0.get_mut().json(value.as_bytes()) + } + + /// DE: Ziel flushen; nach jedem Fehler weitere Ausgabe verweigern. + /// EN: Flush the destination; refuse further output after any failure. + /// # Errors + /// DE/EN: Flushfehler oder vergifteter Zustand / flush failure or poisoned state. + pub fn flush(&mut self) -> io::Result<()> { + let state = self.0.get_mut(); + state.ready()?; + state.poisoned = true; + state + .output + .as_deref_mut() + .ok_or_else(unavailable)? + .flush()?; + state.poisoned = false; + Ok(()) + } +} + +fn unavailable() -> io::Error { + io::Error::other("protected output unavailable") +} + +fn write_parts( + output: &mut Option<&mut W>, + poisoned: &mut bool, + bytes: &[u8], +) -> io::Result<()> { + if *poisoned { + return Err(unavailable()); + } + // DE: Auch Panic/Unwind darf keinen erneut benutzbaren Teilzustand hinterlassen. + // EN: A panic/unwind must not leave a reusable partial state either. + *poisoned = true; + output + .as_deref_mut() + .ok_or_else(unavailable)? + .write_all(bytes)?; + *poisoned = false; + Ok(()) +} + +impl State<'_, W> { + fn ready(&self) -> io::Result<()> { + if self.poisoned || self.output.is_none() { + Err(unavailable()) + } else { + Ok(()) + } + } + + fn write(&mut self, bytes: &[u8]) -> io::Result<()> { + write_parts(&mut self.output, &mut self.poisoned, bytes) + } + + fn decimal(&mut self, value: u64) -> io::Result<()> { + self.ready()?; + self.number = value; + self.cursor = self.digits.len(); + loop { + self.cursor -= 1; + self.digits[self.cursor] = + u8::try_from(self.number % 10).map_err(|_| unavailable())? + b'0'; + self.number /= 10; + if self.number == 0 { + break; + } + } + write_parts( + &mut self.output, + &mut self.poisoned, + &self.digits[self.cursor..], + )?; + self.digits.zeroize(); + self.cursor.zeroize(); + Ok(()) + } + + fn escaped(&mut self, byte: u8) -> io::Result<()> { + match byte { + b'"' => return self.write(b"\\\""), + b'\\' => return self.write(b"\\\\"), + 8 => return self.write(b"\\b"), + 9 => return self.write(b"\\t"), + 10 => return self.write(b"\\n"), + 12 => return self.write(b"\\f"), + 13 => return self.write(b"\\r"), + _ => {} + } + self.escape[..4].copy_from_slice(b"\\u00"); + self.escape[4] = HEX[usize::from(byte >> 4)]; + self.escape[5] = HEX[usize::from(byte & 15)]; + write_parts(&mut self.output, &mut self.poisoned, &self.escape)?; + self.escape.zeroize(); + Ok(()) + } + + fn json(&mut self, bytes: &[u8]) -> io::Result<()> { + self.ready()?; + self.cursor = 0; + self.start = 0; + self.write(b"\"")?; + while self.cursor < bytes.len() { + if bytes[self.cursor] < 32 || matches!(bytes[self.cursor], b'"' | b'\\') { + self.write(&bytes[self.start..self.cursor])?; + self.escaped(bytes[self.cursor])?; + self.start = self.cursor + 1; + } + self.cursor += 1; + } + self.write(&bytes[self.start..])?; + self.write(b"\"")?; + self.cursor.zeroize(); + self.start.zeroize(); + Ok(()) + } +} + +#[cfg(test)] +#[path = "output_metadata_tests.rs"] +mod tests; diff --git a/src/security/output_metadata_tests.rs b/src/security/output_metadata_tests.rs new file mode 100644 index 0000000..3bef620 --- /dev/null +++ b/src/security/output_metadata_tests.rs @@ -0,0 +1,251 @@ +//! DE: Echte gesperrte Formatierzustände, Referenzbytes, Fehler und Verweigerung. +//! EN: Actual locked formatting states, reference bytes, failures and refusal. +#![allow(clippy::unwrap_used)] +use super::*; +use crate::locked_owner_test_support::{isolated_test, locked}; +use std::fmt::Write as _; + +#[derive(Default)] +struct Sink { + bytes: Vec, + calls: usize, + fail: bool, + panic: bool, +} +impl Write for Sink { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.calls += 1; + if self.panic { + std::panic::resume_unwind(Box::new(())); + } + if self.fail { + return Err(io::ErrorKind::BrokenPipe.into()); + } + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + self.calls += 1; + Err(io::ErrorKind::PermissionDenied.into()) + } +} + +fn physical(writer: &DisclosureWriter<'_, W>) { + let state = writer.0.get(); + locked(state); + locked(&state.output); + locked(&state.number); + locked(&state.cursor); + locked(&state.start); + locked(&state.digits); + locked(&state.escape); + locked(&state.poisoned); + #[cfg(windows)] + { + let mut query = + SecretState::new(pqkeep_platform::memory_fixture::MemoryLockQuery::empty()).unwrap(); + let start = std::ptr::from_ref(state).addr(); + for offset in (0..size_of_val(state)).step_by(region::page::size()) { + assert!(query.get_mut().is_locked(start + offset).unwrap()); + } + assert!( + query + .get_mut() + .is_locked(start + size_of_val(state) - 1) + .unwrap() + ); + } +} + +#[test] +fn complete_actual_state_is_locked_movable_and_wiped_before_release() { + let mut sink = Sink::default(); + let mut writer = DisclosureWriter::new(&mut sink).unwrap(); + writer.write_u64(u64::MAX).unwrap(); + writer.write_json_string("public\0fixture").unwrap(); + physical(&writer); + let mut moved = Box::new(writer); + physical(&moved); + assert!(moved.0.get().digits.iter().all(|b| *b == 0)); + assert!(moved.0.get().escape.iter().all(|b| *b == 0)); + moved.0.get_mut().number = 7; + moved.0.get_mut().digits.fill(3); + moved.0.get_mut().escape.fill(5); + moved.0.get_mut().zeroize(); + physical(&moved); + assert_eq!(moved.0.get().number, 0); + assert!(moved.0.get().output.is_none()); + assert!(moved.0.get().digits.iter().all(|b| *b == 0)); + assert!(moved.0.get().escape.iter().all(|b| *b == 0)); + assert!(moved.write_text("public fixture").is_err()); +} + +#[test] +fn decimal_output_matches_std_across_small_values_powers_and_full_width_samples() { + let mut values: Vec = (0..=u64::from(u16::MAX)).collect(); + values.extend([u64::MAX, u64::MAX - 1, 1 << 63]); + for power in 0..=19 { + let value = 10u64.pow(power); + values.extend([value - 1, value, value.saturating_add(1)]); + } + let mut sample = 7u64; + for _ in 0..10_000 { + sample = sample + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + values.push(sample); + } + let mut out = Vec::new(); + { + let mut writer = DisclosureWriter::new(&mut out).unwrap(); + for value in &values { + writer.write_u64(*value).unwrap(); + writer.write_text("\n").unwrap(); + } + } + let mut expected = String::new(); + for value in &values { + writeln!(expected, "{value}").unwrap(); + } + assert_eq!(out, expected.as_bytes()); +} + +#[test] +fn json_escaping_matches_serde_for_every_unicode_scalar_and_ascii_control() { + let source: String = (0..=0x0010_ffff).filter_map(char::from_u32).collect(); + let mut out = Vec::new(); + { + let mut writer = DisclosureWriter::new(&mut out).unwrap(); + writer.write_json_string(&source).unwrap(); + physical(&writer); + } + assert_eq!(out, serde_json::to_vec(&source).unwrap()); + let decoded: String = serde_json::from_slice(&out).unwrap(); + assert_eq!(decoded, source); +} + +#[test] +fn write_flush_and_unwind_failures_poison_state_without_repeating_callbacks() { + for (fail, panic) in [(true, false), (false, true), (false, false)] { + let mut sink = Sink { + fail, + panic, + ..Sink::default() + }; + let mut writer = DisclosureWriter::new(&mut sink).unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if fail || panic { + writer.write_u64(u64::MAX) + } else { + writer.flush() + } + })); + assert!(matches!(result, Err(_) | Ok(Err(_)))); + assert!(writer.0.get().poisoned); + assert!(writer.write_u64(7).is_err()); + assert!(writer.write_json_string("public fixture").is_err()); + assert!(writer.write_text("public fixture").is_err()); + assert!(writer.flush().is_err()); + assert_eq!(writer.0.get().output.as_deref().unwrap().calls, 1); + physical(&writer); + } +} + +#[test] +fn actual_writer_cleanup_and_unwind_run_in_a_bounded_own_child() { + isolated_test( + "security::output::metadata::tests::cleanup_child", + "PQKEEP_DISCLOSURE_CLEANUP_CHILD", + ); +} + +#[test] +#[ignore = "DE/EN: Nur begrenztes eigenes Kind / bounded own child only"] +fn cleanup_child() { + assert_eq!( + std::env::var("PQKEEP_DISCLOSURE_CLEANUP_CHILD").unwrap(), + "1" + ); + drop(DisclosureWriter::new(&mut Sink::default()).unwrap()); + let baseline = snapshot(); + let result = std::panic::catch_unwind(|| { + let mut sink = Sink::default(); + let mut writer = DisclosureWriter::new(&mut sink).unwrap(); + writer.write_u64(u64::MAX).unwrap(); + physical(&writer); + std::panic::resume_unwind(Box::new(())); + }); + assert!(result.is_err()); + assert_eq!(snapshot(), baseline); +} + +fn snapshot() -> (usize, usize) { + let pages = crate::hardening::memlock::stats().locked_pages; + #[cfg(target_os = "linux")] + { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let bytes = status + .lines() + .find_map(|line| line.strip_prefix("VmLck:")) + .unwrap() + .split_whitespace() + .next() + .unwrap() + .parse::() + .unwrap() + * 1024; + (pages, bytes) + } + #[cfg(not(target_os = "linux"))] + { + (pages, 0) + } +} + +#[cfg(target_os = "linux")] +#[test] +fn actual_factory_denial_precedes_output_and_preserves_parent_limits() { + use rustix::process::{Resource, getrlimit}; + let before = getrlimit(Resource::Memlock); + isolated_test( + "security::output::metadata::tests::denial_child", + "PQKEEP_DISCLOSURE_DENIAL_CHILD", + ); + assert_eq!(getrlimit(Resource::Memlock), before); +} + +#[cfg(target_os = "linux")] +#[test] +#[ignore = "DE/EN: Nur begrenztes eigenes Kind / bounded own child only"] +fn denial_child() { + use rustix::process::{Resource, getrlimit, setrlimit}; + assert_eq!( + std::env::var("PQKEEP_DISCLOSURE_DENIAL_CHILD").unwrap(), + "1" + ); + let mut targets: Vec = (0..2048).map(|_| Sink::default()).collect(); + let mut retained = Vec::with_capacity(targets.len()); + let mut old = Sink::default(); + let mut existing = DisclosureWriter::new(&mut old).unwrap(); + let baseline = snapshot(); + let mut limit = getrlimit(Resource::Memlock); + limit.current = Some(0); + setrlimit(Resource::Memlock, limit).unwrap(); + let mut denied = false; + for target in &mut targets { + match DisclosureWriter::new(target) { + Ok(writer) => retained.push(writer), + Err(error) => { + assert_eq!(error, crate::Error::MemoryLock); + denied = true; + break; + } + } + } + assert!(denied); + existing.write_u64(u64::MAX).unwrap(); + physical(&existing); + drop(retained); + assert!(targets.iter().all(|target| target.calls == 0)); + assert_eq!(snapshot(), baseline); +}