commit 911559676398145166f146090d3ea61469d02e97 Author: Harald Date: Mon Sep 7 15:40:58 2026 +0200 Initial commit: Sanctum encrypted single-file container for Windows diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72342f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +*.sanctum +*.log diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..72be4cb --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1858 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", + "zeroize", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "dav-server" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88e9e4e7a3546a5b348518694e9f3ed5cf3fc8856e50141c197f54d79b5714a8" +dependencies = [ + "bytes", + "chrono", + "derive-where", + "dyn-clone", + "futures-channel", + "futures-util", + "headers", + "htmlescape", + "http", + "http-body", + "http-body-util", + "log", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "url", + "uuid", + "xml-rs", + "xmltree", +] + +[[package]] +name = "derive-where" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + +[[package]] +name = "headers" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +dependencies = [ + "base64", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "htmlescape" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "sanctum" +version = "0.1.0" +dependencies = [ + "aes-gcm", + "anyhow", + "argon2", + "bytes", + "clap", + "dav-server", + "dyn-clone", + "futures-util", + "http-body-util", + "hyper", + "hyper-util", + "rand", + "rpassword", + "rusqlite", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", + "tracing-subscriber", + "zeroize", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + +[[package]] +name = "xml-rs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3a56132a0d6ecbe77352edc10232f788fc4ceefefff4cab784a98e0e16b6b51" +dependencies = [ + "xml", +] + +[[package]] +name = "xmltree" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc04313cab124e498ab1724e739720807b6dc405b9ed0edc5860164d2e4ff70" +dependencies = [ + "xml", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4d3a9be --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "sanctum" +version = "0.1.0" +edition = "2021" +authors = ["Sanctum Engineering Team"] +description = "Verschlüsselter Ein-Datei-Container unter Windows im reinen Userland via WebDAV" + +[dependencies] +clap = { version = "4.5", features = ["derive"] } +rpassword = "7.3" +argon2 = { version = "0.5", features = ["password-hash"] } +aes-gcm = { version = "0.10", features = ["zeroize"] } +rand = "0.8" +zeroize = { version = "1.8", features = ["derive", "zeroize_derive"] } +rusqlite = { version = "0.32", features = ["bundled"] } +tokio = { version = "1.40", features = ["full"] } +dav-server = { version = "0.11", default-features = false } +hyper = { version = "1.4", features = ["server", "http1"] } +hyper-util = { version = "0.1", features = ["tokio", "server-auto"] } +http-body-util = "0.1" +bytes = "1.7" +futures-util = "0.3" +thiserror = "2.0" +anyhow = "1.0" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +dyn-clone = "1.0" + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +panic = "abort" +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..0c2face --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# Sanctum 🛡️ + +Sanctum ist eine eigenständige, speichersichere und hochperformante CLI-Anwendung in Rust, die einen verschlüsselten Ein-Datei-Container (`.sanctum`) unter Windows (10/11) im reinen Userland verwaltet. + +- **Keine Administratorrechte erforderlich** +- **Keine Kernel-Treiber** (weder WinFsp noch Dokan) +- **Transparenter Windows Explorer-Zugriff** über einen integrierten lokalen WebDAV-Server (`127.0.0.1`) via Windows-Bordmittel (`net use`) +- **Statisches Single-Binary** (`sanctum.exe`, ~4.6 MB) ohne externe DLL-Abhängigkeiten + +--- + +## 🔐 Kryptografie & Sicherheitsarchitektur + +- **Key Derivation (Argon2id)**: + Aus dem Master-Passwort wird mittels `Argon2id` ($M=64\,\text{MB}, T=3, P=4$) ein 256-Bit Key Encryption Key (KEK) abgeleitet. +- **Data Encryption Key (DEK)**: + Ein zufälliger 256-Bit Schlüssel via CSPRNG (`OsRng`). Der DEK wird mit dem KEK via AES-256-GCM verschlüsselt und im Header abgelegt. +- **RAM-Schutz**: + Alle Schlüsselstrukturen implementieren das `Zeroize`-Trait (`Zeroizing<[u8; 32]>`), um sensible Schlüsseldaten beim Verlassen des Gültigkeitsbereichs im Arbeitsspeicher sicher zu nullen. +- **Chunk-Verschlüsselung (AES-256-GCM)**: + Dateien werden in Blöcken von 1 MB verschlüsselt. +- **Schutz vor Swap-Angriffen**: + Als Associated Data (AAD) werden `node_id` (8 Bytes LE) und `chunk_index` (8 Bytes LE) fest eingebunden. Dadurch wird verhindert, dass Chunks zwischen Dateien oder innerhalb einer Datei vertauscht werden können. + +--- + +## 📦 Storage Engine (SQLite3 im VFS-Container) + +Der gesamte Container besteht aus exakt **einer** Datei auf der Host-Festplatte (`.sanctum`), die dynamisch bis über 100 GB wachsen kann. + +- **Pragmas**: + - `PRAGMA journal_mode = WAL;` + - `PRAGMA synchronous = NORMAL;` + - `PRAGMA page_size = 8192;` + - `PRAGMA foreign_keys = ON;` +- **Tabellen**: + - `meta`: Container-Header mit Magic Bytes (`SANCTUM\0`), Version 1, Salt, KDF-Parametern und Wrapped DEK. + - `nodes`: Verzeichnis- und Dateiknoten mit Hierarchiebaum und Zeitstempeln. + - `chunks`: Verschlüsselte Nutzdatenblöcke mit Nonce und Authentifizierungstag. + +--- + +## 🚀 Kompilieren + +Voraussetzungen: Rust (>= 1.85) mit GCC/MinGW-Toolchain für SQLite: + +```powershell +cargo build --release +``` + +Das fertige Binary befindet sich unter `target/release/sanctum.exe`. + +--- + +## 🛠️ Verwendung + +### 1. Neuen Container anlegen +```powershell +sanctum.exe init --path "C:\Users\username\Documents\safe.sanctum" +``` + +### 2. Container als Windows-Laufwerk einbinden +```powershell +sanctum.exe mount --path "C:\Users\username\Documents\safe.sanctum" --drive S +``` +Das Netzlaufwerk `S:` steht sofort im Windows Explorer zur Verfügung. +Zum Beenden und sicheren Trennen einfach `Ctrl+C` im Terminal drücken. + +### 3. Laufwerk manuell trennen +```powershell +sanctum.exe unmount --drive S +``` diff --git a/src/crypto.rs b/src/crypto.rs new file mode 100644 index 0000000..0963175 --- /dev/null +++ b/src/crypto.rs @@ -0,0 +1,248 @@ +use aes_gcm::{ + aead::{AeadInPlace, KeyInit}, + Aes256Gcm, Nonce, Tag, +}; +use anyhow::{bail, Result}; +use argon2::{Algorithm, Argon2, Params, Version}; +use rand::rngs::OsRng; +use rand::RngCore; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +pub const MAGIC_BYTES: &[u8; 8] = b"SANCTUM\0"; +pub const FORMAT_VERSION: u32 = 1; +pub const CHUNK_SIZE: usize = 1024 * 1024; // 1 MB + +pub const DEFAULT_MEMORY_COST_KIB: u32 = 64 * 1024; // 64 MB +pub const DEFAULT_TIME_COST: u32 = 3; +pub const DEFAULT_PARALLELISM: u32 = 4; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct KdfParams { + pub memory_cost: u32, + pub time_cost: u32, + pub parallelism: u32, +} + +impl Default for KdfParams { + fn default() -> Self { + Self { + memory_cost: DEFAULT_MEMORY_COST_KIB, + time_cost: DEFAULT_TIME_COST, + parallelism: DEFAULT_PARALLELISM, + } + } +} + +/// Leitet aus dem Master-Passwort und dem Salt einen 256-Bit Key Encryption Key (KEK) via Argon2id ab. +pub fn derive_kek( + password: &str, + salt: &[u8], + params: &KdfParams, +) -> Result> { + let argon2_params = Params::new( + params.memory_cost, + params.time_cost, + params.parallelism, + Some(32), + ) + .map_err(|e| anyhow::anyhow!("Ungültige Argon2-Parameter: {e}"))?; + + let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params); + let mut kek = Zeroizing::new([0u8; 32]); + + argon2 + .hash_password_into(password.as_bytes(), salt, &mut *kek) + .map_err(|e| anyhow::anyhow!("Argon2id KDF-Berechnung fehlgeschlagen: {e}"))?; + + Ok(kek) +} + +/// Generiert einen kryptografisch sicheren 256-Bit Data Encryption Key (DEK). +pub fn generate_dek() -> Zeroizing<[u8; 32]> { + let mut dek = Zeroizing::new([0u8; 32]); + OsRng.fill_bytes(&mut *dek); + dek +} + +/// Generiert ein kryptografisch sicheres 16-Byte KDF-Salt. +pub fn generate_salt() -> [u8; 16] { + let mut salt = [0u8; 16]; + OsRng.fill_bytes(&mut salt); + salt +} + +/// Verschlüsselt den DEK mit dem KEK via AES-256-GCM. +/// Gibt (wrapped_dek_32_bytes, nonce_12_bytes, tag_16_bytes) zurück. +pub fn wrap_dek( + kek: &[u8; 32], + dek: &[u8; 32], +) -> Result<(Vec, [u8; 12], [u8; 16])> { + let cipher = Aes256Gcm::new_from_slice(kek) + .map_err(|e| anyhow::anyhow!("AES-GCM Initialisierungsfehler: {e}"))?; + + let mut nonce_bytes = [0u8; 12]; + OsRng.fill_bytes(&mut nonce_bytes); + let nonce = Nonce::from_slice(&nonce_bytes); + + let mut buffer = dek.to_vec(); + let tag = cipher + .encrypt_in_place_detached(nonce, b"SANCTUM_HEADER_DEK", &mut buffer) + .map_err(|e| anyhow::anyhow!("DEK-Wrapping fehlgeschlagen: {e}"))?; + + let mut tag_bytes = [0u8; 16]; + tag_bytes.copy_from_slice(tag.as_slice()); + + Ok((buffer, nonce_bytes, tag_bytes)) +} + +/// Entschlüsselt den DEK mit dem KEK via AES-256-GCM und validiert die Authentizität. +pub fn unwrap_dek( + kek: &[u8; 32], + wrapped_dek: &[u8], + nonce_bytes: &[u8; 12], + tag_bytes: &[u8; 16], +) -> Result> { + if wrapped_dek.len() != 32 { + bail!("Ungültige wrapped_dek Länge: erwartet 32 Bytes, erhalten {}", wrapped_dek.len()); + } + + let cipher = Aes256Gcm::new_from_slice(kek) + .map_err(|e| anyhow::anyhow!("AES-GCM Initialisierungsfehler: {e}"))?; + + let nonce = Nonce::from_slice(nonce_bytes); + let tag = Tag::from_slice(tag_bytes); + + let mut buffer = wrapped_dek.to_vec(); + cipher + .decrypt_in_place_detached(nonce, b"SANCTUM_HEADER_DEK", &mut buffer, tag) + .map_err(|_| anyhow::anyhow!("Passwort falsch oder Header beschädigt (AEAD Authentifizierungsfehler)"))?; + + let mut dek = Zeroizing::new([0u8; 32]); + dek.copy_from_slice(&buffer); + Ok(dek) +} + +/// Erzeugt die 16-Byte Associated Data (AAD) für einen Chunk, um Swap-Angriffe zu verhindern: +/// node_id (8 Bytes Little-Endian) || chunk_index (8 Bytes Little-Endian). +#[inline] +pub fn build_chunk_aad(node_id: i64, chunk_index: u32) -> [u8; 16] { + let mut aad = [0u8; 16]; + aad[..8].copy_from_slice(&node_id.to_le_bytes()); + aad[8..].copy_from_slice(&(chunk_index as u64).to_le_bytes()); + aad +} + +/// Verschlüsselt einen Payload-Chunk mit dem DEK via AES-256-GCM unter Einbindung von AAD. +/// Gibt (ciphertext, nonce_12_bytes, tag_16_bytes) zurück. +pub fn encrypt_chunk( + dek: &[u8; 32], + node_id: i64, + chunk_index: u32, + plaintext: &[u8], +) -> Result<(Vec, [u8; 12], [u8; 16])> { + let cipher = Aes256Gcm::new_from_slice(dek) + .map_err(|e| anyhow::anyhow!("AES-GCM Initialisierungsfehler: {e}"))?; + + let mut nonce_bytes = [0u8; 12]; + OsRng.fill_bytes(&mut nonce_bytes); + let nonce = Nonce::from_slice(&nonce_bytes); + + let aad = build_chunk_aad(node_id, chunk_index); + + let mut buffer = plaintext.to_vec(); + let tag = cipher + .encrypt_in_place_detached(nonce, &aad, &mut buffer) + .map_err(|e| anyhow::anyhow!("Chunk-Verschlüsselung fehlgeschlagen: {e}"))?; + + let mut tag_bytes = [0u8; 16]; + tag_bytes.copy_from_slice(tag.as_slice()); + + Ok((buffer, nonce_bytes, tag_bytes)) +} + +/// Entschlüsselt und authentifiziert einen Payload-Chunk mit dem DEK via AES-256-GCM. +pub fn decrypt_chunk( + dek: &[u8; 32], + node_id: i64, + chunk_index: u32, + ciphertext: &[u8], + nonce_bytes: &[u8; 12], + tag_bytes: &[u8; 16], +) -> Result> { + let cipher = Aes256Gcm::new_from_slice(dek) + .map_err(|e| anyhow::anyhow!("AES-GCM Initialisierungsfehler: {e}"))?; + + let nonce = Nonce::from_slice(nonce_bytes); + let tag = Tag::from_slice(tag_bytes); + let aad = build_chunk_aad(node_id, chunk_index); + + let mut buffer = ciphertext.to_vec(); + cipher + .decrypt_in_place_detached(nonce, &aad, &mut buffer, tag) + .map_err(|_| anyhow::anyhow!("Chunk-Integritätsprüfung fehlgeschlagen (AEAD Auth-Fehler oder Swap-Angriff)"))?; + + Ok(buffer) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_kdf_and_dek_wrapping() { + let password = "SuperSecretMasterPassword123!"; + let salt = generate_salt(); + let params = KdfParams { + memory_cost: 1024, // Schneller für Unit-Test + time_cost: 1, + parallelism: 1, + }; + + let kek = derive_kek(password, &salt, ¶ms).unwrap(); + let dek = generate_dek(); + + let (wrapped, nonce, tag) = wrap_dek(&kek, &dek).unwrap(); + assert_eq!(wrapped.len(), 32); + + // Erfolgreiche Entschlüsselung + let unwrapped = unwrap_dek(&kek, &wrapped, &nonce, &tag).unwrap(); + assert_eq!(*dek, *unwrapped); + + // Falscher KEK schlägt fehl + let wrong_kek = derive_kek("WrongPassword!", &salt, ¶ms).unwrap(); + assert!(unwrap_dek(&wrong_kek, &wrapped, &nonce, &tag).is_err()); + + // Manipulierter Tag schlägt fehl + let mut tampered_tag = tag; + tampered_tag[0] ^= 0xFF; + assert!(unwrap_dek(&kek, &wrapped, &nonce, &tampered_tag).is_err()); + } + + #[test] + fn test_chunk_encryption_and_swap_protection() { + let dek = generate_dek(); + let plaintext = b"Hello, Sanctum Encrypted Storage World!"; + let node_id = 42i64; + let chunk_index = 0u32; + + let (ciphertext, nonce, tag) = encrypt_chunk(&dek, node_id, chunk_index, plaintext).unwrap(); + + // Reguläre Entschlüsselung + let decrypted = decrypt_chunk(&dek, node_id, chunk_index, &ciphertext, &nonce, &tag).unwrap(); + assert_eq!(decrypted, plaintext); + + // Swap Attack 1: Falsche node_id (Chunk in andere Datei verschoben) + let swap_node_err = decrypt_chunk(&dek, 99i64, chunk_index, &ciphertext, &nonce, &tag); + assert!(swap_node_err.is_err()); + + // Swap Attack 2: Falscher chunk_index (Chunk innerhalb derselben Datei verschoben) + let swap_idx_err = decrypt_chunk(&dek, node_id, 1u32, &ciphertext, &nonce, &tag); + assert!(swap_idx_err.is_err()); + + // Manipulation des Ciphertexts + let mut tampered_ct = ciphertext.clone(); + tampered_ct[0] ^= 0x01; + assert!(decrypt_chunk(&dek, node_id, chunk_index, &tampered_ct, &nonce, &tag).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..397b117 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,4 @@ +pub mod crypto; +pub mod mount; +pub mod storage; +pub mod vfs; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..a9a3198 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,168 @@ +use std::path::{Path, PathBuf}; + +use anyhow::{bail, Context, Result}; +use clap::{Parser, Subcommand}; +use tracing::info; +use tracing_subscriber::EnvFilter; + +use sanctum::crypto::{derive_kek, generate_dek, generate_salt, wrap_dek, KdfParams}; +use sanctum::mount::{format_drive, mount_container, unmount_drive}; +use sanctum::storage::Database; + +#[derive(Parser)] +#[command(name = "sanctum")] +#[command(author = "Sanctum Systems & Security Engineering")] +#[command(about = "Sanctum: Verschlüsselter Ein-Datei-Container unter Windows im reinen Userland", long_about = None)] +#[command(version)] +struct Cli { + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + /// Initialisiert einen neuen verschlüsselten Sanctum-Container (.sanctum) + Init { + /// Pfad zur zu erstellenden .sanctum Containerdatei + #[arg(short, long)] + path: PathBuf, + }, + + /// Bindet einen Sanctum-Container als Windows-Netzlaufwerk via WebDAV ein + Mount { + /// Pfad zur .sanctum Containerdatei + #[arg(short, long)] + path: PathBuf, + + /// Laufwerksbuchstabe (z. B. 'S' oder 'S:') + #[arg(short, long)] + drive: String, + + /// Optionaler TCP-Port für den lokalen WebDAV-Server (Standard: 8443) + #[arg(long)] + port: Option, + }, + + /// Trennt ein eingebundenes Netzlaufwerk manuell + Unmount { + /// Laufwerksbuchstabe (z. B. 'S' oder 'S:') + #[arg(short, long)] + drive: String, + }, +} + +fn parse_drive_letter(s: &str) -> Result { + let trimmed = s.trim(); + let ch = trimmed + .chars() + .next() + .context("Laufwerksangabe darf nicht leer sein")?; + + if !ch.is_ascii_alphabetic() { + bail!("Ungültiger Laufwerksbuchstabe: '{}'", trimmed); + } + + Ok(ch.to_ascii_uppercase()) +} + +fn handle_init(container_path: &Path) -> Result<()> { + if container_path.exists() { + bail!( + "Zieldatei '{}' existiert bereits. Initialisierung abgebrochen, um Überschreiben zu verhindern.", + container_path.display() + ); + } + + println!("============================================================"); + println!(" Sanctum Container Initialisierung"); + println!(" Zieldatei: {}", container_path.display()); + println!("============================================================"); + + let password = rpassword::prompt_password("Master-Passwort eingeben: ") + .context("Fehler beim Einlesen des Passworts")?; + + if password.trim().is_empty() { + bail!("Das Master-Passwort darf nicht leer sein."); + } + + let confirm_password = rpassword::prompt_password("Master-Passwort bestätigen: ") + .context("Fehler beim Einlesen der Passwort-Bestätigung")?; + + if password != confirm_password { + bail!("Die eingegebenen Passwörter stimmen nicht überein!"); + } + + info!("Generiere KDF-Salt und leite KEK via Argon2id ab ..."); + let salt = generate_salt(); + let kdf_params = KdfParams::default(); + let kek = derive_kek(&password, &salt, &kdf_params) + .context("KDF-Schlüsselableitung fehlgeschlagen")?; + + info!("Erzeuge kryptografisch sicheren DEK via CSPRNG (OsRng) ..."); + let dek = generate_dek(); + + info!("Verschlüssele DEK mit KEK via AES-256-GCM ..."); + let (wrapped_dek, header_nonce, header_tag) = + wrap_dek(&kek, &dek).context("DEK-Wrapping fehlgeschlagen")?; + + info!("Initialisiere SQLite-Containerstruktur mit WAL-Modus ..."); + let db = Database::open(container_path) + .context("Konnte SQLite-Containerdatei nicht anlegen")?; + + db.init_schema(&salt, &kdf_params, &wrapped_dek, &header_nonce, &header_tag) + .context("Fehler bei der Schema-Initialisierung")?; + + db.checkpoint() + .context("Fehler beim finalen WAL-Checkpoint")?; + + println!(); + println!("✔ Sanctum-Container erfolgreich initialisiert!"); + println!(" Container: {}", container_path.display()); + println!(" Format: Version 1 (Magic: SANCTUM\\0)"); + println!(" KDF: Argon2id (M=64MB, T=3, P=4)"); + println!(" Cipher: AES-256-GCM mit AEAD-Swap-Protection (1-MB Chunks)"); + println!(); + println!("Zum Einbinden ausführen:"); + println!( + " sanctum mount --path \"{}\" --drive S", + container_path.display() + ); + + Ok(()) +} + +#[tokio::main] +async fn main() -> Result<()> { + // Tracing / Logging initialisieren (Standard-Filter: info) + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::try_from_default_env() + .unwrap_or_else(|_| EnvFilter::new("sanctum=info,dav_server=warn,hyper=warn")), + ) + .init(); + + let cli = Cli::parse(); + + match cli.command { + Commands::Init { path } => { + handle_init(&path)?; + } + Commands::Mount { path, drive, port } => { + let drive_char = parse_drive_letter(&drive)?; + let password = rpassword::prompt_password(format!( + "Master-Passwort für Container '{}' eingeben: ", + path.display() + )) + .context("Fehler beim Einlesen des Passworts")?; + + mount_container(&path, drive_char, port, &password).await?; + } + Commands::Unmount { drive } => { + let drive_char = parse_drive_letter(&drive)?; + unmount_drive(drive_char)?; + println!("✔ Laufwerk {} erfolgreich getrennt.", format_drive(drive_char)); + } + } + + Ok(()) +} diff --git a/src/mount.rs b/src/mount.rs new file mode 100644 index 0000000..773dc98 --- /dev/null +++ b/src/mount.rs @@ -0,0 +1,228 @@ +use std::convert::Infallible; +use std::net::SocketAddr; +use std::path::Path; +use std::process::Command; + +use anyhow::{bail, Context, Result}; +use dav_server::{fakels::FakeLs, DavHandler}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper_util::rt::TokioIo; +use tokio::net::TcpListener; +use tokio::sync::watch; +use tracing::{debug, error, info, warn}; + +use crate::crypto::{derive_kek, unwrap_dek}; +use crate::storage::Database; +use crate::vfs::SanctumFs; + +/// Hilfsfunktion zur Formatierung des Laufwerksbuchstabens (z. B. 'S' -> "S:") +pub fn format_drive(drive_letter: char) -> String { + format!("{}:", drive_letter.to_ascii_uppercase()) +} + +/// Trennt ein Windows-Netzlaufwerk via `net use : /delete /y`. +pub fn unmount_drive(drive_letter: char) -> Result<()> { + let drive_str = format_drive(drive_letter); + info!("Trennen des Netzlaufwerks {} ...", drive_str); + + let output = Command::new("net") + .args(["use", &drive_str, "/delete", "/y"]) + .output() + .context("Fehler beim Ausführen des Befehls 'net use'")?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + bail!( + "Netzlaufwerk {} konnte nicht getrennt werden:\n{}{}", + drive_str, + stdout, + stderr + ); + } + + info!("Laufwerk {} erfolgreich getrennt.", drive_str); + Ok(()) +} + +/// Bindet ein Windows-Netzlaufwerk via `net use : http://127.0.0.1:/ /persistent:no` ein. +fn run_net_use_mount(drive_str: &str, port: u16) -> Result<()> { + let url = format!("http://127.0.0.1:{}/", port); + info!("Verbinde Netzlaufwerk {} mit {} ...", drive_str, url); + + let output = Command::new("net") + .args(["use", drive_str, &url, "/persistent:no"]) + .output() + .context("Fehler beim Ausführen des Befehls 'net use'")?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + bail!( + "Laufwerk {} konnte nicht eingebunden werden:\n{}{}", + drive_str, + stdout, + stderr + ); + } + + info!("Laufwerk {} erfolgreich eingebunden!", drive_str); + Ok(()) +} + +/// Startet den WebDAV-Server für den Sanctum-Container und bindet ihn als Netzlaufwerk ein. +pub async fn mount_container( + container_path: &Path, + drive_letter: char, + requested_port: Option, + password: &str, +) -> Result<()> { + let drive_str = format_drive(drive_letter); + + if !container_path.exists() { + bail!( + "Containerdatei '{}' existiert nicht.", + container_path.display() + ); + } + + info!( + "Öffne Container '{}' ...", + container_path.display() + ); + let db = Database::open(container_path) + .context("Konnte Container-Datenbank nicht öffnen")?; + + info!("Lese Header und verifiziere Magic Bytes ..."); + let meta = db + .read_meta() + .context("Konnte Container-Header nicht lesen")?; + + info!("Leite KEK via Argon2id ab ..."); + let kek = derive_kek(password, &meta.kdf_salt, &meta.kdf_params) + .context("Schlüsselableitung fehlgeschlagen")?; + + info!("Entschlüssele DEK via AES-256-GCM ..."); + let dek = unwrap_dek( + &kek, + &meta.wrapped_dek, + &meta.header_nonce, + &meta.header_tag, + ) + .context("Ungültiges Master-Passwort oder Container beschädigt")?; + + // WebDAV Filesystem und Handler konfigurieren + let fs = SanctumFs::new(db.clone(), dek); + let dav_server = DavHandler::builder() + .filesystem(Box::new(fs)) + .locksystem(FakeLs::new()) + .build_handler(); + + // TCP-Port ermitteln und binden + let port_to_try = requested_port.unwrap_or(8443); + let listener = match TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port_to_try))).await { + Ok(l) => l, + Err(_) if requested_port.is_none() => { + info!( + "Standard-Port {} belegt, wähle dynamischen freien Port ...", + port_to_try + ); + TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))) + .await + .context("Konnte keinen lokalen TCP-Port binden")? + } + Err(e) => { + bail!("Konnte Port 127.0.0.1:{} nicht binden: {}", port_to_try, e); + } + }; + + let bound_addr = listener.local_addr()?; + let bound_port = bound_addr.port(); + info!("WebDAV-Server lauscht auf http://{}", bound_addr); + + let (shutdown_tx, mut shutdown_rx) = watch::channel(false); + + // Hyper HTTP Server Loop im Hintergrund starten + let server_dav = dav_server.clone(); + let server_handle = tokio::spawn(async move { + loop { + tokio::select! { + res = listener.accept() => { + let (stream, _) = match res { + Ok(val) => val, + Err(e) => { + warn!("Verbindungsfehler im TCP-Listener: {e}"); + continue; + } + }; + + let io = TokioIo::new(stream); + let handler = server_dav.clone(); + + tokio::spawn(async move { + let service = service_fn(move |req| { + let h = handler.clone(); + async move { + Ok::<_, Infallible>(h.handle(req).await) + } + }); + + if let Err(err) = http1::Builder::new().serve_connection(io, service).await { + // Client-Disconnects im Explorer sind normal + debug!("HTTP-Verbindungsende: {:?}", err); + } + }); + } + _ = shutdown_rx.changed() => { + info!("WebDAV-Server-Task empfängt Shutdown-Signal."); + break; + } + } + } + }); + + // Netzlaufwerk einbinden + if let Err(e) = run_net_use_mount(&drive_str, bound_port) { + let _ = shutdown_tx.send(true); + let _ = server_handle.await; + return Err(e); + } + + println!(); + println!("============================================================"); + println!(" Sanctum Container erfolgreich gemountet!"); + println!(" Pfad: {}", container_path.display()); + println!(" Laufwerk: {}", drive_str); + println!(" WebDAV URL: http://127.0.0.1:{}/", bound_port); + println!(" Drücke [Ctrl+C] zum sauberen Trennen und Schließen."); + println!("============================================================"); + println!(); + + // Warten auf Strg+C + tokio::signal::ctrl_c() + .await + .context("Fehler beim Registrieren des Ctrl+C Signalhandlers")?; + + println!(); + info!("Beendigungssignal (Ctrl+C) erhalten."); + info!("Trennen des Windows-Netzlaufwerks {} ...", drive_str); + + // Automatisches Unmount + if let Err(e) = unmount_drive(drive_letter) { + warn!("Warnung beim automatischen Unmount: {e}"); + } + + // HTTP Server beenden + let _ = shutdown_tx.send(true); + let _ = server_handle.await; + + // SQLite WAL Checkpoint erzwingen + info!("Führe SQLite WAL-Checkpoint aus (PRAGMA wal_checkpoint(TRUNCATE)) ..."); + if let Err(e) = db.checkpoint() { + error!("Fehler beim WAL-Checkpoint: {e}"); + } + + info!("Sanctum Container wurde sicher und vollständig geschlossen."); + Ok(()) +} diff --git a/src/storage.rs b/src/storage.rs new file mode 100644 index 0000000..7c084f8 --- /dev/null +++ b/src/storage.rs @@ -0,0 +1,534 @@ +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{bail, Context, Result}; +use rusqlite::{params, Connection, OptionalExtension}; + +use crate::crypto::{KdfParams, FORMAT_VERSION, MAGIC_BYTES}; + +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub struct NodeRecord { + pub id: i64, + pub parent_id: Option, + pub name: String, + pub is_dir: bool, + pub size: u64, + pub created_at: u64, + pub modified_at: u64, +} + +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub struct ChunkRecord { + pub node_id: i64, + pub chunk_index: u32, + pub nonce: [u8; 12], + pub tag: [u8; 16], + pub ciphertext: Vec, +} + +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub struct ContainerMeta { + pub version: u32, + pub kdf_salt: [u8; 16], + pub kdf_params: KdfParams, + pub wrapped_dek: Vec, + pub header_nonce: [u8; 12], + pub header_tag: [u8; 16], +} + +#[derive(Clone)] +pub struct Database { + conn: Arc>, +} + +fn current_timestamp() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +impl Database { + /// Öffnet oder erstellt die Container-Datenbank und initialisiert die Pragmas. + pub fn open>(path: P) -> Result { + let conn = Connection::open(path)?; + let db = Self { + conn: Arc::new(Mutex::new(conn)), + }; + db.init_pragmas()?; + Ok(db) + } + + /// Öffnet eine In-Memory-Datenbank (vorwiegend für Tests). + #[cfg(test)] + pub fn open_in_memory() -> Result { + let conn = Connection::open_in_memory()?; + let db = Self { + conn: Arc::new(Mutex::new(conn)), + }; + db.init_pragmas()?; + Ok(db) + } + + /// Setzt die vorgeschriebenen SQLite3-Pragmas: WAL, NORMAL synchronous, 8192 Page-Size. + pub fn init_pragmas(&self) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute_batch( + "PRAGMA page_size = 8192; + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA foreign_keys = ON; + PRAGMA busy_timeout = 5000;", + )?; + Ok(()) + } + + /// Initialisiert das Datenbankschema für einen neuen Container. + pub fn init_schema( + &self, + salt: &[u8; 16], + kdf_params: &KdfParams, + wrapped_dek: &[u8], + header_nonce: &[u8; 12], + header_tag: &[u8; 16], + ) -> Result<()> { + let conn = self.conn.lock().unwrap(); + + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS meta ( + magic BLOB NOT NULL, + version INTEGER NOT NULL, + kdf_salt BLOB NOT NULL, + kdf_params TEXT NOT NULL, + wrapped_dek BLOB NOT NULL, + header_nonce BLOB NOT NULL, + header_tag BLOB NOT NULL + ); + + CREATE TABLE IF NOT EXISTS nodes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + parent_id INTEGER, + name TEXT NOT NULL, + is_dir INTEGER NOT NULL, + size INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + modified_at INTEGER NOT NULL, + FOREIGN KEY(parent_id) REFERENCES nodes(id) ON DELETE CASCADE + ); + CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_parent_name ON nodes(COALESCE(parent_id, 0), name); + + CREATE TABLE IF NOT EXISTS chunks ( + node_id INTEGER NOT NULL, + chunk_index INTEGER NOT NULL, + nonce BLOB NOT NULL, + tag BLOB NOT NULL, + ciphertext BLOB NOT NULL, + PRIMARY KEY (node_id, chunk_index), + FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE + );", + )?; + + // Metadaten einfügen + let params_json = serde_json::to_string(kdf_params)?; + conn.execute( + "INSERT INTO meta (magic, version, kdf_salt, kdf_params, wrapped_dek, header_nonce, header_tag) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + MAGIC_BYTES.as_slice(), + FORMAT_VERSION, + salt.as_slice(), + params_json, + wrapped_dek, + header_nonce.as_slice(), + header_tag.as_slice(), + ], + )?; + + // Root-Verzeichnis '/' mit id = 1 anlegen + let now = current_timestamp(); + conn.execute( + "INSERT OR IGNORE INTO nodes (id, parent_id, name, is_dir, size, created_at, modified_at) + VALUES (1, NULL, '', 1, 0, ?1, ?2)", + params![now, now], + )?; + + Ok(()) + } + + /// Liest die Metadaten des Containers aus der `meta`-Tabelle aus und verifiziert die Magic Bytes. + pub fn read_meta(&self) -> Result { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT magic, version, kdf_salt, kdf_params, wrapped_dek, header_nonce, header_tag FROM meta LIMIT 1" + )?; + + let meta = stmt.query_row([], |row| { + let magic: Vec = row.get(0)?; + let version: u32 = row.get(1)?; + let kdf_salt: Vec = row.get(2)?; + let kdf_params_str: String = row.get(3)?; + let wrapped_dek: Vec = row.get(4)?; + let header_nonce: Vec = row.get(5)?; + let header_tag: Vec = row.get(6)?; + + Ok(( + magic, + version, + kdf_salt, + kdf_params_str, + wrapped_dek, + header_nonce, + header_tag, + )) + })?; + + if meta.0.as_slice() != MAGIC_BYTES.as_slice() { + bail!("Ungültige Sanctum-Containerdatei: Magic Bytes stimmen nicht überein"); + } + + if meta.1 != FORMAT_VERSION { + bail!("Nicht unterstützte Sanctum-Formatversion: {}", meta.1); + } + + if meta.2.len() != 16 { + bail!("Ungültige Salt-Länge im Header"); + } + let mut salt = [0u8; 16]; + salt.copy_from_slice(&meta.2); + + let kdf_params: KdfParams = serde_json::from_str(&meta.3) + .context("KDF-Parameter im Header konnten nicht deserialisiert werden")?; + + if meta.5.len() != 12 { + bail!("Ungültige Header-Nonce-Länge"); + } + let mut header_nonce = [0u8; 12]; + header_nonce.copy_from_slice(&meta.5); + + if meta.6.len() != 16 { + bail!("Ungültige Header-Tag-Länge"); + } + let mut header_tag = [0u8; 16]; + header_tag.copy_from_slice(&meta.6); + + Ok(ContainerMeta { + version: meta.1, + kdf_salt: salt, + kdf_params, + wrapped_dek: meta.4, + header_nonce, + header_tag, + }) + } + + /// Löst einen hierarchischen Pfad (z. B. "/ordner/datei.txt") in den entsprechenden NodeRecord auf. + pub fn resolve_path(&self, raw_path: &str) -> Result> { + let normalized = raw_path.trim_matches('/'); + if normalized.is_empty() { + return self.get_node_by_id(1); + } + + let segments: Vec<&str> = normalized.split('/').filter(|s| !s.is_empty()).collect(); + let conn = self.conn.lock().unwrap(); + + let mut current_id = 1i64; + let mut last_record = None; + + for (idx, segment) in segments.iter().enumerate() { + let mut stmt = conn.prepare( + "SELECT id, parent_id, name, is_dir, size, created_at, modified_at + FROM nodes + WHERE parent_id = ?1 AND name = ?2", + )?; + + let record: Option = stmt + .query_row(params![current_id, segment], |row| { + Ok(NodeRecord { + id: row.get(0)?, + parent_id: row.get(1)?, + name: row.get(2)?, + is_dir: row.get::<_, i32>(3)? != 0, + size: row.get::<_, i64>(4)? as u64, + created_at: row.get::<_, i64>(5)? as u64, + modified_at: row.get::<_, i64>(6)? as u64, + }) + }) + .optional()?; + + match record { + Some(rec) => { + if idx + 1 < segments.len() && !rec.is_dir { + // Zwischenelement ist kein Verzeichnis + return Ok(None); + } + current_id = rec.id; + last_record = Some(rec); + } + None => return Ok(None), + } + } + + Ok(last_record) + } + + pub fn get_node_by_id(&self, id: i64) -> Result> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, parent_id, name, is_dir, size, created_at, modified_at + FROM nodes WHERE id = ?1", + )?; + + let record = stmt + .query_row(params![id], |row| { + Ok(NodeRecord { + id: row.get(0)?, + parent_id: row.get(1)?, + name: row.get(2)?, + is_dir: row.get::<_, i32>(3)? != 0, + size: row.get::<_, i64>(4)? as u64, + created_at: row.get::<_, i64>(5)? as u64, + modified_at: row.get::<_, i64>(6)? as u64, + }) + }) + .optional()?; + + Ok(record) + } + + /// Listet alle direkten Kinder eines Verzeichnisknotens auf. + pub fn list_children(&self, parent_id: i64) -> Result> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, parent_id, name, is_dir, size, created_at, modified_at + FROM nodes + WHERE parent_id = ?1 + ORDER BY is_dir DESC, name ASC", + )?; + + let rows = stmt.query_map(params![parent_id], |row| { + Ok(NodeRecord { + id: row.get(0)?, + parent_id: row.get(1)?, + name: row.get(2)?, + is_dir: row.get::<_, i32>(3)? != 0, + size: row.get::<_, i64>(4)? as u64, + created_at: row.get::<_, i64>(5)? as u64, + modified_at: row.get::<_, i64>(6)? as u64, + }) + })?; + + let mut entries = Vec::new(); + for r in rows { + entries.push(r?); + } + Ok(entries) + } + + /// Erstellt einen neuen Datei- oder Ordnerknoten. + pub fn create_node(&self, parent_id: i64, name: &str, is_dir: bool) -> Result { + let now = current_timestamp(); + let conn = self.conn.lock().unwrap(); + + conn.execute( + "INSERT INTO nodes (parent_id, name, is_dir, size, created_at, modified_at) + VALUES (?1, ?2, ?3, 0, ?4, ?5)", + params![parent_id, name, if is_dir { 1 } else { 0 }, now, now], + )?; + + let new_id = conn.last_insert_rowid(); + + // Aktualisiere das Änderungsdatum des Elternordners + let _ = conn.execute( + "UPDATE nodes SET modified_at = ?1 WHERE id = ?2", + params![now, parent_id], + ); + + Ok(NodeRecord { + id: new_id, + parent_id: Some(parent_id), + name: name.to_string(), + is_dir, + size: 0, + created_at: now, + modified_at: now, + }) + } + + /// Aktualisiert Dateigröße und Modifikationszeitstempel eines Knotens. + pub fn update_node_size_and_time(&self, id: i64, size: u64, modified_at: u64) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute( + "UPDATE nodes SET size = ?1, modified_at = ?2 WHERE id = ?3", + params![size as i64, modified_at as i64, id], + )?; + Ok(()) + } + + /// Löscht einen Knoten und alle assoziierten Chunks atomar. + pub fn delete_node(&self, id: i64) -> Result<()> { + let conn = self.conn.lock().unwrap(); + // Foreign Key Cascade löscht Chunks und Unterordner, wir stellen es explizit sicher: + conn.execute("DELETE FROM chunks WHERE node_id = ?1", params![id])?; + conn.execute("DELETE FROM nodes WHERE id = ?1", params![id])?; + Ok(()) + } + + /// Benennt einen Knoten um und/oder verschiebt ihn in ein anderes Verzeichnis. + pub fn rename_node(&self, id: i64, new_parent_id: i64, new_name: &str) -> Result<()> { + let now = current_timestamp(); + let conn = self.conn.lock().unwrap(); + conn.execute( + "UPDATE nodes SET parent_id = ?1, name = ?2, modified_at = ?3 WHERE id = ?4", + params![new_parent_id, new_name, now, id], + )?; + Ok(()) + } + + /// Liest einen verschlüsselten Chunk aus der Datenbank. + pub fn read_chunk(&self, node_id: i64, chunk_index: u32) -> Result> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT nonce, tag, ciphertext FROM chunks WHERE node_id = ?1 AND chunk_index = ?2", + )?; + + let record = stmt + .query_row(params![node_id, chunk_index], |row| { + let nonce_vec: Vec = row.get(0)?; + let tag_vec: Vec = row.get(1)?; + let ciphertext: Vec = row.get(2)?; + + let mut nonce = [0u8; 12]; + let mut tag = [0u8; 16]; + if nonce_vec.len() == 12 { + nonce.copy_from_slice(&nonce_vec); + } + if tag_vec.len() == 16 { + tag.copy_from_slice(&tag_vec); + } + + Ok(ChunkRecord { + node_id, + chunk_index, + nonce, + tag, + ciphertext, + }) + }) + .optional()?; + + Ok(record) + } + + /// Schreibt oder aktualisiert einen verschlüsselten Chunk in der Datenbank. + pub fn write_chunk( + &self, + node_id: i64, + chunk_index: u32, + nonce: &[u8; 12], + tag: &[u8; 16], + ciphertext: &[u8], + ) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute( + "INSERT INTO chunks (node_id, chunk_index, nonce, tag, ciphertext) + VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(node_id, chunk_index) DO UPDATE SET + nonce = excluded.nonce, + tag = excluded.tag, + ciphertext = excluded.ciphertext", + params![ + node_id, + chunk_index, + nonce.as_slice(), + tag.as_slice(), + ciphertext, + ], + )?; + Ok(()) + } + + /// Schneidet überzählige Chunks ab (z. B. beim Truncate oder Überschreiben mit kleinerer Datei). + pub fn truncate_chunks_after(&self, node_id: i64, max_chunk_index: u32) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute( + "DELETE FROM chunks WHERE node_id = ?1 AND chunk_index > ?2", + params![node_id, max_chunk_index], + )?; + Ok(()) + } + + /// Erzwingt einen SQLite WAL Checkpoint und leert das Write-Ahead-Log. + pub fn checkpoint(&self) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_storage_schema_and_path_resolution() { + let db = Database::open_in_memory().unwrap(); + let salt = [1u8; 16]; + let kdf_params = KdfParams::default(); + let wrapped_dek = vec![2u8; 32]; + let nonce = [3u8; 12]; + let tag = [4u8; 16]; + + db.init_schema(&salt, &kdf_params, &wrapped_dek, &nonce, &tag).unwrap(); + + // Meta abrufen + let meta = db.read_meta().unwrap(); + assert_eq!(meta.version, FORMAT_VERSION); + assert_eq!(meta.kdf_salt, salt); + assert_eq!(meta.wrapped_dek, wrapped_dek); + + // Root prüfen + let root = db.resolve_path("/").unwrap().expect("Root node must exist"); + assert_eq!(root.id, 1); + assert!(root.is_dir); + + // Ordner und Datei erstellen + let docs = db.create_node(root.id, "documents", true).unwrap(); + assert_eq!(docs.name, "documents"); + assert!(docs.is_dir); + + let file = db.create_node(docs.id, "notes.txt", false).unwrap(); + assert_eq!(file.name, "notes.txt"); + assert!(!file.is_dir); + + // Pfadauflösung testen + let resolved_file = db.resolve_path("/documents/notes.txt").unwrap().expect("File should resolve"); + assert_eq!(resolved_file.id, file.id); + + let resolved_docs = db.resolve_path("documents").unwrap().expect("Docs should resolve"); + assert_eq!(resolved_docs.id, docs.id); + + // Chunks schreiben & lesen + let test_cipher = b"ENCRYPTED_DATA_BLOCK"; + let c_nonce = [7u8; 12]; + let c_tag = [8u8; 16]; + db.write_chunk(file.id, 0, &c_nonce, &c_tag, test_cipher).unwrap(); + + let chunk = db.read_chunk(file.id, 0).unwrap().expect("Chunk 0 should exist"); + assert_eq!(chunk.ciphertext, test_cipher); + + // Truncate + db.truncate_chunks_after(file.id, 0).unwrap(); + let chunk_after = db.read_chunk(file.id, 0).unwrap(); + assert!(chunk_after.is_some()); + + // Löschen + db.delete_node(file.id).unwrap(); + let deleted_res = db.resolve_path("/documents/notes.txt").unwrap(); + assert!(deleted_res.is_none()); + assert!(db.read_chunk(file.id, 0).unwrap().is_none()); + } +} diff --git a/src/vfs.rs b/src/vfs.rs new file mode 100644 index 0000000..ea1dbc9 --- /dev/null +++ b/src/vfs.rs @@ -0,0 +1,709 @@ +use std::fmt::Debug; +use std::io::SeekFrom; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use bytes::{Buf, Bytes, BytesMut}; +use dav_server::{ + davpath::DavPath, + fs::{ + DavDirEntry, DavFile, DavFileSystem, DavMetaData, FsError, FsFuture, FsResult, FsStream, + OpenOptions, ReadDirMeta, + }, +}; +use futures_util::stream; +use tracing::{debug, error, warn}; +use zeroize::Zeroizing; + +use crate::crypto::{decrypt_chunk, encrypt_chunk, CHUNK_SIZE}; +use crate::storage::{Database, NodeRecord}; + +// --------------------------------------------------------------------------- +// Metadaten +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct SanctumMetaData { + pub is_dir: bool, + pub size: u64, + pub modified_at: SystemTime, + pub created_at: SystemTime, +} + +impl DavMetaData for SanctumMetaData { + fn len(&self) -> u64 { + self.size + } + + fn modified(&self) -> FsResult { + Ok(self.modified_at) + } + + fn is_dir(&self) -> bool { + self.is_dir + } + + fn created(&self) -> FsResult { + Ok(self.created_at) + } + + fn is_file(&self) -> bool { + !self.is_dir + } +} + +// --------------------------------------------------------------------------- +// Verzeichniseintrag +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct SanctumDirEntry { + pub name: String, + pub meta: SanctumMetaData, +} + +impl DavDirEntry for SanctumDirEntry { + fn name(&self) -> Vec { + self.name.as_bytes().to_vec() + } + + fn metadata(&self) -> FsFuture<'_, Box> { + let meta = self.meta.clone(); + Box::pin(async move { Ok(Box::new(meta) as Box) }) + } +} + +// --------------------------------------------------------------------------- +// Datei-Handle mit Streaming & Chunk-Pufferung +// --------------------------------------------------------------------------- + +pub struct SanctumFile { + node_id: i64, + file_size: u64, + cursor: u64, + db: Database, + dek: Arc>, + meta: SanctumMetaData, + // (chunk_index, decrypted_payload, is_dirty) + cached_chunk: Option<(u32, Vec, bool)>, +} + +impl Debug for SanctumFile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SanctumFile") + .field("node_id", &self.node_id) + .field("file_size", &self.file_size) + .field("cursor", &self.cursor) + .finish() + } +} + +impl SanctumFile { + pub fn new( + node: NodeRecord, + db: Database, + dek: Arc>, + ) -> Self { + let meta = SanctumMetaData { + is_dir: node.is_dir, + size: node.size, + created_at: UNIX_EPOCH + Duration::from_secs(node.created_at), + modified_at: UNIX_EPOCH + Duration::from_secs(node.modified_at), + }; + + Self { + node_id: node.id, + file_size: node.size, + cursor: 0, + db, + dek, + meta, + cached_chunk: None, + } + } + + /// Schreibt den aktuell im RAM gehaltenen Chunk verschlüsselt in die SQLite-Datenbank zurück. + fn flush_cached_chunk(&mut self) -> Result<(), FsError> { + if let Some((idx, ref data, true)) = self.cached_chunk { + let (ciphertext, nonce, tag) = + encrypt_chunk(&self.dek, self.node_id, idx, data).map_err(|e| { + error!("Verschlüsselungsfehler beim Chunk-Flush: {e}"); + FsError::GeneralFailure + })?; + + self.db + .write_chunk(self.node_id, idx, &nonce, &tag, &ciphertext) + .map_err(|e| { + error!("DB-Fehler beim Schreiben des Chunks: {e}"); + FsError::GeneralFailure + })?; + + if let Some((_, _, ref mut dirty)) = self.cached_chunk { + *dirty = false; + } + } + Ok(()) + } + + /// Stellt sicher, dass der angeforderte Chunk im Cache geladen und entschlüsselt ist. + fn ensure_chunk_loaded(&mut self, chunk_index: u32) -> Result<&mut Vec, FsError> { + let is_current = match &self.cached_chunk { + Some((idx, _, _)) => *idx == chunk_index, + None => false, + }; + + if !is_current { + self.flush_cached_chunk()?; + + let payload = match self.db.read_chunk(self.node_id, chunk_index).map_err(|e| { + error!("Fehler beim Lesen des Chunks #{chunk_index}: {e}"); + FsError::GeneralFailure + })? { + Some(record) => decrypt_chunk( + &self.dek, + self.node_id, + chunk_index, + &record.ciphertext, + &record.nonce, + &record.tag, + ) + .map_err(|e| { + error!("AEAD-Entschlüsselungsfehler bei Chunk #{chunk_index}: {e}"); + FsError::GeneralFailure + })?, + None => Vec::new(), + }; + + self.cached_chunk = Some((chunk_index, payload, false)); + } + + match &mut self.cached_chunk { + Some((_, ref mut data, _)) => Ok(data), + None => unreachable!(), + } + } +} + +impl Drop for SanctumFile { + fn drop(&mut self) { + if let Err(e) = self.flush_cached_chunk() { + warn!("Fehler beim automatischen Flush im SanctumFile::drop: {:?}", e); + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let _ = self.db.update_node_size_and_time(self.node_id, self.file_size, now); + } +} + +impl DavFile for SanctumFile { + fn metadata(&mut self) -> FsFuture<'_, Box> { + self.meta.size = self.file_size; + let meta = self.meta.clone(); + Box::pin(async move { Ok(Box::new(meta) as Box) }) + } + + fn read_bytes(&mut self, mut count: usize) -> FsFuture<'_, Bytes> { + Box::pin(async move { + if self.cursor >= self.file_size || count == 0 { + return Ok(Bytes::new()); + } + + let remaining_file = (self.file_size - self.cursor) as usize; + if count > remaining_file { + count = remaining_file; + } + + let mut result = BytesMut::with_capacity(count); + + while count > 0 && self.cursor < self.file_size { + let chunk_idx = (self.cursor / CHUNK_SIZE as u64) as u32; + let offset_in_chunk = (self.cursor % CHUNK_SIZE as u64) as usize; + let bytes_in_chunk_left = CHUNK_SIZE - offset_in_chunk; + + let to_read = count + .min(bytes_in_chunk_left) + .min((self.file_size - self.cursor) as usize); + + let chunk_data = self.ensure_chunk_loaded(chunk_idx)?; + if offset_in_chunk >= chunk_data.len() { + break; + } + + let available = (chunk_data.len() - offset_in_chunk).min(to_read); + result.extend_from_slice(&chunk_data[offset_in_chunk..offset_in_chunk + available]); + + self.cursor += available as u64; + count -= available; + + if available < to_read { + break; + } + } + + Ok(result.freeze()) + }) + } + + fn write_bytes(&mut self, buf: Bytes) -> FsFuture<'_, ()> { + Box::pin(async move { + let mut src = &buf[..]; + + while !src.is_empty() { + let chunk_idx = (self.cursor / CHUNK_SIZE as u64) as u32; + let offset_in_chunk = (self.cursor % CHUNK_SIZE as u64) as usize; + let space_in_chunk = CHUNK_SIZE - offset_in_chunk; + let to_write = src.len().min(space_in_chunk); + + let chunk_data = self.ensure_chunk_loaded(chunk_idx)?; + + if chunk_data.len() < offset_in_chunk { + chunk_data.resize(offset_in_chunk, 0); + } + if chunk_data.len() < offset_in_chunk + to_write { + chunk_data.resize(offset_in_chunk + to_write, 0); + } + + chunk_data[offset_in_chunk..offset_in_chunk + to_write] + .copy_from_slice(&src[..to_write]); + + if let Some((_, _, ref mut dirty)) = self.cached_chunk { + *dirty = true; + } + + self.cursor += to_write as u64; + if self.cursor > self.file_size { + self.file_size = self.cursor; + } + + // Wenn der Chunk exakt 1 MB erreicht hat, sofort flushen, um RAM zu schonen + if self.cached_chunk.as_ref().map(|(_, d, _)| d.len() >= CHUNK_SIZE).unwrap_or(false) { + self.flush_cached_chunk()?; + } + + src = &src[to_write..]; + } + + Ok(()) + }) + } + + fn write_buf(&mut self, mut buf: Box) -> FsFuture<'_, ()> { + let bytes = buf.copy_to_bytes(buf.remaining()); + self.write_bytes(bytes) + } + + fn seek(&mut self, pos: SeekFrom) -> FsFuture<'_, u64> { + Box::pin(async move { + let new_cursor = match pos { + SeekFrom::Start(offset) => offset as i64, + SeekFrom::End(offset) => self.file_size as i64 + offset, + SeekFrom::Current(offset) => self.cursor as i64 + offset, + }; + + if new_cursor < 0 { + return Err(FsError::GeneralFailure); + } + + self.cursor = new_cursor as u64; + Ok(self.cursor) + }) + } + + fn flush(&mut self) -> FsFuture<'_, ()> { + Box::pin(async move { + self.flush_cached_chunk()?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + self.db + .update_node_size_and_time(self.node_id, self.file_size, now) + .map_err(|e| { + error!("Fehler beim Aktualisieren der Knotengröße: {e}"); + FsError::GeneralFailure + })?; + self.meta.size = self.file_size; + self.meta.modified_at = UNIX_EPOCH + Duration::from_secs(now); + Ok(()) + }) + } +} + +// --------------------------------------------------------------------------- +// DavFileSystem Implementierung +// --------------------------------------------------------------------------- + +#[derive(Clone)] +pub struct SanctumFs { + db: Database, + dek: Arc>, +} + +impl SanctumFs { + pub fn new(db: Database, dek: Zeroizing<[u8; 32]>) -> Self { + Self { + db, + dek: Arc::new(dek), + } + } + + fn path_to_str(path: &DavPath) -> String { + String::from_utf8_lossy(path.as_bytes()).to_string() + } + + fn split_parent_and_name<'a>(&self, path: &'a str) -> (&'a str, &'a str) { + let trimmed = path.trim_matches('/'); + match trimmed.rfind('/') { + Some(pos) => (&trimmed[..pos], &trimmed[pos + 1..]), + None => ("", trimmed), + } + } +} + +impl DavFileSystem for SanctumFs { + fn open<'a>( + &'a self, + path: &'a DavPath, + options: OpenOptions, + ) -> FsFuture<'a, Box> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + debug!("VFS open aufgerufen: path='{}', options={:?}", path_str, options); + + let existing_node = self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)?; + + let node = match existing_node { + Some(n) => { + if n.is_dir && (options.write || options.append) { + return Err(FsError::Forbidden); + } + if options.create_new { + return Err(FsError::Exists); + } + + if options.truncate { + self.db + .truncate_chunks_after(n.id, 0) + .map_err(|_| FsError::GeneralFailure)?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + self.db + .update_node_size_and_time(n.id, 0, now) + .map_err(|_| FsError::GeneralFailure)?; + + NodeRecord { + size: 0, + modified_at: now, + ..n + } + } else { + n + } + } + None => { + if options.create || options.create_new { + let (parent_path, file_name) = self.split_parent_and_name(&path_str); + let parent = self + .db + .resolve_path(parent_path) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if !parent.is_dir { + return Err(FsError::Forbidden); + } + + self.db + .create_node(parent.id, file_name, false) + .map_err(|e| { + error!("Fehler beim Erstellen der Datei: {e}"); + FsError::GeneralFailure + })? + } else { + return Err(FsError::NotFound); + } + } + }; + + let file = SanctumFile::new(node, self.db.clone(), self.dek.clone()); + Ok(Box::new(file) as Box) + }) + } + + fn read_dir<'a>( + &'a self, + path: &'a DavPath, + _meta: ReadDirMeta, + ) -> FsFuture<'a, FsStream>> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + let node = self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if !node.is_dir { + return Err(FsError::Forbidden); + } + + let children = self + .db + .list_children(node.id) + .map_err(|_| FsError::GeneralFailure)?; + + let entries: Vec, FsError>> = children + .into_iter() + .map(|child| { + Ok(Box::new(SanctumDirEntry { + name: child.name, + meta: SanctumMetaData { + is_dir: child.is_dir, + size: child.size, + created_at: UNIX_EPOCH + Duration::from_secs(child.created_at), + modified_at: UNIX_EPOCH + Duration::from_secs(child.modified_at), + }, + }) as Box) + }) + .collect(); + + Ok(Box::pin(stream::iter(entries)) as FsStream>) + }) + } + + fn metadata<'a>(&'a self, path: &'a DavPath) -> FsFuture<'a, Box> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + let node = self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + let meta = SanctumMetaData { + is_dir: node.is_dir, + size: node.size, + created_at: UNIX_EPOCH + Duration::from_secs(node.created_at), + modified_at: UNIX_EPOCH + Duration::from_secs(node.modified_at), + }; + + Ok(Box::new(meta) as Box) + }) + } + + fn create_dir<'a>(&'a self, path: &'a DavPath) -> FsFuture<'a, ()> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + if self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)? + .is_some() + { + return Err(FsError::Exists); + } + + let (parent_path, dir_name) = self.split_parent_and_name(&path_str); + let parent = self + .db + .resolve_path(parent_path) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if !parent.is_dir { + return Err(FsError::Forbidden); + } + + self.db + .create_node(parent.id, dir_name, true) + .map_err(|_| FsError::GeneralFailure)?; + + Ok(()) + }) + } + + fn remove_dir<'a>(&'a self, path: &'a DavPath) -> FsFuture<'a, ()> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + let node = self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if !node.is_dir { + return Err(FsError::Forbidden); + } + if node.id == 1 { + // Root-Verzeichnis darf nicht gelöscht werden + return Err(FsError::Forbidden); + } + + self.db + .delete_node(node.id) + .map_err(|_| FsError::GeneralFailure)?; + + Ok(()) + }) + } + + fn remove_file<'a>(&'a self, path: &'a DavPath) -> FsFuture<'a, ()> { + Box::pin(async move { + let path_str = Self::path_to_str(path); + let node = self + .db + .resolve_path(&path_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if node.is_dir { + return Err(FsError::Forbidden); + } + + self.db + .delete_node(node.id) + .map_err(|_| FsError::GeneralFailure)?; + + Ok(()) + }) + } + + fn rename<'a>( + &'a self, + from: &'a DavPath, + to: &'a DavPath, + ) -> FsFuture<'a, ()> { + Box::pin(async move { + let from_str = Self::path_to_str(from); + let to_str = Self::path_to_str(to); + + let node = self + .db + .resolve_path(&from_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + let (to_parent_path, to_name) = self.split_parent_and_name(&to_str); + let to_parent = self + .db + .resolve_path(to_parent_path) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if !to_parent.is_dir { + return Err(FsError::Forbidden); + } + + // Falls Zieldatei bereits existiert und Datei ist: überschreiben / löschen + if let Some(dest) = self + .db + .resolve_path(&to_str) + .map_err(|_| FsError::GeneralFailure)? + { + if dest.is_dir { + return Err(FsError::Forbidden); + } + self.db + .delete_node(dest.id) + .map_err(|_| FsError::GeneralFailure)?; + } + + self.db + .rename_node(node.id, to_parent.id, to_name) + .map_err(|_| FsError::GeneralFailure)?; + + Ok(()) + }) + } + + fn copy<'a>( + &'a self, + from: &'a DavPath, + to: &'a DavPath, + ) -> FsFuture<'a, ()> { + Box::pin(async move { + let from_str = Self::path_to_str(from); + let to_str = Self::path_to_str(to); + + let node = self + .db + .resolve_path(&from_str) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + if node.is_dir { + return Err(FsError::NotImplemented); + } + + let (to_parent_path, to_name) = self.split_parent_and_name(&to_str); + let to_parent = self + .db + .resolve_path(to_parent_path) + .map_err(|_| FsError::GeneralFailure)? + .ok_or(FsError::NotFound)?; + + let dest_node = self + .db + .create_node(to_parent.id, to_name, false) + .map_err(|_| FsError::GeneralFailure)?; + + // Kopiere alle Chunks und re-verschlüssele mit neuer node_id (wegen AAD-Bindung!) + let total_chunks = if node.size == 0 { + 0 + } else { + ((node.size - 1) / CHUNK_SIZE as u64 + 1) as u32 + }; + + for idx in 0..total_chunks { + if let Some(record) = self + .db + .read_chunk(node.id, idx) + .map_err(|_| FsError::GeneralFailure)? + { + let plaintext = decrypt_chunk( + &self.dek, + node.id, + idx, + &record.ciphertext, + &record.nonce, + &record.tag, + ) + .map_err(|_| FsError::GeneralFailure)?; + + let (new_ct, new_nonce, new_tag) = + encrypt_chunk(&self.dek, dest_node.id, idx, &plaintext) + .map_err(|_| FsError::GeneralFailure)?; + + self.db + .write_chunk(dest_node.id, idx, &new_nonce, &new_tag, &new_ct) + .map_err(|_| FsError::GeneralFailure)?; + } + } + + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + self.db + .update_node_size_and_time(dest_node.id, node.size, now) + .map_err(|_| FsError::GeneralFailure)?; + + Ok(()) + }) + } + + fn get_quota(&self) -> FsFuture<'_, (u64, Option)> { + Box::pin(async move { + // Virtueller Speicherplatz für Explorer: 1 TB + let total_capacity: u64 = 1024 * 1024 * 1024 * 1024; + Ok((0, Some(total_capacity))) + }) + } +} diff --git a/tests/integration_test.rs b/tests/integration_test.rs new file mode 100644 index 0000000..ae620a3 --- /dev/null +++ b/tests/integration_test.rs @@ -0,0 +1,160 @@ +use std::io::SeekFrom; +use std::path::PathBuf; + +use bytes::Bytes; +use dav_server::{ + davpath::DavPath, + fs::{DavFileSystem, OpenOptions, ReadDirMeta}, +}; +use futures_util::StreamExt; +use sanctum::{ + crypto::{ + derive_kek, generate_dek, generate_salt, unwrap_dek, wrap_dek, KdfParams, CHUNK_SIZE, + FORMAT_VERSION, + }, + storage::Database, + vfs::SanctumFs, +}; + +#[tokio::test] +async fn test_sanctum_full_container_lifecycle() { + let temp_dir = std::env::temp_dir(); + let container_path: PathBuf = temp_dir.join(format!("test_sanctum_{}.sanctum", std::process::id())); + + // Aufräumen, falls alte Testdatei existiert + if container_path.exists() { + let _ = std::fs::remove_file(&container_path); + } + + let password = "CorrectMasterPassword2026!"; + let wrong_password = "WrongMasterPassword!"; + + // 1. Initialisierung + let salt = generate_salt(); + let kdf_params = KdfParams { + memory_cost: 1024, // Schnell für Tests + time_cost: 1, + parallelism: 1, + }; + let kek = derive_kek(password, &salt, &kdf_params).expect("KEK derivation"); + let dek = generate_dek(); + let (wrapped_dek, header_nonce, header_tag) = + wrap_dek(&kek, &dek).expect("DEK wrapping"); + + let db = Database::open(&container_path).expect("Open database"); + db.init_schema(&salt, &kdf_params, &wrapped_dek, &header_nonce, &header_tag) + .expect("Init schema"); + db.checkpoint().expect("Checkpoint"); + + // 2. Header & Magic Bytes Prüfung + let meta = db.read_meta().expect("Read meta"); + assert_eq!(meta.version, FORMAT_VERSION); + assert_eq!(meta.kdf_salt, salt); + assert_eq!(meta.wrapped_dek, wrapped_dek); + + // Falsches Passwort schlägt fehl + let wrong_kek = derive_kek(wrong_password, &meta.kdf_salt, &meta.kdf_params).unwrap(); + assert!(unwrap_dek(&wrong_kek, &meta.wrapped_dek, &meta.header_nonce, &meta.header_tag).is_err()); + + // Richtiges Passwort entschlüsselt DEK + let unwrapped_dek = + unwrap_dek(&kek, &meta.wrapped_dek, &meta.header_nonce, &meta.header_tag).unwrap(); + assert_eq!(*dek, *unwrapped_dek); + + // 3. VFS Filesystem-Operationen (WebDAV Trait) + let fs = SanctumFs::new(db.clone(), unwrapped_dek); + + // Ordner erstellen + let docs_path = DavPath::new("/documents").unwrap(); + fs.create_dir(&docs_path).await.expect("Create /documents"); + + let docs_meta = fs.metadata(&docs_path).await.expect("Metadata /documents"); + assert!(docs_meta.is_dir()); + + // Multi-MB Datei über mehrere Chunks hinweg schreiben (2.5 MB = 3 Chunks à 1 MB) + let file_path = DavPath::new("/documents/large_payload.bin").unwrap(); + let mut opts_write = OpenOptions::default(); + opts_write.write = true; + opts_write.create_new = true; + + let mut file = fs.open(&file_path, opts_write).await.expect("Open for write"); + + let payload_size = (2.5 * CHUNK_SIZE as f64) as usize; + let mut sample_data = Vec::with_capacity(payload_size); + for i in 0..payload_size { + sample_data.push((i % 251) as u8); + } + + file.write_bytes(Bytes::copy_from_slice(&sample_data)) + .await + .expect("Write 2.5 MB"); + file.flush().await.expect("Flush file"); + drop(file); + + // Metadaten verifizieren + let file_meta = fs.metadata(&file_path).await.expect("Metadata file"); + assert_eq!(file_meta.len(), payload_size as u64); + assert!(!file_meta.is_dir()); + + // Datei lesen & Seek über Chunk-Grenzen testen + let mut opts_read = OpenOptions::default(); + opts_read.read = true; + let mut read_file = fs.open(&file_path, opts_read).await.expect("Open for read"); + + // Seek mitten in den 2. Chunk (1 MB + 500 Bytes) + let seek_offset = (CHUNK_SIZE + 500) as u64; + let new_pos = read_file + .seek(SeekFrom::Start(seek_offset)) + .await + .expect("Seek"); + assert_eq!(new_pos, seek_offset); + + // 2000 Bytes lesen (überschreitet evtl. Chunk-Grenze oder bleibt im Chunk) + let read_len = 2000; + let read_chunk_bytes = read_file.read_bytes(read_len).await.expect("Read bytes"); + assert_eq!(read_chunk_bytes.len(), read_len); + assert_eq!( + &read_chunk_bytes[..], + &sample_data[seek_offset as usize..seek_offset as usize + read_len] + ); + drop(read_file); + + // Datei umbenennen + let renamed_path = DavPath::new("/documents/renamed_payload.bin").unwrap(); + fs.rename(&file_path, &renamed_path).await.expect("Rename file"); + + assert!(fs.metadata(&file_path).await.is_err()); + let renamed_meta = fs.metadata(&renamed_path).await.expect("Metadata renamed"); + assert_eq!(renamed_meta.len(), payload_size as u64); + + // Datei kopieren + let copy_path = DavPath::new("/documents/copy_payload.bin").unwrap(); + fs.copy(&renamed_path, ©_path).await.expect("Copy file"); + let copy_meta = fs.metadata(©_path).await.expect("Metadata copy"); + assert_eq!(copy_meta.len(), payload_size as u64); + + // Verzeichnis auflisten + let stream = fs.read_dir(&docs_path, ReadDirMeta::None).await.expect("Read dir"); + let entries: Vec<_> = stream.collect().await; + assert_eq!(entries.len(), 2); // renamed_payload.bin & copy_payload.bin + + // Dateien und Verzeichnis löschen + fs.remove_file(&renamed_path).await.expect("Remove renamed"); + fs.remove_file(©_path).await.expect("Remove copy"); + fs.remove_dir(&docs_path).await.expect("Remove dir"); + + // Prüfen, dass Root leer ist + let root_path = DavPath::new("/").unwrap(); + let root_stream = fs.read_dir(&root_path, ReadDirMeta::None).await.expect("Read root"); + let root_entries: Vec<_> = root_stream.collect().await; + assert_eq!(root_entries.len(), 0); + + // Finaler DB Checkpoint + db.checkpoint().expect("Final checkpoint"); + drop(fs); + drop(db); + + // Verifizieren, dass die Containerdatei existiert und aufgeräumt werden kann + assert!(container_path.exists()); + let _ = std::fs::remove_file(&container_path); +}