diff --git a/Cargo.lock b/Cargo.lock index 0cd06e5..1a4ccad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,41 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ctutils", + "ghash", +] + [[package]] name = "ahash" version = "0.8.12" @@ -281,6 +316,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bit-vec" version = "0.9.1" @@ -302,7 +343,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -314,6 +355,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "brotli" version = "3.5.0" @@ -352,6 +411,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.11.1" @@ -376,6 +444,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -385,6 +464,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clap" version = "4.6.7" @@ -434,6 +524,24 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cms" +version = "0.3.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e99ff55bfffd019bf15e3f0d5edef2ca1e3af5ade276ed100e3c0c3455050c2" +dependencies = [ + "const-oid", + "der", + "spki", + "x509-cert", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -459,6 +567,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-random" version = "0.1.18" @@ -505,6 +619,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -514,6 +634,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.4" @@ -554,6 +683,33 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "daemonix" version = "0.1.0" @@ -591,6 +747,19 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "der-parser" version = "9.0.0" @@ -619,6 +788,17 @@ dependencies = [ "rusticata-macros", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -636,17 +816,38 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "des" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a" +dependencies = [ + "cipher", +] + [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -706,6 +907,12 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.11" @@ -879,6 +1086,16 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval", ] [[package]] @@ -947,6 +1164,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -992,6 +1218,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -1064,8 +1299,11 @@ dependencies = [ "ianitor-edge", "ianitor-testkit", "log", + "p12-keystore", + "qrcode", "rcgen", "ring", + "rpassword", "rustls", "serde", "serde_json", @@ -1281,6 +1519,16 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "instant-acme" version = "0.8.5" @@ -1613,6 +1861,29 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "p12-keystore" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2ed4fa0ec7ec58b657d4184680c57da9e203e97771d29a566028869a5193e0" +dependencies = [ + "cbc", + "cms", + "der", + "des", + "hex", + "hmac", + "pkcs12", + "pkcs5", + "pkcs8", + "rand 0.10.3", + "rc2", + "sha1 0.11.0", + "sha2", + "thiserror 2.0.21", + "x509-parser 0.18.1", +] + [[package]] name = "parking" version = "2.2.1" @@ -1642,6 +1913,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + [[package]] name = "pem" version = "4.0.0" @@ -1652,6 +1933,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1942,12 +2232,64 @@ dependencies = [ "tokio", ] +[[package]] +name = "pkcs12" +version = "0.2.0-rc.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca" +dependencies = [ + "cms", + "const-oid", + "der", + "digest 0.11.3", + "spki", + "x509-cert", + "zeroize", +] + +[[package]] +name = "pkcs5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" +dependencies = [ + "aes", + "aes-gcm", + "cbc", + "der", + "pbkdf2", + "scrypt", + "sha2", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[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.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.1", + "universal-hash", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1994,6 +2336,12 @@ dependencies = [ "yansi", ] +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quote" version = "1.0.47" @@ -2036,6 +2384,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -2074,6 +2433,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rc2" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe" +dependencies = [ + "cipher", +] + [[package]] name = "rcgen" version = "0.14.10" @@ -2159,6 +2533,27 @@ dependencies = [ "serde", ] +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rust_decimal" version = "1.43.0" @@ -2295,6 +2690,16 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" +dependencies = [ + "cfg-if", + "cipher", +] + [[package]] name = "same-file" version = "1.0.6" @@ -2319,6 +2724,18 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0" +dependencies = [ + "cfg-if", + "pbkdf2", + "salsa20", + "sha2", +] + [[package]] name = "security-framework" version = "2.11.1" @@ -2473,8 +2890,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2531,6 +2970,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2931,7 +3380,7 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "sha1", + "sha1 0.10.7", "thiserror 2.0.21", ] @@ -2962,6 +3411,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -3203,6 +3662,17 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid", + "der", + "spki", +] + [[package]] name = "x509-parser" version = "0.16.0" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3929d18..d2a3801 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -29,11 +29,16 @@ ring.workspace = true base64.workspace = true http.workspace = true bytes.workspace = true -# Dev mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3). rcgen.workspace = true +# Device certificate install files (PKCS#12) and their QR codes. +p12-keystore = "0.4" +qrcode = { version = "0.14", default-features = false, features = ["svg"] } +# The offline root CLI asks for its passphrase without echo. +rpassword = "7" [dev-dependencies] ianitor-testkit.workspace = true +p12-keystore = "0.4" ianitor-edge.workspace = true rustls.workspace = true diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index a35e23a..59a8df2 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -48,6 +48,16 @@ pub struct Config { pub compile: Compile, /// Different facts for the Caddy output (only tests need this: both engines side by side). pub compile_caddy: Option, + /// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already + /// and the certificate screens say the CA is not set up. + #[serde(default)] + pub pki: Option, + /// The web UI behind edge (sign-in through Authelia, see docs/api.md). + #[serde(default)] + pub ui: Option, + /// Switching between Pingora and the Caddy fallback at runtime. + #[serde(default)] + pub engine: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -280,3 +290,73 @@ fn empty_model() -> Option { ) .ok() } + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PkiConfig { + /// The Domi root certificate (public; may be a Nix store path). The root key is never on + /// the server. + pub root_cert: PathBuf, + /// Credential with the password that encrypts the intermediate and device keys at rest. + #[serde(default = "default_pki_password")] + pub password_credential: String, + /// How requests are approved: `manual` (`ianitor-control pki approve ` on the + /// server) until Custos can (docs/custos-ticket.md). + #[serde(default = "default_approval")] + pub approval: String, + /// PBKDF2 iterations for the keys control encrypts (only tests lower it). + #[serde(default = "default_kdf")] + pub kdf_iterations: u32, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UiConfig { + /// The admin host edge serves the UI on (a host in the routes repository with + /// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to + /// `allowed_hosts`; used for device install links. + pub hostname: Option, + /// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin + /// host. With it, a request carrying the proof is identified by its `Remote-User`. + pub proof_credential: Option, + /// The built web UI (served at `/`). + pub static_dir: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EngineConfig { + /// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit). + pub file: PathBuf, + /// `systemctl` (through the polkit rule for exactly the two units) or `none`. + #[serde(default = "default_units")] + pub units: String, + #[serde(default = "default_systemctl")] + pub systemctl: PathBuf, + #[serde(default = "default_edge_unit")] + pub edge_unit: String, + #[serde(default = "default_caddy_unit")] + pub caddy_unit: String, +} + +fn default_pki_password() -> String { + "pki-password".into() +} +fn default_approval() -> String { + "manual".into() +} +fn default_kdf() -> u32 { + ianitor_core::pki::KEY_KDF_ITERATIONS +} +fn default_units() -> String { + "systemctl".into() +} +fn default_systemctl() -> PathBuf { + PathBuf::from("systemctl") +} +fn default_edge_unit() -> String { + "ianitor-edge.service".into() +} +fn default_caddy_unit() -> String { + "caddy-fallback.service".into() +} diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 70930e6..22f43c3 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -174,6 +174,9 @@ pub async fn run(args: &[String]) -> Result<(), String> { caddy_admin: None, }, compile_caddy: None, + pki: None, + ui: None, + engine: None, }; cfg.check().map_err(|e| e.to_string())?; Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) diff --git a/crates/control/src/edgelink.rs b/crates/control/src/edgelink.rs index 5485e57..045e1f7 100644 --- a/crates/control/src/edgelink.rs +++ b/crates/control/src/edgelink.rs @@ -174,6 +174,13 @@ impl EdgeLink { Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned()) } + /// Re-read the device CA bundle and allow list (works during a trial too). + pub async fn reload_devices(&self) -> Result<(), EdgeLinkError> { + self.call("POST", "/v1/device-certs/reload", None) + .await + .map(|_| ()) + } + pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> { self.call("POST", "/v1/share-revocations/reload", None) .await diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 19ccbeb..573484d 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -141,6 +141,12 @@ pub struct Control { pub tokens: Tokens, pub shares: Shares, pub share_key: Option, + /// The Domi CA, when `[pki]` is configured. + pub pki: Option, + /// Which engine serves (see `switch`). + pub engine: Mutex, + /// How control starts and stops the engines; `None` without `[engine]`. + pub units: Option>, records: Mutex>, queue: Mutex>, wake: Notify, @@ -151,7 +157,7 @@ pub struct Control { /// False while the pause is only in memory (paused.json could not be written). pause_saved: std::sync::atomic::AtomicBool, /// Serialises applies with share-revocation writes and recovery. - apply_lock: tokio::sync::Mutex<()>, + pub(crate) apply_lock: tokio::sync::Mutex<()>, } const MAX_RECORDS: usize = 1000; @@ -207,6 +213,21 @@ impl Control { if share_key.is_none() { log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made"); } + let keys = crate::pki::root_key_files(&cfg.state_dir); + if let Some(k) = keys.first() { + return Err(format!( + "{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.", + k.display() + )); + } + let pki = match &cfg.pki { + Some(p) => Some(crate::pki::Pki::open( + p, + &cfg.state_dir, + cfg.credential(&p.password_credential), + )?), + None => None, + }; let records: Vec = read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default(); let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default(); @@ -217,6 +238,19 @@ impl Control { repo, edge, share_key, + pki, + engine: Mutex::new(crate::switch::EngineState { + running: cfg + .engine + .as_ref() + .map(|e| crate::switch::read_engine_file(&e.file)) + .unwrap_or_else(|| "pingora".into()), + state: "running".into(), + since: now(), + target: None, + last_error: None, + }), + units: crate::switch::units_for(cfg.engine.as_ref()), records: Mutex::new(records), queue: Mutex::new(VecDeque::new()), wake: Notify::new(), @@ -228,6 +262,11 @@ impl Control { apply_lock: tokio::sync::Mutex::new(()), cfg, }); + if let Ok((_, _, m)) = c.head_model() + && let Err(f) = c.pki_prepare(&m) + { + log::error!(target: "ianitor::pki", "{}", f.reason.message); + } c.recover().await?; Ok(c) } @@ -390,6 +429,9 @@ impl Control { /// `in_worker` is false when a request is first checked: a change that the worker may /// still let through (after it retried the files) is queued rather than refused. fn paused_for(&self, change: &Change, in_worker: bool) -> Option { + if let Some(e) = self.engine_pause() { + return Some(e); + } let p = self.paused()?; if !in_worker && p.code == "control.files_unwritten" { return None; @@ -863,6 +905,11 @@ impl Control { Ok(x) => x, Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()), }; + // Domi certificates for the hosts of the new tree, before anything is committed (new + // files only: a certificate edge serves now is never replaced by a worse one). + if let Err(f) = self.pki_prepare(&plan.model) { + return self.finish(&id, "failed", Some(f.reason), Vec::new()); + } self.update(&id, |r| { r.step("compile", "done"); r.step("write", "running"); diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 683a167..3740c9c 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -14,9 +14,12 @@ pub mod engine; pub mod hostspec; pub mod logger; pub mod messages; +pub mod pki; +pub mod pki_ctl; pub mod records; pub mod repo; pub mod shares; +pub mod switch; pub mod tokens; pub mod util; diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index 945f222..ee9ba0e 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -228,6 +228,88 @@ fn template(code: &str) -> &'static str { "health.unavailable" => { "Ianitor cannot read health from {engine} right now. Traffic is not affected." } + // 3.6 PKI + "pki.waiting" => { + "Open Custos on your phone. Approve only if it shows the same code: {code}." + } + "pki.waiting.manual" => { + "Approve it on the server: run ianitor-control pki approve {code}. Approve only if the code matches." + } + "pki.renew.manual" => { + "Sign this request on the offline machine (ianitor-control ca sign), check that it shows the code {code}, then install the certificate." + } + "pki.denied" => "The request was turned down. Nothing was issued.", + "pki.expired" => "Nobody approved it in time, so the request closed. Nothing was issued.", + "pki.custos_unreachable" => "Custos is not answering, so the request could not be sent.", + "pki.device_name_taken" => { + "A device with this name already has a certificate or an open request. Use another name, or revoke the old one first." + } + "pki.device_name" => "Give the device a name of 1 to 64 characters.", + "pki.device_kind" => "Choose phone, computer or app.", + "pki.issued" => "{name} has a certificate.", + "pki.bundle_used" => { + "This download was already used or has expired. Make a new one from the device's row." + } + "pki.renew_due" => "The Domi intermediate certificate expires in {days} days, on {date}.", + "pki.renew_urgent" => { + "The Domi intermediate certificate expires in {days} days. After that, Domi certificates stop working." + } + "pki.intermediate_expired" => { + "The Domi intermediate certificate has expired. Hosts with a Domi certificate are not trusted until it is renewed." + } + "pki.renewed" => "Renewed. The Domi intermediate certificate is now valid until {date}.", + "pki.not_configured" => { + "The Domi certificate authority is not set up on this server. See docs/pki.md." + } + "pki.no_password" => { + "The password for the Domi certificate keys is missing from the server's credentials, so nothing can be issued." + } + "pki.wrong_password" => { + "The password for the Domi certificate keys does not open them. Check the pki-password credential." + } + "pki.no_intermediate" => { + "There is no Domi intermediate certificate yet, so Domi certificates cannot be issued. Set it up first in Certificates." + } + "pki.not_our_root" => { + "This certificate was not signed by the Domi root this server trusts." + } + "pki.wrong_key" => { + "This certificate was made for another request. Sign the request shown here, then try again." + } + "pki.bad_certificate" => { + "This is not a Domi intermediate certificate Ianitor can use. It must be a CA with path length 0 that is valid now." + } + "pki.request_not_found" => "There is no such request.", + "pki.request_closed" => "This request is closed. Start a new one.", + "pki.wrong_code" => "That code does not match the request.", + "pki.too_many_requests" => "Too many requests are open. Finish or cancel some first.", + "pki.device_not_found" => "There is no such device.", + "pki.device_not_valid" => { + "This device's certificate is revoked or expired, so it cannot be installed. Issue a new one." + } + "pki.revoked" => { + "Revoked. {name} can no longer reach hosts that need a device certificate." + } + // UI sign-in + "ui.no_proof" => { + "This request carries a sign-in header but did not come through Ianitor's proxy, so it was refused." + } + "ui.no_user" => "The sign-in did not say who you are. Sign in again.", + // engine switch + "engine.unmanaged" => { + "This server does not let Ianitor switch engines (no engine settings in control.toml)." + } + "engine.same" => "{engine} is already serving.", + "engine.switching" => "A switch is already running. Wait for it to finish.", + "engine.busy" => "A change is being applied. Switch when it has finished.", + "engine.switched" => "{engine} is serving now.", + "engine.switch_failed" => { + "{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before." + } + "engine.caddy" => "Caddy is serving. Changes wait until you switch back to Pingora.", + "share.engine_caddy" => { + "Share links are paused while Caddy serves. They work again after switching back." + } "internal" => "Something went wrong inside Ianitor control. Show details for more.", _ => "Something went wrong.", } diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs new file mode 100644 index 0000000..d68c990 --- /dev/null +++ b/crates/control/src/pki.rs @@ -0,0 +1,1058 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA on the server (ROADMAP §1.2, §3): the intermediate, the server certificates +//! of `tls = "domi"` hosts, device certificates and their install files, and the requests +//! that need an approval. +//! +//! Files, under `/pki/` (mode 0700): +//! +//! ```text +//! intermediate.crt the current intermediate (public) +//! intermediate.key its key, encrypted (IANITOR ENCRYPTED PRIVATE KEY, password from +//! the `pki-password` credential); never in plain text on disk +//! previous.crt the one before, while it is still valid (device CA bundle) +//! pending-.key the new key of an open renewal, encrypted the same way +//! requests.json approval requests (devices, renewals) +//! devices.json issued device certificates +//! devices/.key a device's key, encrypted, kept to make its install file again +//! approvals/.approve written by `ianitor-control pki approve` (the manual approval) +//! approvals/.deny written by `ianitor-control pki deny` +//! approvals/.crt the signed intermediate, from `pki install` or the API +//! ``` +//! +//! The root key is never here: control only reads the root *certificate* named in +//! control.toml, and refuses to start if a root key file appears in its state directory. +//! +//! Approvals: ROADMAP §4 says "approve in Custos". Custos has no such operation yet +//! (docs/custos-ticket.md), so until it does a request is approved on the server with the +//! match code the UI shows: `ianitor-control pki approve 47 19 83`. The intermediate is +//! signed offline (docs/pki.md). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use ianitor_core::pki::{self, Intermediate, PkiError}; +use serde::{Deserialize, Serialize}; + +use crate::config::PkiConfig; +use crate::util::{hex, random, read_json, remove_if_exists, write_atomic, write_json}; + +/// How long a device request waits for its approval. +pub const DEVICE_REQUEST_SECS: u64 = 600; +/// How long a renewal waits for the offline signature. +pub const RENEWAL_REQUEST_SECS: u64 = 7 * 86_400; +/// How long a device install link works. +pub const BUNDLE_SECS: u64 = 600; +/// Banner thresholds. +pub const DUE_DAYS: i64 = 30; +pub const URGENT_DAYS: i64 = 7; +/// Most open requests at once. +const MAX_OPEN: usize = 20; +/// Most devices with certificates (active or not) kept in the list. +const MAX_DEVICES: usize = 500; +/// Device kinds the UI offers. +pub const DEVICE_KINDS: [&str; 3] = ["phone", "computer", "app"]; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PkiFail { + /// A refusal with a stable code for the API (`pki.*`). + #[error("{0}")] + Code(&'static str), + #[error("{0}")] + Internal(String), +} + +impl From for PkiFail { + fn from(e: PkiError) -> Self { + PkiFail::Internal(e.to_string()) + } +} + +fn io(e: impl std::fmt::Display) -> PkiFail { + PkiFail::Internal(e.to_string()) +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Request { + pub id: String, + /// `device` or `intermediate`. + pub kind: String, + /// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`. + pub state: String, + pub match_code: String, + pub created_at: u64, + pub expires_at: u64, + #[serde(default)] + pub approved_at: Option, + /// Device requests: the name and kind asked for, and the device made. + #[serde(default)] + pub name: Option, + #[serde(default)] + pub device_kind: Option, + #[serde(default)] + pub device_id: Option, + /// Renewals: the CSR to sign offline. + #[serde(default)] + pub csr_pem: Option, + /// Renewals: when the new intermediate expires, once installed. + #[serde(default)] + pub not_after: Option, + /// Why it failed (plain English, no secrets). + #[serde(default)] + pub error: Option, + /// Who asked (token name or signed-in user). + #[serde(default)] + pub actor: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Device { + pub id: String, + pub name: String, + pub kind: String, + pub serial: String, + pub sha256: String, + pub cert_pem: String, + pub created_at: u64, + pub not_after: i64, + #[serde(default)] + pub revoked_at: Option, + /// Which intermediate issued it (its SHA-256). + pub issuer_sha256: String, +} + +impl Device { + pub fn state(&self, now: u64) -> &'static str { + if self.revoked_at.is_some() { + "revoked" + } else if self.not_after <= now as i64 { + "expired" + } else { + "valid" + } + } +} + +/// A one-time install file waiting to be downloaded. +struct Bundle { + device_id: String, + password: String, + expires_at: u64, +} + +/// What the main screen shows about the intermediate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IntermediateStatus { + /// `ok`, `due`, `urgent`, `expired` or `missing` (no intermediate yet). + pub state: &'static str, + pub subject: Option, + pub not_after: Option, + pub days_left: Option, + pub renewal: Option, +} + +/// What changed in one poll. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Changes { + pub devices: bool, + pub intermediate: bool, +} + +pub struct Pki { + dir: PathBuf, + root_pem: String, + password: Option>, + kdf_iterations: u32, + lock: Mutex<()>, + current: Mutex>>, + bundles: Mutex>, +} + +impl std::fmt::Debug for Pki { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Pki").field("dir", &self.dir).finish() + } +} + +fn id(prefix: &str) -> Result { + Ok(format!("{prefix}{}", hex(&random::<6>().map_err(io)?))) +} + +/// `47 19 83` from random bytes (device requests have no CSR to hash). +fn random_code() -> Result { + let b = random::<3>().map_err(io)?; + Ok(format!( + "{:02} {:02} {:02}", + b[0] % 100, + b[1] % 100, + b[2] % 100 + )) +} + +/// Digits only: `47 19 83`, `471983` and `47-19-83` are the same code. +pub fn normalise_code(c: &str) -> String { + c.chars().filter(char::is_ascii_digit).collect() +} + +/// A readable one-time password for an install file: 4 groups of 4 from 30 letters and +/// digits without look-alikes (about 78 bits). +fn bundle_password() -> Result { + const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + let b = random::<16>().map_err(io)?; + let mut s = String::new(); + for (i, x) in b.iter().enumerate() { + if i > 0 && i % 4 == 0 { + s.push('-'); + } + s.push(char::from(ALPHABET[(*x as usize) % ALPHABET.len()])); + } + Ok(s) +} + +/// Is there anything that looks like a root CA key in `dir` (recursively, shallow)? Control +/// refuses to run with one in its state directory (ROADMAP §1.2: the root is never on the +/// server). +pub fn root_key_files(dir: &Path) -> Vec { + let mut found = Vec::new(); + let mut stack = vec![(dir.to_path_buf(), 0)]; + while let Some((d, depth)) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + let name = e.file_name().to_string_lossy().to_ascii_lowercase(); + if p.is_dir() { + if depth < 3 { + stack.push((p, depth + 1)); + } + } else if name.starts_with("root") && (name.ends_with(".key") || name.contains("key")) { + found.push(p); + } + } + } + found +} + +impl Pki { + /// Open the CA state. The root certificate must be a CA and self-signed; the password + /// credential may be missing (then nothing can be issued, and the UI says why). + pub fn open( + cfg: &PkiConfig, + state_dir: &Path, + password: Option>, + ) -> Result { + let keys = root_key_files(state_dir); + if !keys.is_empty() { + return Err(format!( + "{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.", + keys[0].display() + )); + } + let root_pem = std::fs::read_to_string(&cfg.root_cert).map_err(|e| { + format!( + "cannot read the Domi root certificate {}: {e}", + cfg.root_cert.display() + ) + })?; + let info = + pki::inspect(&root_pem).map_err(|e| format!("{}: {e}", cfg.root_cert.display()))?; + if !info.is_ca || !pki::issued_by(&root_pem, &root_pem).unwrap_or(false) { + return Err(format!( + "{} is not a self-signed CA certificate", + cfg.root_cert.display() + )); + } + if root_pem.contains("PRIVATE KEY") { + return Err(format!( + "{} contains a private key; give control the root certificate only", + cfg.root_cert.display() + )); + } + let dir = state_dir.join("pki"); + for d in [dir.clone(), dir.join("devices"), dir.join("approvals")] { + std::fs::create_dir_all(&d) + .map_err(|e| format!("cannot create {}: {e}", d.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = if d.ends_with("approvals") { + 0o700 + } else { + 0o700 + }; + let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)); + } + } + Ok(Pki { + dir, + root_pem: pki::first_pem(&root_pem).map_err(|e| e.to_string())?, + password: password.filter(|p| !p.is_empty()), + kdf_iterations: cfg.kdf_iterations, + lock: Mutex::new(()), + current: Mutex::new(None), + bundles: Mutex::new(HashMap::new()), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn root_pem(&self) -> &str { + &self.root_pem + } + + fn password(&self) -> Result<&[u8], PkiFail> { + self.password + .as_deref() + .ok_or(PkiFail::Code("pki.no_password")) + } + + fn seal(&self, key: &pki::KeyPair) -> Result { + Ok(pki::encrypt_key_with( + key, + self.password()?, + self.kdf_iterations, + )?) + } + + fn open_key(&self, path: &Path) -> Result { + let sealed = std::fs::read_to_string(path).map_err(io)?; + pki::decrypt_key(&sealed, self.password()?).map_err(|e| match e { + PkiError::WrongPassword => PkiFail::Code("pki.wrong_password"), + other => PkiFail::Internal(other.to_string()), + }) + } + + fn guard(&self) -> Result, PkiFail> { + self.lock.lock().map_err(|_| io("pki lock")) + } + + fn requests(&self) -> Result, PkiFail> { + Ok(read_json(&self.dir.join("requests.json")) + .map_err(io)? + .unwrap_or_default()) + } + + fn save_requests(&self, r: &[Request]) -> Result<(), PkiFail> { + write_json(&self.dir.join("requests.json"), &r).map_err(io) + } + + pub fn devices(&self) -> Result, PkiFail> { + Ok(read_json(&self.dir.join("devices.json")) + .map_err(io)? + .unwrap_or_default()) + } + + fn save_devices(&self, d: &[Device]) -> Result<(), PkiFail> { + write_json(&self.dir.join("devices.json"), &d).map_err(io) + } + + // -------------------------------------------------------------- the intermediate + + /// The current intermediate, unlocked once and kept in memory. `None` before the first + /// one is installed. + pub fn intermediate(&self) -> Result>, PkiFail> { + if let Some(i) = self.current.lock().map_err(|_| io("pki"))?.as_ref() { + return Ok(Some(i.clone())); + } + let crt = self.dir.join("intermediate.crt"); + if !crt.exists() { + return Ok(None); + } + let pem = std::fs::read_to_string(&crt).map_err(io)?; + let key = self.open_key(&self.dir.join("intermediate.key"))?; + let int = Arc::new(Intermediate::new(&pem, key)?); + if !pki::issued_by(int.cert_pem(), &self.root_pem)? { + return Err(PkiFail::Code("pki.not_our_root")); + } + *self.current.lock().map_err(|_| io("pki"))? = Some(int.clone()); + Ok(Some(int)) + } + + /// The intermediate's public certificate, readable without the password. + fn intermediate_info(&self) -> Option { + let pem = std::fs::read_to_string(self.dir.join("intermediate.crt")).ok()?; + pki::inspect(&pem).ok() + } + + pub fn status(&self, now: u64) -> IntermediateStatus { + let renewal = self.requests().ok().and_then(|rs| { + rs.into_iter() + .rev() + .find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now) + }); + match self.intermediate_info() { + None => IntermediateStatus { + state: "missing", + subject: None, + not_after: None, + days_left: None, + renewal, + }, + Some(i) => { + let left = (i.not_after - now as i64).div_euclid(86_400); + let state = if i.not_after <= now as i64 { + "expired" + } else if left <= URGENT_DAYS { + "urgent" + } else if left <= DUE_DAYS { + "due" + } else { + "ok" + }; + IntermediateStatus { + state, + subject: Some(i.subject_cn), + not_after: Some(i.not_after), + days_left: Some(left.max(0)), + renewal, + } + } + } + } + + /// Start a renewal (or the first intermediate): a new key, encrypted at rest, and a CSR + /// to be signed by the root. An open renewal is returned again rather than replaced. + pub fn request_renewal(&self, now: u64, actor: &str) -> Result { + let _g = self.guard()?; + self.password()?; + let mut rs = self.requests()?; + if let Some(r) = rs + .iter() + .rev() + .find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now) + { + return Ok(r.clone()); + } + let key = pki::generate_key()?; + let (y, m, _) = ymd(now); + let cn = format!("{} {y:04}-{m:02}", pki::INTERMEDIATE_CN); + let csr = pki::intermediate_csr(&key, &cn)?; + let code = pki::match_code(&pki::csr_der(&csr)?); + let rid = id("pr_")?; + write_atomic( + &self.dir.join(format!("pending-{rid}.key")), + self.seal(&key)?.as_bytes(), + 0o600, + ) + .map_err(io)?; + let r = Request { + id: rid, + kind: "intermediate".into(), + state: "waiting".into(), + match_code: code, + created_at: now, + expires_at: now + RENEWAL_REQUEST_SECS, + approved_at: None, + name: None, + device_kind: None, + device_id: None, + csr_pem: Some(csr), + not_after: None, + error: None, + actor: actor.to_owned(), + }; + prune(&mut rs, now); + rs.push(r.clone()); + self.save_requests(&rs)?; + Ok(r) + } + + /// Install a signed intermediate for an open renewal (from `pki install` or the API). + /// Checks: signed by our root, a CA with path length 0, for the pending key, valid now. + pub fn install_intermediate( + &self, + request_id: &str, + cert_pem: &str, + now: u64, + ) -> Result { + let _g = self.guard()?; + let mut rs = self.requests()?; + let r = rs + .iter_mut() + .find(|r| r.id == request_id && r.kind == "intermediate") + .ok_or(PkiFail::Code("pki.request_not_found"))?; + if r.state != "waiting" || r.expires_at <= now { + return Err(PkiFail::Code("pki.request_closed")); + } + let first = pki::first_pem(cert_pem).map_err(|_| PkiFail::Code("pki.bad_certificate"))?; + let info = pki::inspect(&first).map_err(|_| PkiFail::Code("pki.bad_certificate"))?; + if !pki::issued_by(&first, &self.root_pem).unwrap_or(false) { + return Err(PkiFail::Code("pki.not_our_root")); + } + if !info.is_ca + || info.path_len != Some(0) + || !info.subject_cn.starts_with(pki::INTERMEDIATE_CN) + { + return Err(PkiFail::Code("pki.bad_certificate")); + } + if info.not_before > now as i64 + 300 || info.not_after <= now as i64 { + return Err(PkiFail::Code("pki.bad_certificate")); + } + let pending = self.dir.join(format!("pending-{request_id}.key")); + let key = self.open_key(&pending)?; + let int = Intermediate::new(&first, key).map_err(|e| match e { + PkiError::KeyMismatch => PkiFail::Code("pki.wrong_key"), + other => PkiFail::Internal(other.to_string()), + })?; + // Keep the old one for the device CA bundle while it is valid. + let crt = self.dir.join("intermediate.crt"); + if let Ok(old) = std::fs::read_to_string(&crt) { + write_atomic(&self.dir.join("previous.crt"), old.as_bytes(), 0o644).map_err(io)?; + } + let sealed = std::fs::read(&pending).map_err(io)?; + write_atomic(&self.dir.join("intermediate.key"), &sealed, 0o600).map_err(io)?; + write_atomic(&crt, first.as_bytes(), 0o644).map_err(io)?; + remove_if_exists(&pending).map_err(io)?; + *self.current.lock().map_err(|_| io("pki"))? = Some(Arc::new(int)); + r.state = "approved".into(); + r.approved_at = Some(now); + r.not_after = Some(info.not_after); + let out = r.clone(); + self.save_requests(&rs)?; + Ok(out) + } + + // -------------------------------------------------------------- server certificates + + /// Make sure every `tls = "domi"` host has a certificate from the current intermediate + /// with at least [`pki::SERVER_RENEW_DAYS`] left. Returns the hosts that got a new one. + /// Files: `/.crt` (leaf + intermediate, 0644), `.key` (0640). + pub fn ensure_host_certs( + &self, + hosts: &[String], + cert_dir: &Path, + now: u64, + ) -> Result, PkiFail> { + if hosts.is_empty() { + return Ok(Vec::new()); + } + let int = self + .intermediate()? + .ok_or(PkiFail::Code("pki.no_intermediate"))?; + let mut issued = Vec::new(); + for h in hosts { + let crt = cert_dir.join(format!("{h}.crt")); + let key = cert_dir.join(format!("{h}.key")); + let fine = std::fs::read_to_string(&crt).ok().is_some_and(|pem| { + pki::inspect(&pem).is_ok_and(|i| { + i.dns_names.iter().any(|n| n == h) + && i.not_after - now as i64 > i64::from(pki::SERVER_RENEW_DAYS) * 86_400 + && i.not_before <= now as i64 + 300 + }) && pki::issued_by(&pem, int.cert_pem()).unwrap_or(false) + }) && key.exists(); + if fine { + continue; + } + let leaf = pki::issue_server(&int, h, now as i64).map_err(|e| match e { + PkiError::IssuerExpired => PkiFail::Code("pki.intermediate_expired"), + other => PkiFail::Internal(other.to_string()), + })?; + // Key first: a certificate never points at a key that is not there yet. + write_atomic(&key, leaf.key_pem.as_bytes(), 0o640).map_err(io)?; + write_atomic(&crt, leaf.chain_pem.as_bytes(), 0o644).map_err(io)?; + issued.push(h.clone()); + } + Ok(issued) + } + + /// Write the device CA bundle and allow list into the certificate directory (what both + /// engines read). Returns whether either changed. + pub fn write_device_files(&self, cert_dir: &Path, now: u64) -> Result { + let mut ca = String::new(); + for f in ["intermediate.crt", "previous.crt"] { + if let Ok(pem) = std::fs::read_to_string(self.dir.join(f)) + && pki::inspect(&pem).is_ok_and(|i| i.not_after > now as i64) + { + ca.push_str(&pem); + } + } + if ca.is_empty() { + // Edge and Caddy refuse an empty bundle; the root keeps the bundle parseable + // while no intermediate exists, and the empty allow list still lets no one in. + ca.push_str(&self.root_pem); + } + let allow: String = self + .devices()? + .iter() + .filter(|d| d.state(now) == "valid") + .map(|d| d.cert_pem.as_str()) + .collect(); + let mut changed = false; + for (name, text) in [ + (ianitor_core::compile::DEVICE_CA_FILE, ca), + (ianitor_core::compile::DEVICE_ALLOW_FILE, allow), + ] { + let p = cert_dir.join(name); + if std::fs::read_to_string(&p).ok().as_deref() != Some(text.as_str()) { + write_atomic(&p, text.as_bytes(), 0o644).map_err(io)?; + changed = true; + } + } + Ok(changed) + } + + // -------------------------------------------------------------- devices + + pub fn request_device( + &self, + name: &str, + kind: &str, + now: u64, + actor: &str, + ) -> Result { + let _g = self.guard()?; + let name = name.trim(); + if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) { + return Err(PkiFail::Code("pki.device_name")); + } + if !DEVICE_KINDS.contains(&kind) { + return Err(PkiFail::Code("pki.device_kind")); + } + if self.intermediate_info().is_none() { + return Err(PkiFail::Code("pki.no_intermediate")); + } + self.password()?; + let taken = |n: &str| n.to_lowercase() == name.to_lowercase(); + if self + .devices()? + .iter() + .any(|d| d.state(now) == "valid" && taken(&d.name)) + { + return Err(PkiFail::Code("pki.device_name_taken")); + } + let mut rs = self.requests()?; + prune(&mut rs, now); + if rs.iter().any(|r| { + r.kind == "device" && r.state == "waiting" && r.name.as_deref().is_some_and(taken) + }) { + return Err(PkiFail::Code("pki.device_name_taken")); + } + if rs.iter().filter(|r| r.state == "waiting").count() >= MAX_OPEN { + return Err(PkiFail::Code("pki.too_many_requests")); + } + // A code no other open request has, so `pki approve ` is never ambiguous. + let mut code = random_code()?; + while rs + .iter() + .any(|r| r.state == "waiting" && normalise_code(&r.match_code) == normalise_code(&code)) + { + code = random_code()?; + } + let r = Request { + id: id("pr_")?, + kind: "device".into(), + state: "waiting".into(), + match_code: code, + created_at: now, + expires_at: now + DEVICE_REQUEST_SECS, + approved_at: None, + name: Some(name.to_owned()), + device_kind: Some(kind.to_owned()), + device_id: None, + csr_pem: None, + not_after: None, + error: None, + actor: actor.to_owned(), + }; + rs.push(r.clone()); + self.save_requests(&rs)?; + Ok(r) + } + + pub fn request(&self, id: &str, now: u64) -> Result, PkiFail> { + Ok(self + .requests()? + .into_iter() + .find(|r| r.id == id) + .map(|mut r| { + if r.state == "waiting" && r.expires_at <= now { + r.state = "expired".into(); + } + r + })) + } + + pub fn cancel(&self, id: &str) -> Result, PkiFail> { + let _g = self.guard()?; + let mut rs = self.requests()?; + let Some(r) = rs.iter_mut().find(|r| r.id == id) else { + return Ok(None); + }; + if r.state == "waiting" { + r.state = "cancelled".into(); + if r.kind == "intermediate" { + remove_if_exists(&self.dir.join(format!("pending-{id}.key"))).map_err(io)?; + } + } + let out = r.clone(); + self.save_requests(&rs)?; + Ok(Some(out)) + } + + /// Act on approvals and expiries. Called every couple of seconds by control. + pub fn poll(&self, now: u64) -> Result { + let mut changes = Changes::default(); + let approvals = self.dir.join("approvals"); + let ids: Vec = { + let mut v = Vec::new(); + if let Ok(rd) = std::fs::read_dir(&approvals) { + for e in rd.flatten() { + v.push(e.file_name().to_string_lossy().into_owned()); + } + } + v + }; + for f in ids { + let path = approvals.join(&f); + let Some((rid, what)) = f.rsplit_once('.') else { + let _ = remove_if_exists(&path); + continue; + }; + let rid = rid.to_owned(); + match what { + "approve" => { + let code = std::fs::read_to_string(&path).unwrap_or_default(); + let _ = remove_if_exists(&path); + if let Err(e) = self.approve_device(&rid, code.trim(), now) { + log::warn!(target: "ianitor::pki", "approval for {rid} not used: {e}"); + } else { + changes.devices = true; + } + } + "deny" => { + let _ = remove_if_exists(&path); + self.close(&rid, "denied", None)?; + } + "crt" => { + let pem = std::fs::read_to_string(&path).unwrap_or_default(); + let _ = remove_if_exists(&path); + match self.install_intermediate(&rid, &pem, now) { + Ok(_) => changes.intermediate = true, + Err(e) => { + log::warn!(target: "ianitor::pki", "intermediate for {rid} not installed: {e}"); + } + } + } + _ => { + let _ = remove_if_exists(&path); + } + } + } + // Expire what waited too long. + let _g = self.guard()?; + let mut rs = self.requests()?; + let mut dirty = false; + for r in rs.iter_mut() { + if r.state == "waiting" && r.expires_at <= now { + r.state = "expired".into(); + dirty = true; + if r.kind == "intermediate" { + let _ = remove_if_exists(&self.dir.join(format!("pending-{}.key", r.id))); + } + } + } + if dirty { + self.save_requests(&rs)?; + } + Ok(changes) + } + + fn close(&self, rid: &str, state: &str, error: Option) -> Result<(), PkiFail> { + let _g = self.guard()?; + let mut rs = self.requests()?; + if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") { + r.state = state.into(); + r.error = error; + if r.kind == "intermediate" { + let _ = remove_if_exists(&self.dir.join(format!("pending-{rid}.key"))); + } + self.save_requests(&rs)?; + } + Ok(()) + } + + /// Issue the device certificate of an approved request. The code must match. + fn approve_device(&self, rid: &str, code: &str, now: u64) -> Result { + let int = self + .intermediate()? + .ok_or(PkiFail::Code("pki.no_intermediate"))?; + let _g = self.guard()?; + let mut rs = self.requests()?; + let r = rs + .iter_mut() + .find(|r| r.id == rid && r.kind == "device") + .ok_or(PkiFail::Code("pki.request_not_found"))?; + if r.state != "waiting" || r.expires_at <= now { + return Err(PkiFail::Code("pki.request_closed")); + } + if normalise_code(code) != normalise_code(&r.match_code) { + return Err(PkiFail::Code("pki.wrong_code")); + } + let name = r.name.clone().unwrap_or_default(); + let kind = r.device_kind.clone().unwrap_or_else(|| "app".into()); + let leaf = match pki::issue_device(&int, &name, now as i64) { + Ok(l) => l, + Err(e) => { + r.state = "failed".into(); + r.error = Some(e.to_string()); + self.save_requests(&rs)?; + return Err(e.into()); + } + }; + let did = id("dv_")?; + write_atomic( + &self.dir.join(format!("devices/{did}.key")), + self.seal(&leaf.key)?.as_bytes(), + 0o600, + ) + .map_err(io)?; + let d = Device { + id: did.clone(), + name, + kind, + serial: leaf.serial_hex.clone(), + sha256: leaf.sha256_hex.clone(), + cert_pem: leaf.cert_pem.clone(), + created_at: now, + not_after: leaf.not_after, + revoked_at: None, + issuer_sha256: int.info().sha256_hex.clone(), + }; + let mut ds = self.devices()?; + ds.push(d.clone()); + // Keep the list bounded: forget the oldest revoked or expired ones first. + while ds.len() > MAX_DEVICES { + match ds.iter().position(|x| x.state(now) != "valid") { + Some(i) => { + let gone = ds.remove(i); + let _ = remove_if_exists(&self.dir.join(format!("devices/{}.key", gone.id))); + } + None => break, + } + } + self.save_devices(&ds)?; + r.state = "approved".into(); + r.approved_at = Some(now); + r.device_id = Some(did); + self.save_requests(&rs)?; + Ok(d) + } + + pub fn revoke(&self, device_id: &str, now: u64) -> Result, PkiFail> { + let _g = self.guard()?; + let mut ds = self.devices()?; + let Some(d) = ds.iter_mut().find(|d| d.id == device_id) else { + return Ok(None); + }; + if d.revoked_at.is_none() { + d.revoked_at = Some(now); + } + let out = d.clone(); + self.save_devices(&ds)?; + // The key is no longer needed: no new install file for a revoked device. + remove_if_exists(&self.dir.join(format!("devices/{device_id}.key"))).map_err(io)?; + if let Ok(mut b) = self.bundles.lock() { + b.retain(|_, x| x.device_id != device_id); + } + Ok(Some(out)) + } + + // -------------------------------------------------------------- install files + + /// A one-time install link for a device: `(token, password, expires_at)`. + pub fn make_bundle(&self, device_id: &str, now: u64) -> Result<(String, String, u64), PkiFail> { + let d = self + .devices()? + .into_iter() + .find(|d| d.id == device_id) + .ok_or(PkiFail::Code("pki.device_not_found"))?; + if d.state(now) != "valid" { + return Err(PkiFail::Code("pki.device_not_valid")); + } + if !self.dir.join(format!("devices/{device_id}.key")).exists() { + return Err(PkiFail::Code("pki.device_not_valid")); + } + let token = hex(&random::<32>().map_err(io)?); + let password = bundle_password()?; + let expires_at = now + BUNDLE_SECS; + let mut b = self.bundles.lock().map_err(|_| io("bundles"))?; + b.retain(|_, x| x.expires_at > now); + // One open link per device: a new one replaces the old. + b.retain(|_, x| x.device_id != device_id); + if b.len() >= 100 { + return Err(PkiFail::Code("pki.too_many_requests")); + } + b.insert( + token.clone(), + Bundle { + device_id: device_id.to_owned(), + password: password.clone(), + expires_at, + }, + ); + Ok((token, password, expires_at)) + } + + /// Hand out an install file once: the PKCS#12 bytes and the device name. The token is + /// gone afterwards, whatever happens. + pub fn take_bundle(&self, token: &str, now: u64) -> Result<(Vec, String), PkiFail> { + let b = { + let mut m = self.bundles.lock().map_err(|_| io("bundles"))?; + m.remove(token) + }; + let b = b.ok_or(PkiFail::Code("pki.bundle_used"))?; + if b.expires_at <= now { + return Err(PkiFail::Code("pki.bundle_used")); + } + let d = self + .devices()? + .into_iter() + .find(|d| d.id == b.device_id && d.state(now) == "valid") + .ok_or(PkiFail::Code("pki.device_not_valid"))?; + let key = self.open_key(&self.dir.join(format!("devices/{}.key", d.id)))?; + let issuer = if self + .intermediate_info() + .is_some_and(|i| i.sha256_hex == d.issuer_sha256) + { + std::fs::read_to_string(self.dir.join("intermediate.crt")).map_err(io)? + } else { + std::fs::read_to_string(self.dir.join("previous.crt")).map_err(io)? + }; + let p12 = pkcs12(&d, &key, &issuer, &self.root_pem, &b.password)?; + Ok((p12, d.name)) + } +} + +/// A PKCS#12 file with the device key and its chain (leaf, intermediate, root), encrypted +/// with AES-256 (PBES2) and a SHA-256 MAC. +fn pkcs12( + d: &Device, + key: &pki::KeyPair, + issuer_pem: &str, + root_pem: &str, + password: &str, +) -> Result, PkiFail> { + use p12_keystore::{ + Certificate, EncryptionAlgorithm, KeyStore, KeyStoreEntry, MacAlgorithm, PrivateKey, + PrivateKeyChain, + }; + let mut certs = Vec::new(); + for pem in [d.cert_pem.as_str(), issuer_pem, root_pem] { + for der in pki::chain_der(pem)? { + certs.push(Certificate::from_der(&der).map_err(io)?); + } + } + let local_id = ring::digest::digest(&ring::digest::SHA256, d.cert_pem.as_bytes()); + let chain = PrivateKeyChain::new( + &local_id.as_ref()[..20], + PrivateKey::from_der(&key.serialize_der()).map_err(io)?, + certs, + ); + let mut ks = KeyStore::new(); + ks.add_entry(&d.name, KeyStoreEntry::PrivateKeyChain(chain)); + ks.writer(password) + .encryption_algorithm(EncryptionAlgorithm::PbeWithHmacSha256AndAes256) + .encryption_iterations(10_000) + .mac_algorithm(MacAlgorithm::HmacSha256) + .mac_iterations(10_000) + .write() + .map_err(io) +} + +/// A QR code (SVG) for a URL, for the install dialog. +pub fn qr_svg(data: &str) -> Result { + let code = qrcode::QrCode::with_error_correction_level(data, qrcode::EcLevel::M).map_err(io)?; + Ok(code + .render::>() + .min_dimensions(240, 240) + .quiet_zone(true) + .build()) +} + +/// Forget closed requests beyond the newest 200. +fn prune(rs: &mut Vec, _now: u64) { + let closed = rs.iter().filter(|r| r.state != "waiting").count(); + if closed > 200 { + let mut drop = closed - 200; + rs.retain(|r| { + if drop > 0 && r.state != "waiting" { + drop -= 1; + false + } else { + true + } + }); + } +} + +fn ymd(unix: u64) -> (i64, u32, u32) { + // Reuse core's calendar via its RFC 3339 text. + let s = ianitor_core::time::rfc3339(unix); + let y = s.get(0..4).and_then(|v| v.parse().ok()).unwrap_or(1970); + let m = s.get(5..7).and_then(|v| v.parse().ok()).unwrap_or(1); + let d = s.get(8..10).and_then(|v| v.parse().ok()).unwrap_or(1); + (y, m, d) +} + +// ------------------------------------------------------------------ the manual approval CLI + +/// `ianitor-control pki approve `: write an approval for the open device request with +/// this code. Run on the server by Mark, as the user control runs as. +pub fn cli_approve(state_dir: &Path, code: &str, deny: bool, now: u64) -> Result { + let dir = state_dir.join("pki"); + let rs: Vec = read_json(&dir.join("requests.json"))?.unwrap_or_default(); + let want = normalise_code(code); + if want.len() != 6 { + return Err("the code has six digits, like 47 19 83".into()); + } + let r = rs + .into_iter() + .find(|r| { + r.kind == "device" + && r.state == "waiting" + && r.expires_at > now + && normalise_code(&r.match_code) == want + }) + .ok_or("no open device request has this code (it may have expired)")?; + let file = dir.join("approvals").join(format!( + "{}.{}", + r.id, + if deny { "deny" } else { "approve" } + )); + write_atomic(&file, want.as_bytes(), 0o600).map_err(|e| e.to_string())?; + Ok(r) +} + +/// `ianitor-control pki install `: hand a signed intermediate to the open renewal +/// whose key it carries. +pub fn cli_install(state_dir: &Path, cert_pem: &str, now: u64) -> Result { + let dir = state_dir.join("pki"); + let rs: Vec = read_json(&dir.join("requests.json"))?.unwrap_or_default(); + let spki = pki::public_key_der(cert_pem).map_err(|e| e.to_string())?; + let r = rs + .into_iter() + .find(|r| { + r.kind == "intermediate" + && r.state == "waiting" + && r.expires_at > now + && r + .csr_pem + .as_deref() + .and_then(|c| pki::csr_public_key_der(c).ok()) + .is_some_and(|k| k == spki) + }) + .ok_or("no open renewal matches this certificate's key (was it signed from the current request?)")?; + let file = dir.join("approvals").join(format!("{}.crt", r.id)); + write_atomic(&file, cert_pem.as_bytes(), 0o600).map_err(|e| e.to_string())?; + Ok(r) +} + +pub fn requests_path(state_dir: &Path) -> PathBuf { + state_dir.join("pki/requests.json") +} diff --git a/crates/control/src/pki_ctl.rs b/crates/control/src/pki_ctl.rs new file mode 100644 index 0000000..d4ec263 --- /dev/null +++ b/crates/control/src/pki_ctl.rs @@ -0,0 +1,207 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied, +//! the device files both engines read, and what happens after an approval, a renewal or a +//! revocation. + +// A refusal is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use ianitor_core::TlsMode; + +use crate::engine::{Control, Fail}; +use crate::messages::{self, Params}; +use crate::pki::PkiFail; +use crate::util::now; + +/// The HTTP status for a PKI refusal. +pub fn status_of(code: &str) -> u16 { + match code { + "pki.request_not_found" | "pki.device_not_found" => 404, + "pki.bundle_used" => 410, + "pki.bad_certificate" + | "pki.not_our_root" + | "pki.wrong_key" + | "pki.device_name" + | "pki.device_kind" + | "pki.wrong_code" => 422, + "pki.too_many_requests" => 429, + _ => 409, + } +} + +pub fn pki_fail(e: PkiFail) -> Fail { + match e { + PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()), + PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d), + } +} + +impl Control { + pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> { + self.pki + .as_ref() + .ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new())) + } + + /// Every certificate directory a compiler output points at. + fn cert_dirs(&self) -> Vec<&Path> { + let mut v = vec![Path::new(&self.cfg.compile.cert_dir)]; + let c = Path::new(&self.cfg.caddy_compile().cert_dir); + if c != v[0] { + v.push(c); + } + v + } + + /// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the + /// device files when a host needs them. Without `[pki]` nothing is issued (the files are + /// expected to be there, as in phase 2). Returns whether a file changed. + pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result { + let Some(p) = &self.pki else { + return Ok(false); + }; + let t = now(); + let domi: Vec = model + .hosts() + .iter() + .filter(|h| h.tls == TlsMode::Domi) + .map(|h| h.hostname.to_string()) + .collect(); + let devices = model.hosts().iter().any(|h| h.device_certs); + let mut changed = false; + for dir in self.cert_dirs() { + let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| { + let mut f = pki_fail(e); + // The apply's reason names a host so the UI can point at it. + if let Some(h) = domi.first() { + f.reason.hostname = Some(h.clone()); + } + f + })?; + if !issued.is_empty() { + log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", ")); + changed = true; + } + if devices || dir.join(ianitor_core::compile::DEVICE_CA_FILE).exists() { + changed |= p.write_device_files(dir, t).map_err(pki_fail)?; + } + } + Ok(changed) + } + + /// Every couple of seconds: act on approvals; once an hour: renew server certificates. + pub async fn pki_poller(self: Arc) { + if self.pki.is_none() { + return; + } + let mut last_renewal_check = now(); + loop { + tokio::time::sleep(Duration::from_secs(2)).await; + let me = self.clone(); + let polled = tokio::task::spawn_blocking(move || match &me.pki { + Some(p) => p.poll(now()), + None => Ok(Default::default()), + }) + .await; + let changes = match polled { + Ok(Ok(c)) => c, + Ok(Err(e)) => { + log::error!(target: "ianitor::pki", "{e}"); + continue; + } + Err(e) => { + log::error!(target: "ianitor::pki", "pki poll crashed: {e}"); + continue; + } + }; + let t = now(); + if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 { + last_renewal_check = t; + self.refresh_certificates(changes.intermediate).await; + } + if changes.devices { + self.devices_changed().await; + } + } + } + + /// Issue what the current tree needs (after a new intermediate: everything) and reload + /// the engine that serves, under the apply lock so no trial is running. + pub async fn refresh_certificates(&self, new_intermediate: bool) { + let _lock = self.apply_lock.lock().await; + let Ok((_, _, model)) = self.head_model() else { + return; + }; + match self.pki_prepare(&model) { + Ok(changed) if changed || new_intermediate => { + if new_intermediate { + log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued"); + } + self.reload_serving_engine().await; + } + Ok(_) => {} + Err(f) => { + log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message); + } + } + } + + /// The device files changed (issue or revoke): rewrite them and tell the engine at once. + pub async fn devices_changed(&self) { + let Some(p) = &self.pki else { return }; + let t = now(); + let mut changed = false; + for dir in self.cert_dirs() { + match p.write_device_files(dir, t) { + Ok(c) => changed |= c, + Err(e) => log::error!(target: "ianitor::pki", "device files not written: {e}"), + } + } + if !changed { + return; + } + if self.engine_running() == "caddy" { + // Caddy reads the allow list when it starts: restart it so a revocation counts. + if let Err(e) = self.restart_caddy().await { + log::error!(target: "ianitor::pki", "caddy-fallback not restarted after a device change: {e}"); + } + } else if self.edge.attached() + && let Err(e) = self.edge.reload_devices().await + { + log::error!(target: "ianitor::pki", "edge did not re-read the device certificates: {e}"); + } + } + + async fn reload_serving_engine(&self) { + if self.engine_running() == "caddy" { + if let Err(e) = self.restart_caddy().await { + log::error!(target: "ianitor::pki", "caddy-fallback not restarted: {e}"); + } + } else if self.edge.attached() + && let Err(e) = self.edge.reload().await + { + log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}"); + } + } + + /// The code and message for a PKI request that waits for its approval. + pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) { + let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual"); + let c = match (kind, manual) { + ("intermediate", _) => "pki.renew.manual", + (_, true) => "pki.waiting.manual", + (_, false) => "pki.waiting", + }; + ( + c.to_owned(), + messages::message(c, &messages::params([("code", code.to_owned())])), + ) + } +} diff --git a/crates/control/src/switch.rs b/crates/control/src/switch.rs new file mode 100644 index 0000000..5bd6e15 --- /dev/null +++ b/crates/control/src/switch.rs @@ -0,0 +1,400 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4). +//! +//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start, +//! stop and restart only those two, through a polkit rule scoped to exactly them (NixOS +//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit +//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the +//! target), stops the old engine, starts the new one and waits until it serves; if the new +//! one does not come up, it goes back to the old one and says so. +//! +//! Decisions (phase 3): +//! - While Caddy serves, changes are paused (`engine.caddy`): Caddy is the emergency +//! fallback, and the apply pipeline's trial, watch and revert are built on edge's admin +//! socket. Changes made then would also have no differential check. +//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md): +//! Caddy cannot check them, and control never serves visitors itself. +//! - Device revocations while Caddy serves restart caddy-fallback (Caddy reads the allow +//! list when it starts); this is why the polkit rule also allows `restart`. +//! +//! The systemd calls go through [`Units`], so tests use a fake. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::config::EngineConfig; +use crate::engine::{Control, Fail, reason}; +use crate::messages::{self, Params}; +use crate::records::Reason; +use crate::util::{now, write_atomic}; + +/// Start, stop and look at systemd units. +pub trait Units: Send + Sync { + fn start(&self, unit: &str) -> Result<(), String>; + fn stop(&self, unit: &str) -> Result<(), String>; + fn restart(&self, unit: &str) -> Result<(), String>; + fn is_active(&self, unit: &str) -> Result; +} + +/// `systemctl --no-ask-password `, as the control user (polkit decides). +pub struct Systemctl { + pub bin: PathBuf, +} + +impl Systemctl { + fn run(&self, args: &[&str]) -> Result { + std::process::Command::new(&self.bin) + .arg("--no-ask-password") + .args(args) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|e| format!("cannot run {}: {e}", self.bin.display())) + } + + fn verb(&self, verb: &str, unit: &str) -> Result<(), String> { + let o = self.run(&[verb, unit])?; + if o.status.success() { + Ok(()) + } else { + Err(format!( + "systemctl {verb} {unit} failed: {}", + String::from_utf8_lossy(&o.stderr).trim() + )) + } + } +} + +impl Units for Systemctl { + fn start(&self, unit: &str) -> Result<(), String> { + self.verb("start", unit) + } + fn stop(&self, unit: &str) -> Result<(), String> { + self.verb("stop", unit) + } + fn restart(&self, unit: &str) -> Result<(), String> { + self.verb("restart", unit) + } + fn is_active(&self, unit: &str) -> Result { + Ok(self.run(&["is-active", "--quiet", unit])?.status.success()) + } +} + +/// In-memory units for tests: records every call; `fail_start` makes a start fail. +#[derive(Default)] +pub struct FakeUnits { + pub calls: Mutex>, + pub active: Mutex>, + pub fail_start: Mutex>, +} + +impl Units for FakeUnits { + fn start(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("start {unit}")); + } + if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) { + return Err(format!("{unit} failed to start")); + } + if let Ok(mut a) = self.active.lock() { + a.insert(unit.to_owned()); + } + Ok(()) + } + fn stop(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("stop {unit}")); + } + if let Ok(mut a) = self.active.lock() { + a.remove(unit); + } + Ok(()) + } + fn restart(&self, unit: &str) -> Result<(), String> { + if let Ok(mut c) = self.calls.lock() { + c.push(format!("restart {unit}")); + } + Ok(()) + } + fn is_active(&self, unit: &str) -> Result { + Ok(self.active.lock().is_ok_and(|a| a.contains(unit))) + } +} + +/// Which engine serves, as control knows it. +#[derive(Debug, Clone)] +pub struct EngineState { + /// `pingora` or `caddy`. + pub running: String, + /// `running`, `switching` or `stopped`. + pub state: String, + pub since: u64, + /// The target while switching. + pub target: Option, + /// Why the last switch did not happen. + pub last_error: Option, +} + +pub fn read_engine_file(p: &Path) -> String { + match std::fs::read_to_string(p) { + Ok(s) if s.trim() == "caddy" => "caddy".into(), + _ => "pingora".into(), + } +} + +pub fn engine_name(e: &str) -> String { + if e == "caddy" { "Caddy" } else { "Pingora" }.into() +} + +impl Control { + pub fn engine_cfg(&self) -> Option<&EngineConfig> { + self.cfg.engine.as_ref() + } + + /// `pingora` or `caddy`. + pub fn engine_running(&self) -> String { + self.engine + .lock() + .map(|e| e.running.clone()) + .unwrap_or_else(|_| "pingora".into()) + } + + pub fn engine_state(&self) -> EngineState { + self.engine + .lock() + .map(|e| e.clone()) + .unwrap_or(EngineState { + running: "pingora".into(), + state: "running".into(), + since: 0, + target: None, + last_error: None, + }) + } + + fn set_engine(&self, f: impl FnOnce(&mut EngineState)) { + if let Ok(mut e) = self.engine.lock() { + f(&mut e); + } + } + + pub async fn restart_caddy(&self) -> Result<(), String> { + let (Some(cfg), Some(units)) = (self.engine_cfg(), self.units.clone()) else { + return Err("no engine settings".into()); + }; + let unit = cfg.caddy_unit.clone(); + tokio::task::spawn_blocking(move || units.restart(&unit)) + .await + .map_err(|e| e.to_string())? + } + + /// Check a switch request and start it. Answers at once; the switch runs in the + /// background (`overview.engine.state` is `switching` until it ends). + pub fn request_switch(self: &Arc, target: &str) -> Result { + if self.engine_cfg().is_none() || self.units.is_none() { + return Err(Fail::new(409, "engine.unmanaged", Params::new())); + } + if target != "pingora" && target != "caddy" { + return Err(Fail::new( + 422, + "request.body", + messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]), + )); + } + { + let mut e = self + .engine + .lock() + .map_err(|_| Fail::new(500, "internal", Params::new()))?; + if e.state == "switching" { + return Err(Fail::new(409, "engine.switching", Params::new())); + } + if e.running == target { + return Err(Fail::new( + 409, + "engine.same", + messages::params([("engine", engine_name(target))]), + )); + } + e.state = "switching".into(); + e.target = Some(target.to_owned()); + e.last_error = None; + } + let me = self.clone(); + let t = target.to_owned(); + tokio::spawn(async move { me.switch(&t).await }); + Ok(self.engine_state()) + } + + async fn switch(self: Arc, target: &str) { + // No apply runs during a switch, and none starts. + let _lock = self.apply_lock.lock().await; + let from = self.engine_running(); + let res = self.switch_inner(&from, target).await; + let t = now(); + match res { + Ok(()) => { + log::info!(target: "ianitor::engine", "switched from {from} to {target}"); + self.set_engine(|e| { + e.running = target.to_owned(); + e.state = "running".into(); + e.since = t; + e.target = None; + }); + } + Err(detail) => { + log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}"); + // Go back to what served before. + let back = self.bring_back(&from).await; + let mut r = reason( + "engine.switch_failed", + messages::params([ + ("engine", engine_name(target)), + ("previous", engine_name(&from)), + ]), + ); + r.detail = Some(match back { + Ok(()) => detail, + Err(b) => format!("{detail}; going back also failed: {b}"), + }); + self.set_engine(|e| { + e.running = from.clone(); + e.state = "running".into(); + e.target = None; + e.last_error = Some(r); + }); + } + } + } + + fn units_and_cfg(&self) -> Result<(Arc, EngineConfig), String> { + match (self.units.clone(), self.engine_cfg().cloned()) { + (Some(u), Some(c)) => Ok((u, c)), + _ => Err("no engine settings".into()), + } + } + + fn unit_of(cfg: &EngineConfig, engine: &str) -> String { + if engine == "caddy" { + cfg.caddy_unit.clone() + } else { + cfg.edge_unit.clone() + } + } + + async fn blocking( + f: impl FnOnce() -> Result + Send + 'static, + ) -> Result { + tokio::task::spawn_blocking(f) + .await + .map_err(|e| e.to_string())? + } + + async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> { + let (units, cfg) = self.units_and_cfg()?; + if target == "caddy" { + // Caddy starts from caddy.json: make sure it is the current tree's. + self.write_current_caddy()?; + } + write_atomic(&cfg.file, target.as_bytes(), 0o644) + .map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?; + let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target)); + let u = units.clone(); + Self::blocking(move || u.stop(&old)).await?; + let u = units.clone(); + let n = new.clone(); + Self::blocking(move || u.start(&n)).await?; + self.wait_serving(target, &units, &new).await + } + + async fn bring_back(&self, engine: &str) -> Result<(), String> { + let (units, cfg) = self.units_and_cfg()?; + let other = if engine == "caddy" { + "pingora" + } else { + "caddy" + }; + write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?; + let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine)); + let u = units.clone(); + let _ = Self::blocking(move || u.stop(&stop)).await; + let u = units.clone(); + let s = start.clone(); + Self::blocking(move || u.start(&s)).await?; + self.wait_serving(engine, &units, &start).await + } + + /// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts + /// connections on the HTTPS address. + async fn wait_serving( + &self, + engine: &str, + units: &Arc, + unit: &str, + ) -> Result<(), String> { + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + let addr = if engine == "caddy" { + self.cfg.caddy_compile().https_listen + } else { + self.cfg.compile.https_listen + }; + loop { + let u = units.clone(); + let n = unit.to_owned(); + let active = Self::blocking(move || u.is_active(&n)) + .await + .unwrap_or(false); + let serving = active + && if engine == "pingora" && self.edge.attached() { + self.edge.status().await.is_ok() + } else { + tokio::net::TcpStream::connect(addr).await.is_ok() + }; + if serving { + return Ok(()); + } + if tokio::time::Instant::now() > deadline { + return Err(format!("{unit} did not come up within 20 s")); + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + + /// Compile the current tree for Caddy and write caddy.json (the file only ever holds a + /// kept tree, so this only matters when it is missing or older). + fn write_current_caddy(&self) -> Result<(), String> { + let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?; + self.pki_prepare(&model).map_err(|f| f.reason.message)?; + let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options()) + .map_err(|e| e.to_string())?; + if std::fs::read_to_string(&self.cfg.caddy.config) + .ok() + .as_deref() + != Some(text.as_str()) + { + write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + } + Ok(()) + } + + /// Changes wait while Caddy serves. + pub fn engine_pause(&self) -> Option { + (self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new())) + } +} + +/// What control.toml's `[engine]` asks for. +pub fn units_for(cfg: Option<&EngineConfig>) -> Option> { + let c = cfg?; + match c.units.as_str() { + "systemctl" => Some(Arc::new(Systemctl { + bin: c.systemctl.clone(), + })), + _ => None, + } +} diff --git a/crates/control/tests/common/mod.rs b/crates/control/tests/common/mod.rs index 7e5d1a9..aea097f 100644 --- a/crates/control/tests/common/mod.rs +++ b/crates/control/tests/common/mod.rs @@ -66,6 +66,8 @@ pub struct EnvSpec { pub watch_secs: u64, pub site: String, pub remote: Option, + /// Appended to control.toml (extra sections such as [pki]). + pub extra_config: String, } impl Default for EnvSpec { @@ -74,6 +76,7 @@ impl Default for EnvSpec { watch_secs: 2, site: String::new(), remote: None, + extra_config: String::new(), } } } @@ -202,7 +205,7 @@ caddy_credentials_dir = "{creds}" certs = d("certs"), edge_state = d("edge-state"), log = d("logs/access.log"), - ); + ) + &spec.extra_config; std::fs::write(self.dir.join("control.toml"), text).unwrap(); } @@ -254,7 +257,7 @@ caddy_credentials_dir = "{creds}" std::thread::sleep(Duration::from_millis(200)); } - fn command(&self) -> Command { + pub fn command(&self) -> Command { let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control")); c.env_remove("IANITOR_TEST_CRASH_AT"); c.env_remove("IANITOR_TEST_FAIL_WRITE"); diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs new file mode 100644 index 0000000..9e14f54 --- /dev/null +++ b/crates/control/tests/pki.rs @@ -0,0 +1,421 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is +//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server +//! certificates that chain to the root; device certificates need the match code; the install +//! file works once; revocation takes the device off the allow list; no root key file is ever +//! in the state directory, and control refuses to start with one there. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux; run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::path::Path; + use std::time::{Duration, Instant}; + + use crate::common::{Env, EnvSpec}; + use ianitor_core::pki; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + use serde_json::{Value, json}; + + const PASSWORD: &str = "intermediate-test-password-123"; + + fn now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 + } + + /// The offline side: a root that lives only in this test's memory (and its cert file). + struct Offline { + root_pem: String, + root_key: pki::KeyPair, + } + + async fn env_with_pki() -> (Env, Offline) { + let (root_pem, root_key) = pki::create_root(now()).unwrap(); + // Only the root certificate goes next to control; the key stays in this test. + let extra = |dir: &Path| { + format!( + "\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n", + dir.join("offline-root.crt").display() + ) + }; + let mut env = Env::new(EnvSpec::default()).await; + std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap(); + std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join(".")); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + (env, Offline { root_pem, root_key }) + } + + async fn wait_request(env: &Env, id: &str, want: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let r = env + .call("GET", &format!("/api/v1/pki-requests/{id}"), None) + .await; + assert_eq!(r.status, 200, "{}", r.text); + if r.json["state"] == want { + return r.json; + } + if Instant::now() > deadline { + panic!( + "request {id} is {} not {want}\n{}", + r.json["state"], + env.control_log() + ); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + + fn cli(env: &Env, args: &[&str]) -> std::process::Output { + env.command() + .args(args) + .arg("--config") + .arg(env.config_path()) + .output() + .unwrap() + } + + /// Renew (first intermediate), sign offline, install with the CLI. + async fn install_intermediate(env: &Env, off: &Offline) -> Value { + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); + // The code the UI shows is the one the offline signer computes from the CSR. + assert_eq!( + r.json["match_code"].as_str().unwrap(), + pki::match_code(&pki::csr_der(&csr).unwrap()) + ); + let r2 = env + .call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None) + .await; + assert_eq!(r2.status, 200); + assert_eq!(r2.text, csr); + let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); + let f = env.dir.join("signed.crt"); + std::fs::write(&f, &signed).unwrap(); + let out = cli(env, &["pki", "install", f.to_str().unwrap()]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + wait_request(env, &rid, "approved").await + } + + #[tokio::test(flavor = "multi_thread")] + async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() { + let (env, off) = env_with_pki().await; + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text); + + // Before an intermediate exists a domi host cannot get a certificate. + let echo = Echo::start("domi").await; + let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await; + assert_eq!(rec["state"], "failed", "{rec}"); + assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}"); + + install_intermediate(&env, &off).await; + let ov = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text); + assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364); + + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); + // The served certificate chains to the Domi root (only the root is trusted here). + let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem); + let edge = env.edge.as_ref().unwrap(); + let r = client::https( + edge.https, + "fresh.test", + roots, + &Req::get("fresh.test", "/"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); + let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap(); + let info = pki::inspect(&crt).unwrap(); + assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]); + assert_eq!( + (info.not_after - now()) / 86_400, + i64::from(pki::SERVER_DAYS) - 1 + ); + + // No root key anywhere control writes. + let key_pem = off.root_key.serialize_pem(); + let body: String = key_pem + .lines() + .filter(|l| !l.starts_with("-----")) + .collect(); + for d in ["state", "certs", "edge", "caddy", "edge-state"] { + for f in walk(&env.dir.join(d)) { + let bytes = std::fs::read(&f).unwrap(); + let text = String::from_utf8_lossy(&bytes); + assert!( + !text.contains(&body[..40]), + "root key material in {}", + f.display() + ); + assert!( + !contains(&bytes, &off.root_key.serialize_der()), + "root key DER in {}", + f.display() + ); + } + } + // The intermediate key is only stored encrypted. + let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap(); + assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY"))); + assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY"))); + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_wrong_certificate_is_not_installed() { + let (env, off) = env_with_pki().await; + let r = env + .call( + "POST", + "/api/v1/certs/intermediate/renewal", + Some(json!({})), + ) + .await; + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); + // Signed by another root. + let (other, other_key) = pki::create_root(now()).unwrap(); + let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": wrong})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "pki.not_our_root"); + // For another key. + let k = pki::generate_key().unwrap(); + let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); + let wrong = + pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": wrong})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "pki.wrong_key"); + // A leaf is not an intermediate. + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": "garbage"})), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + let st = env + .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) + .await; + assert_eq!(st.json["state"], "waiting"); + // The right one through the API works too. + let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); + let r = env + .call( + "PUT", + &format!("/api/v1/pki-requests/{rid}/certificate"), + Some(json!({"certificate_pem": good})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["state"], "approved"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn device_certificate_needs_the_match_code_and_installs_once() { + let (env, off) = env_with_pki().await; + install_intermediate(&env, &off).await; + let r = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "Mark's phone", "kind": "phone"})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let rid = r.json["request_id"].as_str().unwrap().to_owned(); + let code = r.json["match_code"].as_str().unwrap().to_owned(); + assert_eq!(code.len(), 8, "{code}"); + // The same name again while it waits: refused. + let again = env + .call( + "POST", + "/api/v1/certs/devices", + Some(json!({"name": "mark's PHONE", "kind": "phone"})), + ) + .await; + assert_eq!(again.status, 409, "{}", again.text); + assert_eq!(again.json["error"]["code"], "pki.device_name_taken"); + + // A wrong code does nothing. + let wrong = if code.starts_with('0') { + "11 11 11" + } else { + "00 00 00" + }; + let out = cli(&env, &["pki", "approve", wrong]); + assert!(!out.status.success()); + tokio::time::sleep(Duration::from_millis(2500)).await; + let st = env + .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) + .await; + assert_eq!(st.json["state"], "waiting"); + + let out = cli(&env, &["pki", "approve", &code]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let done = wait_request(&env, &rid, "approved").await; + let did = done["device_id"].as_str().unwrap().to_owned(); + + let certs = env.call("GET", "/api/v1/certs", None).await; + assert_eq!(certs.status, 200, "{}", certs.text); + assert_eq!(certs.json["root"]["offline"], true); + let dev = certs.json["devices"] + .as_array() + .unwrap() + .iter() + .find(|d| d["id"] == did.as_str()) + .unwrap() + .clone(); + assert_eq!(dev["state"], "valid"); + assert_eq!(dev["name"], "Mark's phone"); + + // The allow list both engines read has it. + let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); + assert!(allow.contains("BEGIN CERTIFICATE")); + + // One-time install file. + let b = env + .call( + "POST", + &format!("/api/v1/certs/devices/{did}/bundle"), + Some(json!({"format": "qr"})), + ) + .await; + assert_eq!(b.status, 200, "{}", b.text); + let url = b.json["download_url"].as_str().unwrap().to_owned(); + let password = b.json["one_time_password"].as_str().unwrap().to_owned(); + assert!(b.json["qr_svg"].as_str().unwrap().starts_with(" Vec { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { + continue; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else { + out.push(p); + } + } + } + out + } + + fn contains(hay: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) + } +} diff --git a/crates/control/tests/ui_auth.rs b/crates/control/tests/ui_auth.rs new file mode 100644 index 0000000..d003fb3 --- /dev/null +++ b/crates/control/tests/ui_auth.rs @@ -0,0 +1,194 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Sign-in for the web UI (G14, tests first). The UI reaches control through edge on the +//! admin host, behind Authelia; edge adds a per-boot secret header (`X-Ianitor-Proof`, from a +//! systemd credential only edge and control can read). Control trusts `Remote-User` only on a +//! request that carries that proof: any local process can send `Remote-User` to loopback, but +//! none can send the proof. API tokens keep working for scripts. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux; run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use crate::common::{Env, EnvSpec}; + use ianitor_testkit::authelia::MockAuthelia; + use ianitor_testkit::client::{self, Req}; + use serde_json::json; + + const PROOF: &str = "per-boot-proof-0123456789abcdef0123456789abcdef"; + + async fn env(site: String) -> Env { + env_for(site, "ui.test").await + } + + async fn env_for(site: String, ui_host: &str) -> Env { + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + std::fs::write(env.dir.join("creds/ui-proof"), format!("{PROOF}\n")).unwrap(); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!("\n[ui]\nhostname = \"{ui_host}\"\nproof_credential = \"ui-proof\"\n"); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + env + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_forged_remote_user_without_the_proof_gets_401() { + let env = env(String::new()).await; + for headers in [ + vec![("Remote-User", "mark")], + vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")], + vec![("Remote-User", "mark"), ("X-Ianitor-Proof", "")], + vec![("remote-user", "mark"), ("Remote-Groups", "admins")], + ] { + let r = env + .call_with("GET", "/api/v1/overview", &headers, None) + .await; + assert_eq!(r.status, 401, "{headers:?}: {}", r.text); + assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text); + } + // A valid API token does not make a forged identity acceptable either. + let auth = format!("Bearer {}", env.token); + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("Authorization", &auth), ("Remote-User", "mark")], + None, + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + // Nothing was trusted: the log does not show the forged user as an actor. + assert!(!env.control_log().contains("by mark")); + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_proof_with_a_remote_user_signs_the_ui_in() { + let env = env(String::new()).await; + let ok = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)]; + let r = env.call_with("GET", "/api/v1/overview", &ok, None).await; + assert_eq!(r.status, 200, "{}", r.text); + // Through edge the Host is the admin host's. + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[ + ("Remote-User", "mark"), + ("X-Ianitor-Proof", PROOF), + ("Host", "ui.test"), + ], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + // Writes need the UI header (CSRF), browser or not. + let r = env + .call_with( + "POST", + "/api/v1/tokens", + &ok, + Some(json!({"name": "from ui"})), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let mut w = ok.to_vec(); + w.push(("X-Ianitor-UI", "1")); + let r = env + .call_with( + "POST", + "/api/v1/tokens", + &w, + Some(json!({"name": "from ui"})), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + // The proof without a user is not a sign-in. + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("X-Ianitor-Proof", PROOF)], + None, + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + assert_eq!(r.json["error"]["code"], "ui.no_user"); + // API tokens still work for scripts. + let r = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(r.status, 200, "{}", r.text); + } + + #[tokio::test(flavor = "multi_thread")] + async fn through_edge_authelia_decides_and_a_client_cannot_bring_its_own_proof() { + let auth = MockAuthelia::start().await; + let site = format!( + "secrets = [\"ui-proof\"]\n[forward_auth]\nurl = \"{}\"\n", + auth.url() + ); + let env = env_for(site, "a.test").await; + // The admin host: forward-auth, upstream control, the proof header from the secret. + let host = json!({"host": { + "hostname": "a.test", "upstreams": [format!("http://{}", env.api)], + "tls": "domi", "auth": "forward-auth", + "request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}] + }}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); + let edge = env.edge.as_ref().unwrap(); + let roots = env.ca.roots(); + // Signed in at Authelia (mock: alice): the UI gets in. + let r = client::https( + edge.https, + "a.test", + roots.clone(), + &Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", r.text()); + assert!(r.text().contains("\"hosts\""), "{}", r.text()); + // Not signed in: Authelia's answer, control never sees it. + let r = client::https( + edge.https, + "a.test", + roots.clone(), + &Req::get("a.test", "/api/v1/overview"), + ) + .await + .unwrap(); + assert_ne!(r.status, 200); + // A client that sends its own proof and user gets neither through: edge replaces + // the proof with the real one only after Authelia allowed the request, and strips + // Remote-* from clients. + let r = client::https( + edge.https, + "a.test", + roots, + &Req::get("a.test", "/api/v1/overview") + .header("x-ianitor-proof", "guess") + .header("remote-user", "mallory"), + ) + .await + .unwrap(); + assert_ne!(r.status, 200); + } +} diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs index f9f04e1..e7ff8d8 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -566,6 +566,15 @@ pub fn match_code(request: &[u8]) -> String { ) } +/// SubjectPublicKeyInfo DER of a CSR (to match a signed certificate to its request). +pub fn csr_public_key_der(csr_pem: &str) -> Result, PkiError> { + use x509_parser::prelude::FromDer; + let der = csr_der(csr_pem)?; + let (_, csr) = x509_parser::certification_request::X509CertificationRequest::from_der(&der) + .map_err(|_| PkiError::BadCsr)?; + Ok(csr.certification_request_info.subject_pki.raw.to_vec()) +} + /// DER of the first PEM block of a CSR (for the match code). pub fn csr_der(csr_pem: &str) -> Result, PkiError> { for p in x509_parser::pem::Pem::iter_from_buffer(csr_pem.as_bytes()) { diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs index 945ea38..44260bf 100644 --- a/tests/diff/tests/apply_sequence.rs +++ b/tests/diff/tests/apply_sequence.rs @@ -121,6 +121,9 @@ mod unix { }, compile: compile_of(&edge_opts), compile_caddy: Some(compile_of(&caddy_opts)), + pki: None, + ui: None, + engine: None, }; // Start from the site file and every host except three; then a sequence of applies diff --git a/tests/support/src/more.rs b/tests/support/src/more.rs index c0938ca..e680e17 100644 --- a/tests/support/src/more.rs +++ b/tests/support/src/more.rs @@ -179,6 +179,8 @@ pub struct JsonResp { pub headers: Vec<(String, String)>, pub json: serde_json::Value, pub text: String, + /// The raw body (for binary answers). + pub body: Vec, } impl JsonResp { @@ -197,6 +199,7 @@ fn json_resp(r: Resp) -> JsonResp { headers: r.headers, json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null), text, + body: r.body, } }