TLS: trust the host operating system's CA certificate store (#303) (#894)

Co-authored-by: Brad Hallett <53977268+bradhallett@users.noreply.github.com>
This commit is contained in:
Precious OkwuandBrad Hallett authored and GitHub committed 2026-11-24 16:21:03 +01:00
1 parent fecaed6b7a
commit 83bd3de037
27 files changed
+1729 -40

No files matched your search

Generated
+79 -6
View File
@@ -190,6 +190,22 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.3.1"
@@ -748,7 +764,6 @@ dependencies = [
"tar",
"ureq",
"webkit2gtk",
"webpki-roots",
]
[[package]]
@@ -757,11 +772,16 @@ version = "0.0.0"
dependencies = [
"rcgen",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"schannel",
"security-framework",
"serde",
"serde_json",
"sha2",
"tar",
"ureq",
"webpki-root-certs",
]
[[package]]
@@ -806,11 +826,15 @@ dependencies = [
"embed-resource",
"kiri-share-proto",
"libc",
"rcgen",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"schannel",
"serde",
"serde_json",
"sha2",
"webpki-roots",
"webpki-root-certs",
"webview2-com",
"windows",
"windows-sys 0.52.0",
@@ -1014,6 +1038,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "openssl-probe"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
[[package]]
name = "pango"
version = "0.18.3"
@@ -1215,6 +1245,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
@@ -1244,6 +1286,38 @@ dependencies = [
"twox-hash",
]
[[package]]
name = "schannel"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "semver"
version = "1.0.28"
@@ -1642,7 +1716,6 @@ dependencies = [
"rustls-pki-types",
"ureq-proto",
"utf8-zero",
"webpki-roots",
]
[[package]]
@@ -1746,10 +1819,10 @@ dependencies = [
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
name = "webpki-root-certs"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585"
dependencies = [
"rustls-pki-types",
]
+21 -1
View File
@@ -3292,6 +3292,8 @@ Used by:
- bitflags 2.13.2 (https://github.com/bitflags/bitflags)
- cc 1.10.0 (https://github.com/rust-lang/cc-rs)
- cfg-if 1.0.5 (https://github.com/rust-lang/cfg-if)
- core-foundation-sys 0.8.7 (https://github.com/servo/core-foundation-rs)
- core-foundation 0.10.1 (https://github.com/servo/core-foundation-rs)
- equivalent 1.0.3 (https://github.com/indexmap-rs/equivalent)
- errno 0.3.14 (https://github.com/lambda-fairy/rust-errno)
- filetime 0.2.29 (https://github.com/alexcrichton/filetime)
@@ -3305,13 +3307,17 @@ Used by:
- linux-raw-sys 0.12.1 (https://github.com/sunfishcode/linux-raw-sys)
- log 0.4.34 (https://github.com/rust-lang/log)
- once_cell 1.21.4 (https://github.com/matklad/once_cell)
- openssl-probe 0.2.2 (https://github.com/rustls/openssl-probe)
- percent-encoding 2.3.2 (https://github.com/servo/rust-url/)
- pkg-config 0.3.34 (https://github.com/rust-lang/pkg-config-rs)
- regex-lite 0.1.9 (https://github.com/rust-lang/regex)
- ring 0.17.14 (https://github.com/briansmith/ring)
- rustc_version 0.4.1 (https://github.com/djc/rustc-version-rs)
- rustix 1.1.5 (https://github.com/bytecodealliance/rustix)
- rustls-native-certs 0.8.5 (https://github.com/rustls/rustls-native-certs)
- rustls 0.23.46 (https://github.com/rustls/rustls)
- security-framework-sys 2.17.0 (https://github.com/kornelski/rust-security-framework)
- security-framework 3.7.0 (https://github.com/kornelski/rust-security-framework)
- smallvec 1.16.4 (https://github.com/servo/rust-smallvec)
- syn 1.0.109 (https://github.com/dtolnay/syn)
- system-deps 6.2.2 (https://github.com/gdesmott/system-deps)
@@ -4732,7 +4738,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Community Data License Agreement Permissive 2.0
----------------------------------------------------------------------
Used by:
- webpki-roots 1.0.11 (https://github.com/rustls/webpki-roots)
- webpki-root-certs 1.0.12 (https://github.com/rustls/webpki-roots)
# Community Data License Agreement - Permissive - Version 2.0
@@ -5549,6 +5555,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
MIT License
----------------------------------------------------------------------
Used by:
- schannel 0.1.30 (https://github.com/steffengy/schannel-rs)
Copyright (c) 2015 steffengy
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
MIT License
----------------------------------------------------------------------
Used by:
+22 -4
View File
@@ -11,13 +11,31 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.11"
tar = "0.4"
ureq = { version = "3", default-features = false, features = ["rustls"] }
ureq = { version = "3", default-features = false, features = ["rustls-no-provider"] }
# The rustls and ring crypto provider ureq is built without
# ("rustls-no-provider"): connect.rs's tls_config hands ring to every agent.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
# The system's root certificates (macOS keychain, Windows store, /etc/ssl),
# merged with the bundled Mozilla set for registries, updates and Share (#303).
# roots.rs is self-contained (rustls-pki-types, rustls-native-certs, the
# bundled set only): kiri-win compiles it by path, without kiri-image.
rustls-native-certs = "0.8"
rustls-pki-types = "1"
webpki-root-certs = "1"
# The roots an administrator distrusted (roots.rs): "Never Trust" in the
# macOS trust settings, the Windows Disallowed store. Both already come in
# with rustls-native-certs.
[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "3"
[target.'cfg(windows)'.dependencies]
schannel = "0.1"
[dev-dependencies]
# Tests serve TLS on localhost with a self-signed certificate, as an
# insecure registry does. Both crates are already in the workspace.
# Tests serve TLS on localhost with a self-signed CA to prove both insecure
# registries and merged-root trust (#303).
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
[lints]
workspace = true
+20 -1
View File
@@ -49,11 +49,30 @@ pub(crate) fn connector_with(stall: Duration) -> impl Connector<(), Out = impl T
().chain(ConnectProxyConnector::default()).chain(HappyConnector { stall }).chain(RustlsConnector::default())
}
/// The TLS settings every verified ureq agent is built on: the merged roots
/// (`trusted`, the system's store and the bundled set) and ring. ureq is
/// built without its bundled roots or a default provider, so an agent
/// without these fails its first https call.
pub fn tls_config(roots: &[rustls_pki_types::CertificateDer<'static>]) -> ureq::tls::TlsConfig {
ureq::tls::TlsConfig::builder()
.root_certs(ureq::tls::RootCerts::Specific(Arc::new(
roots
.iter()
.map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned())
.collect::<Vec<_>>(),
)))
.unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
.build()
}
/// TLS without checking the server's certificate: only for the hosts
/// daemon.json lists in `insecure-registries` (a self-signed registry), as
/// Docker reaches them. Nothing else is built on it.
pub(crate) fn unverified_tls_config() -> ureq::tls::TlsConfig {
ureq::tls::TlsConfig::builder().disable_verification(true).build()
ureq::tls::TlsConfig::builder()
.disable_verification(true)
.unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider()))
.build()
}
/// The addresses in the order to try them: the family the resolver put
+2
View File
@@ -11,12 +11,14 @@ pub mod jsonfile;
pub mod mirror;
pub mod reference;
pub mod registry;
pub mod roots;
pub mod storage;
pub mod store;
pub mod tags;
pub use cancel::Cancel;
pub use config::{Insecure, RegistryConfig};
pub use connect::tls_config;
pub use mirror::Mirror;
pub use reference::Reference;
pub use registry::{
+39 -9
View File
@@ -563,7 +563,7 @@ const IDLE: Duration = Duration::from_secs(90);
/// hop is checked (never from HTTPS down to plain HTTP to a host the list
/// does not allow, credentials only to the origin first asked).
fn shared_agent() -> ureq::Agent {
static AGENT: Mutex<Option<(ProxyChoice, ureq::Agent)>> = Mutex::new(None);
static AGENT: Mutex<Option<(ProxyChoice, u64, ureq::Agent)>> = Mutex::new(None);
cached_agent(&AGENT, false)
}
@@ -573,15 +573,19 @@ fn shared_agent() -> ureq::Agent {
/// goes to a verified connection. Made the first time a listed host is
/// asked, never otherwise.
fn insecure_agent() -> ureq::Agent {
static AGENT: Mutex<Option<(ProxyChoice, ureq::Agent)>> = Mutex::new(None);
static AGENT: Mutex<Option<(ProxyChoice, u64, ureq::Agent)>> = Mutex::new(None);
cached_agent(&AGENT, true)
}
fn cached_agent(slot: &Mutex<Option<(ProxyChoice, ureq::Agent)>>, insecure: bool) -> ureq::Agent {
fn cached_agent(slot: &Mutex<Option<(ProxyChoice, u64, ureq::Agent)>>, insecure: bool) -> ureq::Agent {
let chosen = PROXY_SOURCE.get().and_then(|f| f());
// A host's roots arriving (kiri-win, from the Windows store) builds the
// verified agent again too.
let roots = if insecure { 0 } else { crate::roots::generation() };
let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner());
if let Some((c, agent)) = slot.as_ref()
if let Some((c, g, agent)) = slot.as_ref()
&& *c == chosen
&& *g == roots
{
return agent.clone();
}
@@ -597,9 +601,12 @@ fn cached_agent(slot: &Mutex<Option<(ProxyChoice, ureq::Agent)>>, insecure: bool
// Redirects are followed by hand, hop by hop ([`Client::get_following`]).
.max_redirects(0);
// A listed host's certificate is not checked, as Docker reaches an
// insecure registry; every other agent keeps ureq's verified TLS.
// insecure registry; every other agent verifies against the merged roots
// so corporate proxies and private CAs trusted by the OS work (#303).
if insecure {
cfg = cfg.tls_config(crate::connect::unverified_tls_config());
} else {
cfg = cfg.tls_config(crate::tls_config(&crate::roots::trusted()));
}
if let Some(p) = proxy(chosen.clone()) {
cfg = cfg.proxy(p);
@@ -607,7 +614,7 @@ fn cached_agent(slot: &Mutex<Option<(ProxyChoice, ureq::Agent)>>, insecure: bool
// Happy Eyeballs rather than ureq's one address after another, so an
// IPv6 address without a working route does not stall the pull.
let agent = ureq::Agent::with_parts(cfg.build(), crate::connect::connector(), ureq::unversioned::resolver::DefaultResolver::default());
*slot = Some((chosen, agent.clone()));
*slot = Some((chosen, roots, agent.clone()));
agent
}
@@ -2445,7 +2452,11 @@ mod tests {
}
fn test_client() -> Client {
let cfg = ureq::Agent::config_builder().http_status_as_error(false).max_redirects(0).build();
let cfg = ureq::Agent::config_builder()
.http_status_as_error(false)
.max_redirects(0)
.tls_config(crate::tls_config(&crate::roots::trusted()))
.build();
let agent = ureq::Agent::with_parts(cfg, crate::connect::connector_with(Duration::from_millis(300)), ureq::unversioned::resolver::DefaultResolver::default());
Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None }
}
@@ -2694,7 +2705,10 @@ mod tests {
let root = std::env::temp_dir().join(format!("kiri-slow-cancel-test-{}", std::process::id()));
let store = Store::open(&root).unwrap();
let reference = Reference::parse(&format!("{host}/test/blob:1")).unwrap();
let config = ureq::Agent::config_builder().http_status_as_error(false).build();
let config = ureq::Agent::config_builder()
.http_status_as_error(false)
.tls_config(crate::tls_config(&crate::roots::trusted()))
.build();
let agent = ureq::Agent::with_parts(config, crate::connect::connector_with(Duration::from_secs(2)), ureq::unversioned::resolver::DefaultResolver::default());
let client = Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None };
let _ = client.base(&host);
@@ -2726,7 +2740,10 @@ mod tests {
let store = Store::open(&root).unwrap();
let r = Reference::parse(&format!("{host}/test/blob:1")).unwrap();
// Stalls only give up after 10 s: the cancel must not wait for that.
let cfg = ureq::Agent::config_builder().http_status_as_error(false).build();
let cfg = ureq::Agent::config_builder()
.http_status_as_error(false)
.tls_config(crate::tls_config(&crate::roots::trusted()))
.build();
let agent = ureq::Agent::with_parts(cfg, crate::connect::connector_with(Duration::from_secs(10)), ureq::unversioned::resolver::DefaultResolver::default());
let client = Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None };
// A loopback registry's scheme is asked once (HTTPS, then HTTP):
@@ -4128,4 +4145,17 @@ mod tests {
});
(host, served)
}
/// The shared pull agent verifies against the merged roots, every one
/// of them and in order, not the bundled set only (#303).
#[test]
fn the_shared_agent_trusts_the_merged_roots() {
let agent = shared_agent();
let ureq::tls::RootCerts::Specific(certs) = agent.config().tls_config().root_certs() else {
panic!("the shared agent must trust a list of roots of its own");
};
let roots = crate::roots::trusted();
assert_eq!(certs.len(), roots.len());
assert!(certs.iter().zip(roots.iter()).all(|(a, b)| a.der() == b.as_ref()));
}
}
+672
View File
@@ -0,0 +1,672 @@
//! The roots every outbound TLS connection trusts: the system's own store
//! (the macOS keychain trust settings, the Windows store, `/etc/ssl` on
//! Linux) merged with the Mozilla set Kiri bundles. A company root CA the
//! system trusts then works for pulls, logins and Share (#303), and a
//! Linux host without `ca-certificates` still reaches Docker Hub.
//!
//! `SSL_CERT_FILE` and `SSL_CERT_DIR` are honoured on every platform, like
//! curl and OpenSSL: when either is set, [`system`] reads the certificates
//! from there instead of the platform store. The bundled roots stay in.
//!
//! A root the administrator distrusted stays out even though the bundled
//! set has it: "Never Trust" in the user or admin trust settings on macOS,
//! the Disallowed store (and roots disabled for Server Authentication) on
//! Windows. Linux has no such list to read (a root is distrusted there by
//! taking it out of the bundle), so a Mozilla root removed from `/etc/ssl`
//! is still trusted through the bundled set. A distrusted self-issued root
//! is matched by subject and public key, so a re-issued copy of it goes
//! too; a distrusted cross-certificate is matched as itself only, so the
//! self-signed root it shares a key with stays. With `KIRI_TLS_ROOTS=webpki`
//! nothing is read from the system, distrusted roots included: the bundled
//! set is used as it is.
//!
//! On Windows the engine runs in WSL, away from the Windows store: kiri-win
//! sends the daemon the Windows roots the bundled set lacks and the
//! distrusted list ([`host_export`]), and the daemon adds them
//! ([`set_host`]), so a company root works for pulls as on the Mac.
//!
//! Self-contained on purpose: kiri-win compiles this file by path, as it
//! does share.rs, without depending on kiri-image. Nothing here may name
//! ureq or rustls, only the crates kiri-win has for it (design after
//! brunoselvacj's, issue #303).
use std::panic::{self, UnwindSafe};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use rustls_pki_types::CertificateDer;
/// Which roots to trust, from `KIRI_TLS_ROOTS`. The variable is read when
/// the roots are built, not at startup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// The system's store and the bundled set: the default.
Merged,
/// The bundled set only, as it was before the system store was read:
/// `KIRI_TLS_ROOTS=webpki`, for a system store that causes trouble.
BundledOnly,
}
/// The mode `var` (an environment lookup) asks for. Every value other than
/// `webpki` — including an unset variable — keeps the merged roots.
pub fn mode(var: impl Fn(&str) -> Option<String>) -> Mode {
match var("KIRI_TLS_ROOTS").as_deref() {
Some("webpki") => Mode::BundledOnly,
_ => Mode::Merged,
}
}
/// The roots to trust: `platform`'s, unless `mode` leaves them out, then
/// `bundled`. `platform` is only called when its roots are used.
pub fn merge(
mode: Mode,
platform: impl FnOnce() -> Vec<CertificateDer<'static>>,
bundled: &[CertificateDer<'static>],
) -> Vec<CertificateDer<'static>> {
let mut roots = match mode {
Mode::Merged => platform(),
Mode::BundledOnly => Vec::new(),
};
roots.extend(bundled.iter().cloned());
roots
}
/// The Mozilla set Kiri bundles.
pub fn bundled() -> &'static [CertificateDer<'static>] {
webpki_root_certs::TLS_SERVER_ROOT_CERTS
}
/// A certificate's issuer, subject and public key, each as DER.
type Identity<'a> = (&'a [u8], &'a [u8], &'a [u8]);
/// The issuer, subject and public key of a certificate (their DER, as written in
/// it): what names a root, as opposed to one issue of it. None when `der`
/// is not a certificate this can read.
fn identity(der: &[u8]) -> Option<Identity<'_>> {
// One DER element: (tag, content, what follows).
fn element(b: &[u8]) -> Option<(u8, &[u8], &[u8])> {
let (&tag, rest) = b.split_first()?;
let (&first, rest) = rest.split_first()?;
let (len, rest) = if first < 0x80 {
(usize::from(first), rest)
} else {
let n = usize::from(first & 0x7f);
if n == 0 || n > 4 || rest.len() < n {
return None;
}
(rest[..n].iter().fold(0usize, |a, &x| a << 8 | usize::from(x)), &rest[n..])
};
(rest.len() >= len).then(|| (tag, &rest[..len], &rest[len..]))
}
// Certificate ::= SEQUENCE { tbsCertificate SEQUENCE { [0] version
// OPTIONAL, serial, signature, issuer, validity, subject, spki, ... } }
let (cert_tag, cert, tail) = element(der)?;
if cert_tag != 0x30 || !tail.is_empty() {
return None;
}
let (tbs_tag, tbs, _) = element(cert)?;
if tbs_tag != 0x30 {
return None;
}
let mut rest = tbs;
if let Some((0xa0, _, after_ver)) = element(rest) {
rest = after_ver;
}
// Serial number, signature algorithm, then issuer, validity, subject, spki.
for _ in 0..2 {
rest = element(rest)?.2;
}
let (issuer_tag, _, after_issuer) = element(rest)?;
if issuer_tag != 0x30 {
return None;
}
let issuer = &rest[..rest.len() - after_issuer.len()];
let after_validity = element(after_issuer)?.2;
let (subject_tag, _, after_subject) = element(after_validity)?;
if subject_tag != 0x30 {
return None;
}
let subject = &after_validity[..after_validity.len() - after_subject.len()];
let (spki_tag, _, after_spki) = element(after_subject)?;
if spki_tag != 0x30 {
return None;
}
let spki = &after_subject[..after_subject.len() - after_spki.len()];
Some((issuer, subject, spki))
}
/// Whether `c` is `d`, a distrusted certificate. A self-issued root is
/// distrusted by its subject and public key, so a re-issued copy of it (new
/// dates, same key) goes too. Any other certificate (a cross-certificate:
/// the same name and key as a root, but issued by another one) is distrusted
/// as itself only, so the self-signed root it vouches for stays. Certificates
/// this cannot read are compared whole.
fn same_root(c: &CertificateDer<'_>, d: &CertificateDer<'_>) -> bool {
match (identity(c), identity(d)) {
(Some((_, subject, key)), Some((issuer, d_subject, d_key))) if issuer == d_subject => subject == d_subject && key == d_key,
_ => c == d,
}
}
/// `roots` without any certificate that is one of `distrusted` (see
/// [`same_root`]).
pub fn without(
mut roots: Vec<CertificateDer<'static>>,
distrusted: &[CertificateDer<'static>],
) -> Vec<CertificateDer<'static>> {
if !distrusted.is_empty() {
roots.retain(|c| !distrusted.iter().any(|d| same_root(c, d)));
}
roots
}
/// The roots a Windows host adds to the engine in WSL: the Windows store's
/// roots that the bundled set lacks (a company root, among them), and the
/// ones its administrator distrusted.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Host {
pub certs: Vec<CertificateDer<'static>>,
pub distrusted: Vec<CertificateDer<'static>>,
}
/// The most certificates a [`Host`] list may hold, the largest single
/// certificate, and the most total DER bytes per list (so both lists hex-encoded
/// together always stay comfortably below the daemon's 8 MiB body limit).
pub const HOST_MAX_CERTS: usize = 1024;
pub const HOST_MAX_CERT_BYTES: usize = 16 << 10;
pub const HOST_MAX_LIST_DER_BYTES: usize = 1536 << 10;
/// Keeps non-empty certificates within [`HOST_MAX_CERT_BYTES`], stopping once
/// [`HOST_MAX_CERTS`] or [`HOST_MAX_LIST_DER_BYTES`] would be exceeded.
fn cap_list(iter: impl IntoIterator<Item = CertificateDer<'static>>) -> Vec<CertificateDer<'static>> {
let mut out = Vec::new();
let mut bytes = 0usize;
for cert in iter {
let len = cert.as_ref().len();
if len == 0 || len > HOST_MAX_CERT_BYTES {
continue;
}
if out.len() >= HOST_MAX_CERTS || bytes.saturating_add(len) > HOST_MAX_LIST_DER_BYTES {
break;
}
bytes += len;
out.push(cert);
}
out
}
impl Host {
/// The lists, each certificate as hex (JSON has no bytes), dropping
/// what is past the caps.
pub fn from_hex<'a>(
certs: impl IntoIterator<Item = &'a str>,
distrusted: impl IntoIterator<Item = &'a str>,
) -> Host {
let read = |list: &mut dyn Iterator<Item = &'a str>| {
cap_list(
list.filter(|h| h.len() <= HOST_MAX_CERT_BYTES * 2)
.filter_map(unhex)
.map(CertificateDer::from),
)
};
Host {
certs: read(&mut certs.into_iter()),
distrusted: read(&mut distrusted.into_iter()),
}
}
}
/// `der` as lowercase hex.
pub fn hex(der: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(der.len().saturating_mul(2));
for b in der {
s.push(DIGITS[usize::from(b >> 4)] as char);
s.push(DIGITS[usize::from(b & 15)] as char);
}
s
}
/// The bytes `s` spells in hex, or none if it is not hex.
pub fn unhex(s: &str) -> Option<Vec<u8>> {
let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
let b = s.as_bytes();
if !b.len().is_multiple_of(2) {
return None;
}
b.chunks(2).map(|p| Some(digit(p[0])? << 4 | digit(p[1])?)).collect()
}
/// `base` with a host's roots: its certificates added, and every
/// certificate it distrusts taken out, its own included.
pub fn with_host(base: &[CertificateDer<'static>], host: &Host) -> Vec<CertificateDer<'static>> {
let mut roots = base.to_vec();
roots.extend(host.certs.iter().filter(|c| !base.contains(c)).cloned());
without(roots, &host.distrusted)
}
/// This process's mode, read once with its roots.
fn mode_now() -> Mode {
static MODE: OnceLock<Mode> = OnceLock::new();
*MODE.get_or_init(|| mode(|k| std::env::var(k).ok()))
}
/// The roots from this machine, read once on first use: reading the macOS
/// keychain asks Security.framework about each certificate.
fn base() -> &'static Arc<[CertificateDer<'static>]> {
static ROOTS: OnceLock<Arc<[CertificateDer<'static>]>> = OnceLock::new();
ROOTS.get_or_init(|| {
let mode = mode_now();
let roots = merge(mode, || guarded(system), bundled());
match mode {
Mode::Merged => without(roots, &guarded(distrusted_by_system)),
Mode::BundledOnly => roots,
}
.into()
})
}
/// A host's roots as last set, with the list they make.
static HOST: Mutex<Option<(Host, Arc<[CertificateDer<'static>]>)>> = Mutex::new(None);
static GENERATION: AtomicU64 = AtomicU64::new(0);
/// Takes a host's roots (from kiri-win), and says whether that changed the
/// roots. `KIRI_TLS_ROOTS=webpki` keeps the bundled set alone, so then
/// they are kept but not used.
pub fn set_host(host: Host) -> bool {
let mut slot = HOST.lock().unwrap_or_else(|e| e.into_inner());
if slot.as_ref().is_some_and(|(h, _)| *h == host) {
return false;
}
let roots = with_host(base(), &host).into();
*slot = Some((host, roots));
GENERATION.fetch_add(1, Ordering::SeqCst);
true
}
/// Sets a host's roots only when none have been set yet, atomically under
/// the host lock, so a startup load from disk can never overwrite roots
/// kiri-win already pushed.
pub fn set_host_if_unset(host: Host) -> bool {
let mut slot = HOST.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_some() {
return false;
}
let roots = with_host(base(), &host).into();
*slot = Some((host, roots));
GENERATION.fetch_add(1, Ordering::SeqCst);
true
}
/// A host's roots as last set, if any.
pub fn host() -> Option<Host> {
HOST.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(h, _)| h.clone())
}
/// Counts the changes [`set_host`] made, so a client built on [`trusted`]
/// knows to build again.
pub fn generation() -> u64 {
GENERATION.load(Ordering::SeqCst)
}
/// The roots to trust: this machine's (read once), with a host's.
pub fn trusted() -> Arc<[CertificateDer<'static>]> {
let base = base();
if mode_now() == Mode::BundledOnly {
return base.clone();
}
match HOST.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
Some((_, roots)) => roots.clone(),
None => base.clone(),
}
}
/// What this machine adds to the engine in WSL (kiri-win's side of
/// [`set_host`]): the store's roots the bundled set lacks, and the ones
/// distrusted. Nothing with `KIRI_TLS_ROOTS=webpki`.
pub fn host_export() -> Host {
if mode_now() == Mode::BundledOnly {
return Host::default();
}
let bundled = bundled();
let certs = cap_list(guarded(system).into_iter().filter(|c| !bundled.contains(c)));
let distrusted = cap_list(guarded(distrusted_by_system));
Host { certs, distrusted }
}
/// Certificates in Windows' `ROOT` store whose Server Authentication EKU is
/// disabled (`CERT_TRUST_IS_NOT_VALID_FOR_USAGE`): kept as distrusted when
/// they match a bundled root and no Server-Auth-enabled root in `ROOT`
/// shares the same identity, so disabling a Mozilla root in Windows keeps it
/// out of the merged set without dropping enabled roots or non-TLS roots.
#[cfg(any(windows, test))]
fn windows_root_disallowed(
disallowed_for_tls: &[CertificateDer<'static>],
allowed_in_root: &[CertificateDer<'static>],
bundled: &[CertificateDer<'static>],
) -> Vec<CertificateDer<'static>> {
disallowed_for_tls
.iter()
.filter(|d| {
!allowed_in_root.iter().any(|a| same_root(a, d))
&& bundled.iter().any(|b| same_root(b, d))
})
.cloned()
.collect()
}
/// The roots the administrator distrusted on macOS: "Never Trust" in the
/// user or admin trust settings, a user's setting first, as macOS weighs
/// them. Only those domains: they hold the few certificates someone set,
/// where the system domain would mean asking about every root again.
#[cfg(target_os = "macos")]
fn distrusted_by_system() -> Vec<CertificateDer<'static>> {
use security_framework::trust_settings::{Domain, TrustSettings, TrustSettingsForCertificate};
let mut seen: Vec<(Vec<u8>, bool)> = Vec::new();
for domain in [Domain::User, Domain::Admin] {
let ts = TrustSettings::new(domain);
let Ok(iter) = ts.iter() else { continue };
for cert in iter {
let der = cert.to_der();
if seen.iter().any(|(d, _)| *d == der) {
continue;
}
let denied = matches!(
ts.tls_trust_settings_for_certificate(&cert),
Ok(Some(TrustSettingsForCertificate::Deny))
);
seen.push((der, denied));
}
}
seen.into_iter().filter(|(_, denied)| *denied).map(|(der, _)| CertificateDer::from(der)).collect()
}
/// The roots the administrator distrusted on Windows: the current user's
/// Disallowed store (which takes in the machine's and Group Policy's), plus
/// any bundled root whose Server Authentication EKU was disabled in `ROOT`
/// (`CERT_TRUST_IS_NOT_VALID_FOR_USAGE`).
#[cfg(windows)]
fn distrusted_by_system() -> Vec<CertificateDer<'static>> {
use schannel::cert_context::ValidUses;
use schannel::cert_store::CertStoreBuilder;
const PKIX_SERVER_AUTH: &str = "1.3.6.1.5.5.7.3.1";
let mut out = Vec::new();
if let Ok(store) = CertStoreBuilder::new().read_only().open_current_user("Disallowed") {
out.extend(store.certs().map(|c| CertificateDer::from(c.to_der().to_vec())));
}
if let Ok(store) = CertStoreBuilder::new().read_only().open_current_user("ROOT") {
let mut allowed = Vec::new();
let mut disallowed_for_tls = Vec::new();
for cert in store.certs() {
let der = CertificateDer::from(cert.to_der().to_vec());
let valid_now = cert.is_time_valid().unwrap_or(false);
match cert.valid_uses() {
Ok(ValidUses::All) if valid_now => allowed.push(der),
Ok(ValidUses::Oids(oids)) if oids.iter().any(|o| o == PKIX_SERVER_AUTH) && valid_now => allowed.push(der),
Ok(ValidUses::Oids(oids)) if !oids.iter().any(|o| o == PKIX_SERVER_AUTH) => disallowed_for_tls.push(der),
_ => {}
}
}
out.extend(windows_root_disallowed(&disallowed_for_tls, &allowed, bundled()));
}
out
}
/// Linux keeps no list of distrusted roots (see the module comment).
#[cfg(not(any(target_os = "macos", windows)))]
fn distrusted_by_system() -> Vec<CertificateDer<'static>> {
Vec::new()
}
/// `load`'s roots, or none if it panics (rustls-native-certs unwraps on
/// Windows), so a broken store costs the system roots, not the process.
fn guarded(
load: impl FnOnce() -> Vec<CertificateDer<'static>> + UnwindSafe,
) -> Vec<CertificateDer<'static>> {
panic::catch_unwind(load).unwrap_or_else(|_| {
eprintln!(
"kiri: reading the system certificate store failed; trusting the bundled roots only"
);
Vec::new()
})
}
/// The system's roots. With `SSL_CERT_FILE` or `SSL_CERT_DIR` set,
/// rustls-native-certs reads those instead of the store, as OpenSSL does;
/// say so, as a company CA in the keychain is then not trusted.
fn system() -> Vec<CertificateDer<'static>> {
let set = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
if set("SSL_CERT_FILE") || set("SSL_CERT_DIR") {
eprintln!(
"kiri: SSL_CERT_FILE or SSL_CERT_DIR is set, so the system certificate store is not read"
);
}
let found = rustls_native_certs::load_native_certs();
// A fixed message: an error's text can carry certificate data, which
// doesn't belong in a log.
if !found.errors.is_empty() {
eprintln!("kiri: part of the system certificate store could not be read; the rest is trusted");
}
found.certs
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn cert(byte: u8) -> CertificateDer<'static> {
CertificateDer::from(vec![byte])
}
#[test]
fn merges_the_system_roots_with_the_bundled_roots_by_default() {
let got = merge(Mode::Merged, || vec![cert(1)], &[cert(2)]);
assert_eq!(got, vec![cert(1), cert(2)]);
}
#[test]
fn kiri_tls_roots_webpki_selects_the_bundled_roots_only() {
let got = mode(|_| Some("webpki".into()));
assert_eq!(got, Mode::BundledOnly);
}
#[test]
fn kiri_tls_roots_with_another_value_selects_the_merged_roots() {
let got = mode(|_| Some("system".into()));
assert_eq!(got, Mode::Merged);
}
#[test]
fn kiri_tls_roots_unset_selects_the_merged_roots() {
let got = mode(|_| None);
assert_eq!(got, Mode::Merged);
}
#[test]
fn keeps_the_bundled_roots_when_the_system_store_is_empty() {
let got = merge(Mode::Merged, Vec::new, &[cert(2)]);
assert_eq!(got, vec![cert(2)]);
}
#[test]
fn bundled_only_mode_never_reads_the_system_store() {
let read = Cell::new(false);
let got = merge(
Mode::BundledOnly,
|| {
read.set(true);
vec![cert(1)]
},
&[cert(2)],
);
assert!(!read.get());
assert_eq!(got, vec![cert(2)]);
}
#[test]
fn keeps_the_bundled_roots_when_reading_the_system_store_panics() {
let got = merge(
Mode::Merged,
|| guarded(|| panic!("broken store")),
&[cert(2)],
);
assert_eq!(got, vec![cert(2)]);
}
#[test]
fn keeps_the_system_roots_when_reading_the_system_store_succeeds() {
let got = guarded(|| vec![cert(1)]);
assert_eq!(got, vec![cert(1)]);
}
#[test]
fn a_reissued_copy_of_a_distrusted_root_is_removed_too() {
let root = bundled()[0].clone();
// Same subject and key, different bytes: another issue of the root.
let mut other = root.as_ref().to_vec();
*other.last_mut().unwrap() ^= 0xff;
let reissued = CertificateDer::from(other);
assert_ne!(reissued, root);
assert!(identity(&root).is_some(), "the bundled roots are readable");
let kept = without(vec![reissued.clone(), bundled()[1].clone()], std::slice::from_ref(&root));
assert_eq!(kept, vec![bundled()[1].clone()]);
// Unreadable entries fall back to whole-certificate comparison.
assert_eq!(without(vec![cert(1), cert(2)], &[cert(2)]), vec![cert(1)]);
}
/// A certificate with these names and key, as the parser reads one.
fn fake(issuer: &str, subject: &str, key: &str, tag: u8) -> CertificateDer<'static> {
fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
let mut v = vec![tag, body.len() as u8];
v.extend_from_slice(body);
v
}
let name = |n: &str| tlv(0x30, n.as_bytes());
let mut tbs = tlv(0x02, &[tag]);
for part in [tlv(0x30, &[]), name(issuer), tlv(0x30, &[]), name(subject), tlv(0x30, key.as_bytes())] {
tbs.extend(part);
}
CertificateDer::from(tlv(0x30, &tlv(0x30, &tbs)))
}
#[test]
fn distrusting_a_cross_certificate_keeps_the_root_it_shares_a_key_with() {
let root = fake("R", "R", "key", 1);
let reissued = fake("R", "R", "key", 2);
let cross = fake("D", "R", "key", 3);
let other = fake("O", "O", "other", 4);
// The cross-certificate (R's name and key, issued by D): only itself.
let kept = without(vec![root.clone(), cross.clone(), other.clone()], std::slice::from_ref(&cross));
assert_eq!(kept, vec![root.clone(), other.clone()]);
// The self-signed root: itself and its re-issues.
let kept = without(vec![root.clone(), reissued, other.clone()], std::slice::from_ref(&root));
assert_eq!(kept, vec![other]);
}
#[test]
fn windows_disabled_eku_drops_disabled_bundled_root_but_keeps_enabled_and_cross_roots() {
let disabled_bundled = fake("B", "B", "kB", 1);
let reissued_bundled = fake("B", "B", "kB", 2);
let replaced_old = fake("R", "R", "kR", 1);
let replaced_new = fake("R", "R", "kR", 2);
let cross_disabled = fake("D", "S", "kS", 1);
let self_signed = fake("S", "S", "kS", 2);
let code_signing = fake("M", "M", "kM", 1);
let got = windows_root_disallowed(
&[disabled_bundled.clone(), replaced_old.clone(), cross_disabled.clone(), code_signing],
std::slice::from_ref(&replaced_new),
&[reissued_bundled, replaced_new.clone(), self_signed],
);
assert_eq!(got, vec![disabled_bundled]);
}
#[test]
fn identity_rejects_non_sequence_or_trailing_garbage() {
let valid = fake("R", "R", "key", 1);
assert!(identity(&valid).is_some());
let mut with_tail = valid.as_ref().to_vec();
with_tail.push(0x00);
assert!(identity(&with_tail).is_none());
let mut wrong_tag = valid.as_ref().to_vec();
wrong_tag[0] = 0x04;
assert!(identity(&wrong_tag).is_none());
}
#[test]
fn the_bundled_set_is_not_empty() {
assert!(!webpki_root_certs::TLS_SERVER_ROOT_CERTS.is_empty());
}
/// The merged list holds the bundled roots (real certificates now, not
/// the bare anchors webpki-roots shipped) plus everything the platform
/// store has (nothing on a bare container, hundreds on a desktop),
/// less what the administrator distrusted.
#[test]
fn merged_roots_are_the_bundled_set_plus_the_platform_store() {
// With these set the platform store is replaced or left out, so
// the count below would not hold.
let set = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
if set("SSL_CERT_FILE") || set("SSL_CERT_DIR") || mode(|k| std::env::var(k).ok()) != Mode::Merged {
return;
}
let platform = rustls_native_certs::load_native_certs().certs;
let expected = without(
platform.into_iter().chain(bundled().iter().cloned()).collect(),
&distrusted_by_system(),
);
assert_eq!(trusted().len(), expected.len());
}
#[test]
fn a_distrusted_root_is_left_out_of_the_bundled_set_too() {
let got = without(vec![cert(1), cert(2), cert(3)], &[cert(2)]);
assert_eq!(got, vec![cert(1), cert(3)]);
}
#[test]
fn a_hosts_roots_are_added_and_its_distrusted_ones_taken_out() {
let host = Host { certs: vec![cert(4), cert(1)], distrusted: vec![cert(2), cert(4)] };
let got = with_host(&[cert(1), cert(2), cert(3)], &host);
assert_eq!(got, vec![cert(1), cert(3)]);
}
#[test]
fn hex_goes_both_ways() {
let der = (0..=255u8).collect::<Vec<_>>();
assert_eq!(unhex(&hex(&der)).unwrap(), der);
assert_eq!(unhex("0A"), Some(vec![10]));
assert_eq!(unhex("abc"), None);
assert_eq!(unhex("zz"), None);
}
#[test]
fn host_lists_drop_what_does_not_decode_and_what_is_past_the_caps() {
let big = "00".repeat(HOST_MAX_CERT_BYTES + 1);
let many = vec!["01"; HOST_MAX_CERTS + 5];
let host = Host::from_hex(["0102", "nothex", "", big.as_str()], many.iter().copied());
assert_eq!(host.certs, vec![CertificateDer::from(vec![1, 2])]);
assert_eq!(host.distrusted.len(), HOST_MAX_CERTS);
// Total DER byte budget also caps a list of maximum-size certificates.
let max_one = vec![0xab; HOST_MAX_CERT_BYTES];
let capped = cap_list((0..200).map(|_| CertificateDer::from(max_one.clone())));
assert_eq!(capped.len(), HOST_MAX_LIST_DER_BYTES / HOST_MAX_CERT_BYTES);
}
}
+84
View File
@@ -0,0 +1,84 @@
//! A Windows host's roots in the engine (#303): kiri-win sends the daemon
//! in WSL the Windows store's roots the bundled set lacks and the ones the
//! administrator distrusted, and every agent built on
//! [`kiri_image::roots::trusted`] then trusts the first and refuses the
//! second. Its own binary: setting a host's roots changes the process's.
use kiri_image::roots::{Host, bundled, generation, set_host, set_host_if_unset, trusted};
use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair, SanType};
use rustls::pki_types::CertificateDer;
#[test]
fn a_hosts_root_is_trusted_and_its_distrusted_root_is_not() {
// KIRI_TLS_ROOTS=webpki keeps the bundled set alone, on purpose.
if std::env::var("KIRI_TLS_ROOTS").as_deref() == Ok("webpki") {
return;
}
let (port, ca) = localhost_tls_server();
let url = format!("https://127.0.0.1:{port}/");
let agent = || -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(std::time::Duration::from_secs(5)))
.tls_config(kiri_image::tls_config(&trusted()))
.build()
.into()
};
assert!(agent().get(&url).call().is_err(), "a root nobody sent is not trusted");
let distrusted = bundled()[0].clone();
let before = generation();
let host = Host { certs: vec![ca.der().clone()], distrusted: vec![distrusted.clone()] };
assert!(set_host(host.clone()));
assert_eq!(generation(), before + 1, "agents built on the roots know to build again");
assert!(!set_host(host), "the same roots again change nothing");
assert_eq!(generation(), before + 1);
assert!(!set_host_if_unset(Host::default()), "startup disk load must not overwrite pushed host roots");
assert_eq!(generation(), before + 1);
let roots = trusted();
assert!(roots.contains(&CertificateDer::from(ca.der().to_vec())));
assert!(!roots.contains(&distrusted), "a root the host distrusted is out, bundled or not");
assert_eq!(agent().get(&url).call().unwrap().body_mut().read_to_string().unwrap(), "ok");
}
/// A TLS server on localhost with a certificate for `127.0.0.1`, signed
/// by a fresh self-signed CA. Returns the port and the CA certificate.
fn localhost_tls_server() -> (u16, rcgen::Certificate) {
let ca_key = KeyPair::generate().unwrap();
let mut ca_params = CertificateParams::new(Vec::<String>::new()).unwrap();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca = ca_params.clone().self_signed(&ca_key).unwrap();
let server_key = KeyPair::generate().unwrap();
let mut p = CertificateParams::new(Vec::<String>::new()).unwrap();
p.subject_alt_names = vec![SanType::IpAddress("127.0.0.1".parse().unwrap())];
let server = p.signed_by(&server_key, &Issuer::new(ca_params, &ca_key)).unwrap();
let config = rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(
vec![server.der().clone()],
rustls::pki_types::PrivateKeyDer::Pkcs8(server_key.serialize_der().into()),
)
.unwrap();
let config = std::sync::Arc::new(config);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let config = config.clone();
std::thread::spawn(move || {
use std::io::{Read, Write};
let mut conn = rustls::ServerConnection::new(config).unwrap();
let mut stream = stream;
let mut tls = rustls::Stream::new(&mut conn, &mut stream);
let mut buf = [0u8; 4096];
if tls.read(&mut buf).is_ok() {
let _ = tls.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok");
let _ = tls.flush();
}
});
}
});
(port, ca)
}
+134
View File
@@ -0,0 +1,134 @@
//! `share` accepts a self-signed CA once it is trusted, and rejects the
//! same server before that: the merged roots, handed to a ureq agent
//! through [`kiri_image::tls_config`], are what decide (#303).
//! This lives outside the crate because it spins a live TLS server and
//! agents, not because the crate needs anything but its own roots.
use kiri_image::roots::{Mode, merge, trusted};
use rcgen::{
BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, SanType,
};
use rustls::pki_types::CertificateDer;
/// An agent on the bundled set alone rejects the self-signed server, so
/// does an agent on the merged roots without the CA, and the merged roots
/// with the CA added accept it.
#[test]
fn self_signed_localhost_is_rejected_by_default_and_accepted_once_added() {
let (port, ca) = localhost_tls_server();
let url = format!("https://127.0.0.1:{port}/");
let agent_on = |roots: &[CertificateDer<'static>]| {
ureq::Agent::config_builder()
.timeout_connect(Some(std::time::Duration::from_secs(5)))
.tls_config(kiri_image::tls_config(roots))
.build()
.into()
};
let accepted = |agent: ureq::Agent| {
let mut resp = agent
.get(&url)
.call()
.expect("merged store accepts the self-signed CA");
resp.body_mut()
.with_config()
.limit(64 << 10)
.read_to_string()
.unwrap()
};
let rejected = |agent: ureq::Agent| {
assert!(
agent.get(&url).call().is_err(),
"the agent must reject the self-signed CA"
);
};
// Without the CA: the bundled set alone (what `KIRI_TLS_ROOTS=webpki`
// keeps, and all Kiri had before #303) and the merged store.
rejected(agent_on(&merge(
Mode::BundledOnly,
Vec::new,
webpki_root_certs::TLS_SERVER_ROOT_CERTS,
)));
rejected(agent_on(&trusted()));
// With the CA among the merged roots.
let mut certs = trusted().to_vec();
certs.push(ca.der().clone());
assert_eq!(accepted(agent_on(&certs)), "ok");
}
/// The bundled roots, being full certificates, sit in a rustls root store
/// as they are: subject, public key and name constraints are the
/// certificate's own, so nothing is rebuilt around them.
#[test]
fn the_bundled_roots_load_into_a_root_store_unchanged() {
let mut store = rustls::RootCertStore::empty();
store.add_parsable_certificates(webpki_root_certs::TLS_SERVER_ROOT_CERTS.to_vec());
assert_eq!(store.len(), webpki_root_certs::TLS_SERVER_ROOT_CERTS.len());
}
/// A TLS server on localhost with a certificate for `127.0.0.1`, signed
/// by a fresh self-signed CA. Returns the port and the CA certificate.
fn localhost_tls_server() -> (u16, rcgen::Certificate) {
let ca_key = KeyPair::generate().unwrap();
let mut ca_params = CertificateParams::new(Vec::<String>::new()).unwrap();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca = ca_params.clone().self_signed(&ca_key).unwrap();
let server_key = KeyPair::generate().unwrap();
let mut p = CertificateParams::new(Vec::<String>::new()).unwrap();
p.subject_alt_names = vec![
SanType::DnsName("localhost".to_owned().try_into().unwrap()),
SanType::IpAddress(std::net::IpAddr::from([127, 0, 0, 1])),
];
p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
let server_cert = p
.signed_by(&server_key, &Issuer::new(ca_params, ca_key))
.unwrap();
let key = rustls::pki_types::PrivatePkcs8KeyDer::from(server_key.serialize_der());
let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider());
let config = rustls::ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(
vec![
CertificateDer::from(server_cert.der().to_vec()),
CertificateDer::from(ca.der().to_vec()),
],
key.into(),
)
.unwrap();
let config = std::sync::Arc::new(config);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
// The test makes a handful of connections (the ones it expects
// to be rejected dial too); serve a few more than that.
for _ in 0..8 {
let Ok((sock, _)) = listener.accept() else {
return;
};
let _ = sock.set_read_timeout(Some(std::time::Duration::from_secs(10)));
let Ok(conn) = rustls::ServerConnection::new(config.clone()) else {
continue;
};
// Reads and writes complete the handshake as they go.
let mut stream = rustls::StreamOwned::new(conn, sock);
let mut buf = [0u8; 4096];
let _ = std::io::Read::read(&mut stream, &mut buf);
if std::io::Write::write_all(
&mut stream,
b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
)
.is_ok()
{
let _ = std::io::Write::flush(&mut stream);
}
}
});
(port, ca)
}
+46
View File
@@ -0,0 +1,46 @@
//! `SSL_CERT_FILE` replaces the platform's roots for everything built on
//! [`kiri_image::roots`] (#303). The variable is read when the roots are
//! built, as with curl and OpenSSL, so a test can set it and see the
//! certificates come out. This lives outside the crate because the crate
//! forbids unsafe code and setting an environment variable is unsafe.
use kiri_image::roots::trusted;
/// The file's certificates replace the platform store, and the bundled
/// roots stay merged in.
#[test]
fn ssl_cert_file_replaces_the_platform_roots() {
let ca = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
let key = rcgen::KeyPair::generate().unwrap();
let cert = ca.self_signed(&key).unwrap();
let file = std::env::temp_dir().join(format!(
"kiri-roots-ssl-cert-file-{}.pem",
std::process::id()
));
std::fs::write(&file, cert.pem()).unwrap();
// SAFETY: the only test in this binary, so nothing else reads the
// environment meanwhile. KIRI_TLS_ROOTS=webpki would leave the file
// out, and SSL_CERT_DIR would add its certificates to the file's.
unsafe {
std::env::remove_var("KIRI_TLS_ROOTS");
std::env::remove_var("SSL_CERT_DIR");
std::env::set_var("SSL_CERT_FILE", &file);
}
let certs = trusted();
unsafe { std::env::remove_var("SSL_CERT_FILE") };
let _ = std::fs::remove_file(&file);
assert_eq!(
certs.len(),
webpki_root_certs::TLS_SERVER_ROOT_CERTS.len() + 1
);
// The file's certificate replaces the platform store at the front of
// the merged list, the bundled roots unchanged after it. (No root the
// administrator distrusted is in the bundled set on a test machine.)
assert_eq!(certs.first().unwrap().as_ref(), cert.der().as_ref());
assert!(
certs[1..]
.iter()
.zip(webpki_root_certs::TLS_SERVER_ROOT_CERTS)
.all(|(a, b)| a.as_ref() == b.as_ref())
);
}
+48
View File
@@ -0,0 +1,48 @@
//! `KIRI_TLS_ROOTS=webpki` keeps the bundled Mozilla set alone, reading
//! nothing from the platform store (or `SSL_CERT_FILE`), exporting nothing
//! to WSL, and ignoring any host roots sent via `set_host` (#303).
//! Its own binary: `MODE` and `ROOTS` are read once per process.
use kiri_image::roots::{Host, bundled, host_export, set_host, trusted};
#[test]
fn kiri_tls_roots_webpki_uses_only_the_bundled_roots() {
let ca = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
let key = rcgen::KeyPair::generate().unwrap();
let cert = ca.self_signed(&key).unwrap();
let file = std::env::temp_dir().join(format!(
"kiri-roots-webpki-{}.pem",
std::process::id()
));
std::fs::write(&file, cert.pem()).unwrap();
// SAFETY: the only test in this binary, so nothing else reads the
// environment meanwhile.
unsafe {
std::env::set_var("KIRI_TLS_ROOTS", "webpki");
std::env::set_var("SSL_CERT_FILE", &file);
std::env::remove_var("SSL_CERT_DIR");
}
let got = trusted();
assert_eq!(got.len(), bundled().len());
assert!(got.iter().zip(bundled()).all(|(a, b)| a.as_ref() == b.as_ref()));
// host_export reads nothing from the system when webpki-only is set.
assert_eq!(host_export(), Host::default());
// Even after set_host adds a CA and distrusts a bundled root, trusted()
// keeps the bundled set intact while KIRI_TLS_ROOTS=webpki is active.
assert!(set_host(Host {
certs: vec![cert.der().clone()],
distrusted: vec![bundled()[0].clone()],
}));
let after = trusted();
assert_eq!(after.len(), bundled().len());
assert!(after.iter().zip(bundled()).all(|(a, b)| a.as_ref() == b.as_ref()));
unsafe {
std::env::remove_var("KIRI_TLS_ROOTS");
std::env::remove_var("SSL_CERT_FILE");
}
let _ = std::fs::remove_file(&file);
}
+9 -2
View File
@@ -11,10 +11,15 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.11"
# Share in the window: crates/kiri/src/share.rs, the same library as
# `kiri share`, with what it needs for the TLS connection to the edge.
# `kiri share`. Its roots come from crates/kiri-image/src/roots.rs, compiled
# by path, so kiri-win needs that file's crates instead of kiri-image.
kiri-share-proto = { path = "../kiri-share-proto" }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
webpki-roots = "1"
rustls-native-certs = "0.8"
rustls-pki-types = "1"
webpki-root-certs = "1"
# roots.rs's distrusted roots: the Disallowed store and disabled ROOT entries.
schannel = "0.1"
libc = "0.2"
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Memory", "Win32_System_Diagnostics_ToolHelp", "Win32_System_ProcessStatus", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_Com", "Win32_System_Console", "Win32_System_DataExchange", "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Pipes", "Win32_System_Registry", "Win32_System_RemoteDesktop", "Win32_System_Services", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
# The window: WebView2 (part of Windows) and plain Win32, as the Mac app is
@@ -25,6 +30,8 @@ windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Graphics_Dw
[dev-dependencies]
# crates/kiri-win/src/refuse.rs's tests, on any host.
serde_json = "1"
# share.rs's tests (compiled here by path) make a certificate authority.
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] }
[build-dependencies]
# The icon resource in kiri-win.exe (build.rs).
+45 -1
View File
@@ -153,9 +153,11 @@ fn state(name: &str, error: Option<&str>) -> String {
fn engine(rx: &Receiver<Cmd>, tx: Sender<Cmd>) {
watch(tx);
// Windows' proxy for the daemon, now and every minute.
// Windows' proxy and root certificates for the daemon, now and every
// minute.
std::thread::spawn(|| loop {
send_windows_proxy();
send_windows_roots(false);
std::thread::sleep(Duration::from_secs(60));
});
let mut pending: Option<Cmd> = None;
@@ -305,6 +307,8 @@ fn bring_up(launch: bool) {
let woken = ensure_daemon().and_then(|()| if wakes(launch, stopped()) { wake().map(|()| true) } else { Ok(false) });
match woken {
Ok(woken) => {
// Before the first pull, not up to a minute after.
std::thread::spawn(|| send_windows_roots(true));
if woken {
std::thread::spawn(ensure_builder);
}
@@ -1087,6 +1091,14 @@ mod tests {
use super::{allowed_url, unanswered, wakes};
use std::io::ErrorKind;
#[test]
fn roots_are_sent_when_they_change_or_the_engine_is_new() {
assert!(super::roots_need_sending(None, "a", false));
assert!(!super::roots_need_sending(Some("a"), "a", false));
assert!(super::roots_need_sending(Some("a"), "b", false));
assert!(super::roots_need_sending(Some("a"), "a", true));
}
/// As on the Mac and Linux: Stop on a stopped container, or Start on a
/// running one, is done (Docker's 304, with no body), not an empty error.
#[test]
@@ -1683,6 +1695,38 @@ fn push_windows_proxy(mut body: Value, relay_ports: impl FnOnce(&[u16]) -> std::
let _ = client::request_with("PUT", "/kiri/proxy/system", Some(&body), true);
}
/// The Windows store's root certificates for the daemon in WSL (#303): the
/// ones the bundled set lacks (a company root, Group Policy's) and the
/// distrusted ones, so pulls trust what Windows trusts, as on the Mac.
/// The daemon keeps them and only acts on a change, so they are sent when
/// they differ from what was last sent, or when `force` (the engine has just
/// started, and may be a new one). Marked as the window's own (background) so
/// periodic sends never keep the VM awake.
pub(crate) fn send_windows_roots(force: bool) {
static SENT: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
let host = crate::roots::host_export();
let list = |l: &[rustls_pki_types::CertificateDer<'static>]| l.iter().map(|c| crate::roots::hex(c)).collect::<Vec<_>>();
let body = json!({"certs": list(&host.certs), "distrusted": list(&host.distrusted)});
let digest = {
use sha2::{Digest, Sha256};
Sha256::digest(body.to_string().as_bytes()).iter().map(|b| format!("{b:02x}")).collect::<String>()
};
let mut last = SENT.lock().unwrap_or_else(|e| e.into_inner());
if !roots_need_sending(last.as_deref(), &digest, force) {
return;
}
// Kept only once the daemon took them, so a failed send is tried again.
if client::request_with("PUT", "/kiri/roots/host", Some(&body), true).is_ok_and(|r| r.ok()) {
*last = Some(digest);
}
}
/// Whether the roots with `digest` go to the daemon: they changed since
/// `last` was sent, nothing was sent yet, or `force`.
fn roots_need_sending(last: Option<&str>, digest: &str, force: bool) -> bool {
force || last != Some(digest)
}
/// Settings → Domains: reads (or moves, then reads) the routers' ports. The
/// routers listen on WSL's loopback; WSL forwards their port to Windows'.
fn router_ports(set: Option<Value>) {
+8 -1
View File
@@ -97,11 +97,18 @@ mod daemon {
#[cfg(windows)]
mod wslconfig;
// Kiri Dev's names (the window on Windows is always Kiri) and Share, the
// Mac's own files: crates/kiri/src/flavor.rs and share.rs.
// Mac's own files: crates/kiri/src/flavor.rs and share.rs. Share's roots
// come from crates/kiri-image/src/roots.rs, mounted here directly as
// crate::roots — the name share.rs reaches it by in kiri, whose main.rs
// aliases kiri_image::roots — so the same file compiles unchanged.
#[cfg(windows)]
#[path = "../../kiri/src/flavor.rs"]
mod flavor;
#[cfg(windows)]
#[path = "../../kiri-image/src/roots.rs"]
#[allow(dead_code)]
mod roots;
#[cfg(windows)]
#[path = "../../kiri/src/share.rs"]
#[allow(dead_code)]
mod share;
+1 -3
View File
@@ -17,11 +17,9 @@ sha2 = "0.11"
flate2 = "1"
# zstd uploads to the same endpoints: the decoder the guest unpacks layers with.
ruzstd = "0.9"
ureq = { version = "3", default-features = false, features = ["rustls"] }
ureq = { version = "3", default-features = false, features = ["rustls-no-provider"] }
# HTTPS for container names: the same rustls and ring ureq already brings in.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
# Roots for `kiri share`'s connection to the edge.
webpki-roots = "1"
rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] }
# The `name` filter is a regular expression in Docker (k3d sends `^[/]?name$`).
# regex-lite: RE2 syntax like Go's regexp, without the Unicode tables' size.
+55 -2
View File
@@ -191,6 +191,9 @@ fn route(req: &Request, engine: &Arc<Engine>, caller: &Caller, w: &mut UnixStrea
("GET", "/kiri/proxy") => return reply(w, Ok(super::proxy::report()), 200),
("POST", "/kiri/proxy") => return reply(w, set_proxy(req), 200),
("PUT", "/kiri/proxy/system") => return reply(w, set_host_proxy(req), 200),
// kiri-win's Windows roots, for the engine in WSL (#303).
#[cfg(target_os = "linux")]
("PUT", "/kiri/roots/host") => return reply(w, set_host_roots(req, caller), 200),
// daemon.json's registry keys: Settings → Registries, `kiri registry`.
("GET", "/kiri/registries") => return reply(w, Ok(super::daemon_json::report()), 200),
("POST", "/kiri/registries") => return reply(w, set_registries(req, engine), 200),
@@ -1090,6 +1093,22 @@ fn set_host_proxy(req: &Request) -> Result<Value, Error> {
Ok(super::proxy::report())
}
#[cfg(any(target_os = "linux", test))]
fn set_host_roots(req: &Request, caller: &Caller) -> Result<Value, Error> {
// Only the Windows host (via kiri-win over the daemon's own socket) may
// supply host roots: never a container or an integrated WSL distro (#303).
if *caller != Caller::Host {
return Err(Error::Forbidden("the Windows roots can only be set from Kiri on Windows".into()));
}
// Only the engine in WSL takes them: a native Linux daemon has its own
// certificate store.
if !super::hostroots::in_wsl() {
return Err(Error::BadRequest("the Windows roots are for the engine in WSL".into()));
}
let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?;
super::hostroots::set(&body).map_err(Error::Io)
}
fn set_proxy(req: &Request) -> Result<Value, Error> {
let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?;
let mode = body["mode"].as_str().filter(|m| ["system", "custom", "none"].contains(m)).ok_or_else(|| Error::BadRequest("mode must be system, custom or none".into()))?;
@@ -5376,7 +5395,7 @@ mod tests {
};
let mut routes = kiri_routes(body_of(include_str!("api.rs"), "\nfn route("));
routes.extend(kiri_routes(body_of(include_str!("ops.rs"), "\npub fn route(")));
for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("POST", "/kiri/containers/1/upper"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] {
for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("PUT", "/kiri/roots/host"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("POST", "/kiri/containers/1/upper"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] {
assert!(routes.iter().any(|(m, p)| (m.as_str(), p.as_str()) == known), "{known:?} not found in route(): {routes:?}");
}
for (m, p) in &routes {
@@ -5448,7 +5467,7 @@ mod tests {
fn a_containers_stop_and_settings_are_refused() {
use std::io::{Read, Write};
let (root, engine) = engine_in("container-gate", false);
for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains", "POST /kiri/fs-events"] {
for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "PUT /kiri/roots/host", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains", "POST /kiri/fs-events"] {
let (mut client, server) = UnixStream::pair().unwrap();
let served = std::thread::spawn({
let engine = engine.clone();
@@ -5489,6 +5508,40 @@ mod tests {
let _ = std::fs::remove_dir_all(root);
}
/// `PUT /kiri/roots/host` accepts only `Caller::Host` (kiri-win): neither a
/// container nor an integrated WSL distro may inject root CAs (#303).
#[test]
fn host_roots_endpoint_requires_host_caller() {
let req = Request::internal("PUT", "/kiri/roots/host", &[], br#"{"certs":["3001"],"distrusted":[]}"#.to_vec());
assert!(matches!(set_host_roots(&req, &Caller::Container), Err(Error::Forbidden(_))));
assert!(matches!(set_host_roots(&req, &Caller::Wsl("Ubuntu".into())), Err(Error::Forbidden(_))));
if !crate::daemon::hostroots::in_wsl() {
assert!(matches!(set_host_roots(&req, &Caller::Host), Err(Error::BadRequest(_))));
}
// Over the live HTTP handler: a WSL distro receives 403 on Linux.
#[cfg(target_os = "linux")]
{
use std::io::{Read, Write};
let (root, engine) = engine_in("wsl-host-roots-gate", false);
let (mut client, server) = UnixStream::pair().unwrap();
let served = std::thread::spawn({
let engine = engine.clone();
move || serve(server, engine, Caller::Wsl("Ubuntu".into()))
});
let body = r#"{"certs":["3001"],"distrusted":[]}"#;
client
.write_all(format!("PUT /kiri/roots/host HTTP/1.1\r\nHost: d\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes())
.unwrap();
let mut got = String::new();
client.read_to_string(&mut got).unwrap();
served.join().unwrap().unwrap();
assert!(got.starts_with("HTTP/1.1 403 "), "{got}");
drop(engine);
let _ = std::fs::remove_dir_all(root);
}
}
/// `POST /kiri/registries` refreshes synchronously on the request thread
/// only when the save changed settings, never from a detached thread after
/// answering.
+233
View File
@@ -0,0 +1,233 @@
//! A Windows host's root certificates, for the engine in WSL (#303). The
//! daemon runs in a Linux distro there, away from the Windows store, so
//! kiri-win sends the store's roots that the bundled set lacks (a company
//! root, among them) and the ones the administrator distrusted
//! (`PUT /kiri/roots/host`), when the engine starts and every minute. They
//! are kept in `~/.kiri/host-roots.json`, so a pull before the window has
//! sent them (the engine started by the boot command) trusts them too.
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use kiri_image::roots::{self, Host};
use serde_json::{Value, json};
/// The file's size at most: every certificate past the caps is dropped
/// anyway.
const MAX_FILE: u64 = 8 << 20;
fn path() -> Option<PathBuf> {
super::state_dir().ok().map(|d| d.join("host-roots.json"))
}
/// The roots in `body` (`{"certs": [hex DER…], "distrusted": [hex DER…]}`).
pub fn parse(body: &Value) -> Host {
let list = |k: &str| body[k].as_array().into_iter().flatten().filter_map(Value::as_str);
Host::from_hex(list("certs"), list("distrusted"))
}
fn to_json(h: &Host) -> Value {
let list = |l: &[rustls::pki_types::CertificateDer<'static>]| l.iter().map(|c| roots::hex(c)).collect::<Vec<_>>();
json!({"certs": list(&h.certs), "distrusted": list(&h.distrusted)})
}
/// Whether this daemon is the engine in WSL: the only place kiri-win's
/// roots belong. A native Linux daemon has its own store, and takes
/// neither the roots nor the file they are kept in.
pub fn in_wsl() -> bool {
super::binds::wsl().is_some()
}
/// Takes the roots kiri-win sent, keeping them for the next start when
/// they changed. Answers with how many there are.
pub fn set(body: &Value) -> io::Result<Value> {
// One save at a time: they share a temp file and serialize disk + memory updates.
static SAVING: Mutex<()> = Mutex::new(());
let _saving = SAVING.lock().unwrap_or_else(|e| e.into_inner());
let host = parse(body);
let (certs, distrusted) = (host.certs.len(), host.distrusted.len());
let same = roots::host().as_ref() == Some(&host);
if !same && let Some(p) = path() {
save_to(&p, &host)?;
}
let changed = roots::set_host(host);
Ok(json!({"certs": certs, "distrusted": distrusted, "changed": changed}))
}
/// Atomically writes `host` to `p` with mode `0600`, refusing to write through
/// any pre-existing symlink at the temp path or destination.
fn save_to(p: &Path, host: &Host) -> io::Result<()> {
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = p.with_extension("json.tmp");
// A stale temp file, or a link put there, is not written through.
let _ = std::fs::remove_file(&tmp);
let bytes = to_json(host).to_string();
if let Err(e) = write_private(&tmp, bytes.as_bytes()) {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
if let Err(e) = std::fs::rename(&tmp, p) {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// A new file only this user can read or write, whatever the umask (the
/// daemon's unit may run with 0027, a shell with 022).
fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(bytes)?;
f.sync_all()
}
/// The kept file's JSON, if it is a regular file (not a symlink or FIFO) of a
/// sane size.
fn read_kept(p: &Path) -> io::Result<Value> {
read_kept_limit(p, MAX_FILE)
}
fn read_kept_limit(p: &Path, limit: u64) -> io::Result<Value> {
use std::os::unix::fs::OpenOptionsExt;
// O_NOFOLLOW refuses symlinks; O_NONBLOCK opens a FIFO without waiting for
// a writer so fstat on the open descriptor rejects non-regular files with
// no TOCTOU race.
let f = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
.open(p)?;
if !f.metadata()?.is_file() {
return Err(io::Error::other("not a regular file"));
}
let mut text = Vec::new();
f.take(limit.saturating_add(1)).read_to_end(&mut text)?;
if text.len() as u64 > limit {
return Err(io::Error::other("host-roots.json is too large"));
}
serde_json::from_slice(&text).map_err(io::Error::other)
}
/// The roots kept from the last time, if any: read at start, before the
/// first pull.
pub fn load() {
if !in_wsl() {
return;
}
let Some(p) = path() else { return };
// Never over roots kiri-win has sent this run already (checked atomically
// under the host-roots lock).
if let Ok(v) = read_kept(&p) {
roots::set_host_if_unset(parse(&v));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_lists_kiri_win_sends_and_writes_them_back_the_same() {
let body = json!({"certs": ["3001", 7, "zz"], "distrusted": ["30020a0b"]});
let host = parse(&body);
assert_eq!(host.certs.len(), 1);
assert_eq!(host.distrusted[0].as_ref(), &[0x30, 0x02, 0x0a, 0x0b]);
assert_eq!(to_json(&host), json!({"certs": ["3001"], "distrusted": ["30020a0b"]}));
}
#[test]
fn the_kept_roots_are_private_whatever_the_umask() {
use std::os::unix::fs::PermissionsExt;
const CHILD: &str = "KIRI_TEST_HOSTROOTS_UMASK_DIR";
if let Some(d) = std::env::var_os(CHILD) {
let d = Path::new(&d);
for (i, mask) in [0o000, 0o022, 0o077].into_iter().enumerate() {
let f = d.join(format!("host-roots-{i}.json.tmp"));
// SAFETY: umask only changes this process's file-creation mask,
// and this child process runs this test alone.
unsafe { libc::umask(mask) };
write_private(&f, b"{}").unwrap();
}
return;
}
let d = std::env::temp_dir().join(format!("kiri-hostroots-mode-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let name = "daemon::hostroots::tests::the_kept_roots_are_private_whatever_the_umask";
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", name, "--test-threads=1"])
.env(CHILD, &d)
.output()
.unwrap();
assert!(child.status.success(), "{}", String::from_utf8_lossy(&child.stdout));
for i in 0..3 {
let f = d.join(format!("host-roots-{i}.json.tmp"));
assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600);
}
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn a_fifo_is_not_opened_as_the_kept_roots() {
let d = std::env::temp_dir().join(format!("kiri-hostroots-fifo-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let fifo = d.join("host-roots.json");
assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
assert!(read_kept(&fifo).unwrap_err().to_string().contains("regular"));
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn a_symlink_is_not_followed_when_reading_or_writing_kept_roots() {
use std::os::unix::fs::PermissionsExt;
let d = std::env::temp_dir().join(format!("kiri-hostroots-symlink-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let victim = d.join("victim.json");
std::fs::write(&victim, r#"{"certs":["3001"],"distrusted":[]}"#).unwrap();
let link = d.join("host-roots.json");
let tmp_link = d.join("host-roots.json.tmp");
std::os::unix::fs::symlink(&victim, &link).unwrap();
std::os::unix::fs::symlink(&victim, &tmp_link).unwrap();
// Reading refuses a symlink.
assert!(read_kept(&link).is_err());
// Saving removes the temp symlink and atomically replaces the target
// symlink with a 0600 regular file without modifying the victim.
let host = parse(&json!({"certs": ["3002"], "distrusted": []}));
save_to(&link, &host).unwrap();
assert_eq!(std::fs::read_to_string(&victim).unwrap(), r#"{"certs":["3001"],"distrusted":[]}"#);
let meta = std::fs::symlink_metadata(&link).unwrap();
assert!(meta.file_type().is_file());
assert_eq!(meta.permissions().mode() & 0o777, 0o600);
assert_eq!(parse(&read_kept(&link).unwrap()), host);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn an_oversized_kept_roots_file_is_rejected() {
let d = std::env::temp_dir().join(format!("kiri-hostroots-size-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
let f = d.join("host-roots.json");
std::fs::write(&f, format!(r#"{{"certs":["{}"],"distrusted":[]}}"#, "00".repeat(64))).unwrap();
assert!(read_kept_limit(&f, 64).unwrap_err().to_string().contains("too large"));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn a_body_without_lists_is_no_roots() {
assert_eq!(parse(&json!({})), Host::default());
}
}
+13
View File
@@ -17,6 +17,10 @@ mod engine;
mod filters;
mod health;
mod hostetc;
// A Windows host's roots, for the engine in WSL.
#[cfg(any(target_os = "linux", test))]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
mod hostroots;
mod hostopts;
mod mirror;
mod http;
@@ -308,6 +312,15 @@ pub fn run(_args: &[String]) -> io::Result<()> {
// daemon.json's insecure-registries and registry-mirrors, read again
// whenever the file changes.
kiri_image::set_config_source(daemon_json::current);
// The system's root certificates are read once, here while nothing
// waits for them, and not by the first pull: asking the macOS keychain
// about each of its certificates takes a moment (#303).
let _ = std::thread::Builder::new().name("kiri-tls-roots".into()).spawn(|| {
// In WSL, the Windows roots kiri-win sent last time (#303).
#[cfg(target_os = "linux")]
hostroots::load();
let _ = kiri_image::roots::trusted();
});
// The managed BuildKit stops itself when builds have been idle a while.
builder::watch(engine.clone());
// A Kubernetes node the engine restarted gets its kubectl context.
+4
View File
@@ -1,5 +1,9 @@
//! The `kiri` command.
// Share's roots, aliased at the crate root so its crate::roots::trusted()
// resolves; kiri-win mounts the same file by #[path] instead.
#[cfg(any(unix, windows))]
use kiri_image::roots;
use std::process::ExitCode;
#[cfg(target_os = "macos")]
+105 -6
View File
@@ -401,15 +401,60 @@ fn server(cfg: &Config) -> Server {
Server { host, port, dial }
}
fn tls_config(alpn: &[u8]) -> io::Result<Arc<rustls::ClientConfig>> {
/// Largest `KIRI_SHARE_CA` PEM file accepted (2 MiB) and most certificates
/// read from it, bounding memory even on hostile or misconfigured paths.
const MAX_SHARE_CA_BYTES: u64 = 2 << 20;
const MAX_SHARE_CA_CERTS: usize = 1024;
/// The roots a Share tunnel verifies against: the system's roots merged
/// with webpki's (like the registry client, #303), plus `share_ca`
/// (`KIRI_SHARE_CA`), skipping any certificate rustls refuses to add —
/// the same quiet skip as `platform_certs()` skipping load errors. The
/// merged list comes from places the user doesn't curate (the keychain,
/// `/etc/ssl`), so one anchor rustls won't take shouldn't take every
/// tunnel down. `share_ca`, unlike the merged roots, is chosen on
/// purpose: an explicit CA that doesn't parse is a misconfiguration
/// worth reporting.
fn root_store(
trusted: &[rustls::pki_types::CertificateDer<'static>],
share_ca: Option<&std::path::Path>,
) -> io::Result<rustls::RootCertStore> {
let mut roots = rustls::RootCertStore::empty();
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
if let Some(ca) = std::env::var_os("KIRI_SHARE_CA") {
let certs = rustls::pki_types::CertificateDer::pem_file_iter(&ca).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?;
for c in certs {
roots.add(c.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?;
roots.add_parsable_certificates(trusted.to_vec());
if let Some(ca) = share_ca {
use std::io::Read as _;
let f = std::fs::File::open(ca).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?;
if !f.metadata().map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?.is_file() {
return Err(io::Error::other("KIRI_SHARE_CA: not a regular file"));
}
let mut bytes = Vec::new();
f.take(MAX_SHARE_CA_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?;
if bytes.len() as u64 > MAX_SHARE_CA_BYTES {
return Err(io::Error::other(format!(
"KIRI_SHARE_CA: file exceeds {} MiB",
MAX_SHARE_CA_BYTES >> 20
)));
}
for (i, c) in rustls::pki_types::CertificateDer::pem_slice_iter(&bytes).enumerate() {
if i >= MAX_SHARE_CA_CERTS {
return Err(io::Error::other(format!(
"KIRI_SHARE_CA: more than {MAX_SHARE_CA_CERTS} certificates"
)));
}
roots
.add(c.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?)
.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?;
}
}
Ok(roots)
}
fn tls_config(alpn: &[u8]) -> io::Result<Arc<rustls::ClientConfig>> {
// KIRI_SHARE_CA, if set, is added on top of the merged roots, last.
let share_ca = std::env::var_os("KIRI_SHARE_CA").map(std::path::PathBuf::from);
let roots = root_store(&crate::roots::trusted(), share_ca.as_deref())?;
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut c = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
@@ -2316,6 +2361,60 @@ mod tests {
assert_eq!(parse_server("localhost:"), ("localhost:".into(), 443));
}
/// A malformed anchor in the trusted list is skipped, not fatal: the
/// store still holds every certificate that parses.
#[test]
fn merged_roots_skip_a_cert_that_fails_to_add() {
// The bundled set, not this machine's store: every one of them
// parses, where a store may hold one rustls skips already.
let certs = crate::roots::bundled().to_vec();
let mut with_bad = certs.clone();
let good: &[u8] = certs[0].as_ref();
let bad = rustls::pki_types::CertificateDer::from(good[..good.len() / 2].to_vec());
with_bad.push(bad);
let no_ca = None;
let roots = root_store(&with_bad, no_ca).unwrap();
assert_eq!(
roots.len(),
certs.len(),
"the truncated cert is skipped, the rest land"
);
assert_eq!(roots.len(), with_bad.len() - 1);
}
/// KIRI_SHARE_CA stays loud: a PEM section that doesn't decode fails
/// `root_store` (what `tls_config` builds from the variable), a
/// parseable CA is added and passes. (A file with no PEM sections at
/// all iterates as empty upstream, pki-types 1.15.) `root_store` is
/// called with the file, not through the variable: setting one races
/// every other test reading the environment.
#[test]
fn kiri_share_ca_fails_loud_but_a_valid_ca_is_added() {
let dir = std::env::temp_dir();
let bad = dir.join(format!("kiri-share-ca-bad-{}.pem", std::process::id()));
std::fs::write(
&bad,
"-----BEGIN CERTIFICATE-----\n!!!!\n-----END CERTIFICATE-----\n",
)
.unwrap();
let ca_params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
let key = rcgen::KeyPair::generate().unwrap();
let ca = ca_params.self_signed(&key).unwrap();
let good = dir.join(format!("kiri-share-ca-good-{}.pem", std::process::id()));
std::fs::write(&good, ca.pem()).unwrap();
let oversized = dir.join(format!("kiri-share-ca-big-{}.pem", std::process::id()));
std::fs::write(&oversized, vec![b'A'; MAX_SHARE_CA_BYTES as usize + 1]).unwrap();
let loud = root_store(&[], Some(&bad)).is_err();
let added = root_store(&[], Some(&good)).is_ok_and(|r| r.len() == 1);
let too_big = root_store(&[], Some(&oversized)).is_err();
let _ = std::fs::remove_file(&bad);
let _ = std::fs::remove_file(&good);
let _ = std::fs::remove_file(&oversized);
assert!(loud, "an undecodable KIRI_SHARE_CA fails loudly");
assert!(added, "a parseable KIRI_SHARE_CA is added");
assert!(too_big, "an oversized KIRI_SHARE_CA is refused");
}
#[test]
fn targets() {
assert_eq!(port_or_addr("3000").unwrap().addr, "localhost:3000");
+4 -1
View File
@@ -36,7 +36,10 @@ pub fn lite() -> bool {
pub(crate) fn agent() -> ureq::Agent {
let mut cfg = ureq::Agent::config_builder()
.timeout_connect(Some(Duration::from_secs(15)))
.user_agent(concat!("kiri/", env!("CARGO_PKG_VERSION")));
.user_agent(concat!("kiri/", env!("CARGO_PKG_VERSION")))
// The system's roots merged with webpki's, like the registry client
// (#303); downloads run behind the same corporate proxies.
.tls_config(kiri_image::tls_config(&kiri_image::roots::trusted()));
let e = crate::daemon::proxy::effective();
if let Some(p) = e.https.or(e.http).and_then(|u| ureq::Proxy::new(&u).ok()) {
cfg = cfg.proxy(Some(p));
+16
View File
@@ -72,6 +72,9 @@ fn agent() -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(std::time::Duration::from_secs(10)))
.user_agent(concat!("kiri/", env!("CARGO_PKG_VERSION")))
// The system's roots merged with webpki's, like the registry client
// (#303); the feed often sits behind a corporate proxy's CA.
.tls_config(kiri_image::tls_config(&kiri_image::roots::trusted()))
.build()
.into()
}
@@ -536,6 +539,19 @@ mod tests {
}
}
/// The update agent verifies against the merged roots, every one of
/// them and in order, not the bundled set only (#303).
#[test]
fn the_update_agent_trusts_the_merged_roots() {
let agent = super::agent();
let ureq::tls::RootCerts::Specific(certs) = agent.config().tls_config().root_certs() else {
panic!("the update agent must trust a list of roots of its own");
};
let roots = kiri_image::roots::trusted();
assert_eq!(certs.len(), roots.len());
assert!(certs.iter().zip(roots.iter()).all(|(a, b)| a.der() == b.as_ref()));
}
#[test]
fn compares_versions() {
assert!(newer("0.2.0", "0.1.9"));
+25
View File
@@ -177,6 +177,31 @@ bundles the docker CLI, Compose and buildx; `Kiri-Lite-<version>-arm64.dmg`
versions on first launch (`crates/kiri/src/cli_pins.rs`, checked by SHA-256)
unless the Mac already has a docker CLI.
## Company certificates
Kiri trusts the root certificates of the operating system and the Mozilla set that Kiri bundles. This applies to pulls, pushes, `docker login`, the update check, CLI and grype downloads, and Kiri Share. A registry signed by a company root certificate works when the system trusts that certificate.
- **macOS**: Kiri reads the trust settings of the user, admin and system keychains. Mark the root certificate as trusted, for example: `sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ca.pem`
- **Linux**: Kiri reads the system CA bundle, for example in `/etc/ssl/certs`.
- **Windows**: pulls run in the engine in WSL 2, away from the Windows certificate store, so the Kiri window copies the store into the engine: the root certificates of the current user (which include the machine's and those Group Policy adds) that the bundled set lacks, and the certificates in the Disallowed store (as well as bundled roots disabled for Server Authentication). It sends them when the engine starts and every minute while Kiri runs, and the engine keeps them for its next start. Kiri Share uses the Windows certificate store of the current user. Trust the company root certificate in Windows, for example `certutil -user -addstore Root ca.cer`; pulls trust it within a minute.
A root certificate that an administrator distrusts stays distrusted, even though the bundled Mozilla set has it:
- **macOS**: "Never Trust" in the user or admin trust settings. Settings in the system domain are not read.
- **Windows**: the certificates in the Disallowed store (and bundled roots disabled for Server Authentication in `ROOT`), for Kiri Share and for pulls in the engine (only the engine in WSL accepts Windows roots, and only from Kiri on Windows; a native Linux engine, containers, and other WSL distros are refused). A re-issued copy of a distrusted self-issued root, with the same subject and public key, is distrusted too; a distrusted cross-certificate leaves the self-signed root it shares a key with trusted.
- **Linux**: there is no list of distrusted certificates to read. A Mozilla root certificate that you remove from the system bundle (for example with `!` in `/etc/ca-certificates.conf`) is still trusted through the bundled set.
Kiri does not check online revocation (CRL or OCSP).
NOTE: If `SSL_CERT_FILE` or `SSL_CERT_DIR` is set, Kiri reads the root certificates there instead of the system store, as OpenSSL does. The bundled Mozilla set stays in use, so these variables add root certificates and cannot limit trust to a private CA only. Kiri writes a warning when this occurs, and a company CA trusted in the keychain or system store is then not trusted.
If the system store causes a problem, set `KIRI_TLS_ROOTS=webpki`. Kiri then trusts only the bundled Mozilla set, as before: nothing is read from the system, so the roots an administrator distrusted are trusted again too. The Kiri app and the daemon do not read your shell environment; set the variable for them and restart Kiri:
- **macOS**: `launchctl setenv KIRI_TLS_ROOTS webpki`
- **Linux**: `sudo systemctl edit kiri`, add `Environment=KIRI_TLS_ROOTS=webpki` under `[Service]`, then `sudo systemctl restart kiri`.
To trust a private certificate authority at a Kiri Share edge only, set `KIRI_SHARE_CA` to a PEM file of extra root certificates. Kiri adds them to the trusted roots for that edge only; a file that does not parse is an error, not a silent skip.
## Known issues
- **Mac: an attached USB device leaves your containers while the Mac
+6
View File
@@ -13,6 +13,12 @@ A log of every merged bug fix in Kiri, newest first, together with any later bug
## Fixes
### #303 TLS: trust the system certificate store across macOS, Linux and Windows, respecting distrusted roots and `KIRI_TLS_ROOTS=webpki` (unreleased)
- Fixes: #303 Trust system certificate store (corporate / private CA roots) for image pulls, logins, updates, tool downloads and Share
- Caused: none known
- Caused by: -
- Check: `tls-company-root-pull`, `tls-company-root-login`, `tls-unknown-root-refused`, `crates/kiri-image/src/roots.rs`, `crates/kiri/src/daemon/hostroots.rs`
### #768 Storage & WSL: detect read-only / `emergency_ro` storage filesystems and report actionable recovery steps (unreleased)
- Fixes: #768 Windows (WSL 2) / Linux: when `ext4.vhdx` or `/var/lib/kiri` is remounted read-only (`emergency_ro`), overlayfs mounts container rootfs read-only or daemon startup fails with opaque `EROFS` errors instead of actionable `e2fsck` / storage recovery guidance
- Caused: none known
+22
View File
@@ -0,0 +1,22 @@
# shellcheck shell=sh
# Certificates for the registry checks in tests/linux-host.sh, made in the
# engine's container before the engine starts, as a company root is
# installed before Kiri runs: two roots, each signing a registry's
# certificate (kiri-trusted.test, kiri-other.test). Only the first goes into
# the system's store (/etc/ssl/certs/ca-certificates.crt, where
# update-ca-certificates puts it), so the second stands for a root nobody
# installed. Made once; a restart of the container keeps them.
[ -f /tls/trusted.pem ] && exit 0
command -v openssl >/dev/null || exit 0
mkdir -p /tls && cd /tls || exit 0
for ca in trusted other; do
openssl req -x509 -newkey rsa:2048 -nodes -days 3 -subj "/CN=Kiri test root ($ca)" \
-addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign,cRLSign \
-keyout "$ca-root.key" -out "$ca-root.pem" 2>/dev/null
openssl req -newkey rsa:2048 -nodes -subj "/CN=kiri-$ca.test" -keyout "$ca.key" -out "$ca.csr" 2>/dev/null
printf 'subjectAltName=DNS:kiri-%s.test\nextendedKeyUsage=serverAuth\nbasicConstraints=CA:FALSE\n' "$ca" > "$ca.ext"
openssl x509 -req -in "$ca.csr" -CA "$ca-root.pem" -CAkey "$ca-root.key" -CAcreateserial -days 3 \
-extfile "$ca.ext" -out "$ca.pem" 2>/dev/null
done
chmod 644 ./*.key
cat trusted-root.pem >> /etc/ssl/certs/ca-certificates.crt
+11 -3
View File
@@ -16,7 +16,8 @@ N=${N:-kiri-linux-host}
kiri_seed_images alpine:latest || echo "linux-host: alpine could not be fetched"
$D rm -f "$N" >/dev/null 2>&1
$D run -d --name "$N" --privileged --tmpfs /run -v "$N":/var/lib/kiri -v "$N"-store:/root/.local/share/kiri \
-v "$BIN:/opt/kiri:ro" alpine sh -c 'apk add -q docker-cli curl python3 >/dev/null 2>&1; exec /opt/kiri/kiri daemon' >/dev/null
-v "$BIN:/opt/kiri:ro" -v "$(cd "$(dirname "$0")" && pwd)/lib/registry-certs.sh:/registry-certs.sh:ro" \
alpine sh -c 'apk add -q docker-cli curl python3 openssl >/dev/null 2>&1; sh /registry-certs.sh; exec /opt/kiri/kiri daemon' >/dev/null
# Up to 3 minutes: the container installs its tools with apk first, which can take over a minute.
up() { for _ in $(seq 180); do $D exec "$N" sh -c 'DOCKER_HOST=unix:///root/.kiri/run/docker.sock docker version' >/dev/null 2>&1 && break; sleep 1; done; }
up
@@ -379,11 +380,18 @@ t ij-warning-gone "[]" "docker info --format '{{json .Warnings}}'"
# mirror.
$D exec "$N" sh -c 'grep -q kiri-trusted.test /etc/hosts || echo "$(hostname -i | cut -d" " -f1) kiri-trusted.test kiri-other.test" >> /etc/hosts'
REGS="apk add -q openssl >/dev/null 2>&1; mkdir -p /tls; [ -f /tls/other.pem ] || openssl req -x509 -newkey rsa:2048 -nodes -days 3 -subj /CN=kiri-other.test -addext subjectAltName=DNS:kiri-other.test -keyout /tls/other.key -out /tls/other.pem 2>/dev/null; chmod 644 /tls/other.key
docker rm -f kiri-reg-http kiri-reg-other >/dev/null 2>&1
docker rm -f kiri-reg-http kiri-reg-trusted kiri-reg-other >/dev/null 2>&1
docker run -d --name kiri-reg-http -p 5055:5000 -v kiri-regdata:/var/lib/registry registry:2 >/dev/null
docker run -d --name kiri-reg-other -p 5444:5000 -v kiri-regdata:/var/lib/registry -v /tls:/tls:ro -e REGISTRY_HTTP_TLS_CERTIFICATE=/tls/other.pem -e REGISTRY_HTTP_TLS_KEY=/tls/other.key registry:2 >/dev/null
for ca in trusted:5443 other:5444; do docker run -d --name kiri-reg-\${ca%:*} -p \${ca#*:}:5000 -v kiri-regdata:/var/lib/registry -v /tls:/tls:ro -e REGISTRY_HTTP_TLS_CERTIFICATE=/tls/\${ca%:*}.pem -e REGISTRY_HTTP_TLS_KEY=/tls/\${ca%:*}.key registry:2 >/dev/null; done
for i in \$(seq 60); do curl -s -o /dev/null localhost:5055/v2/ && break; sleep 0.25; done"
t registry-setup "pushed" "$REGS; docker tag alpine:3.21 localhost:5055/team/alp:1 && docker push -q localhost:5055/team/alp:1 >/dev/null && docker rmi localhost:5055/team/alp:1 >/dev/null && echo pushed"
# Registries whose certificate a company root signs (#303). The root went
# into the system's store before the engine started (lib/registry-certs.sh);
# the engine trusts that store as well as its bundled roots, for pulls and
# for docker login, and still refuses a root the system doesn't have.
t tls-company-root-pull "Downloaded newer image" "docker pull kiri-trusted.test:5443/team/alp:1 2>&1"
t tls-company-root-login "Login Succeeded" "echo kiri | docker login kiri-trusted.test:5443 -u kiri --password-stdin 2>&1"
t tls-unknown-root-refused "UnknownIssuer" "docker pull kiri-other.test:5444/team/alp:1 2>&1"
RIP=$($D exec "$N" sh -c 'hostname -i | cut -d" " -f1')
REGAUTH="apk add -q apache2-utils >/dev/null 2>&1; mkdir -p /regauth && htpasswd -Bbn kiriuser kiripass > /regauth/htpasswd
docker rm -f kiri-reg-auth kiri-reg-spare kiri-reg-80 >/dev/null 2>&1; docker run -d --name kiri-reg-spare -p 5057:5000 -v kiri-regdata:/var/lib/registry registry:2 >/dev/null; docker run -d --name kiri-reg-auth -p 5056:5000 -v kiri-regdata:/var/lib/registry -v /regauth:/auth:ro -e REGISTRY_AUTH=htpasswd -e REGISTRY_AUTH_HTPASSWD_REALM=kiri -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd registry:2 >/dev/null
+5
View File
@@ -337,3 +337,8 @@ bind-nonroot-ro #796 non-root writes to a read-only 0444 bind-mount file must st
crates/kiri/src/daemon/rofs.rs #768 when Kiri's WSL 2 ext4.vhdx or Linux storage filesystem was remounted read-only (emergency_ro), daemon startup, /info and diagnostics lacked actionable fsck / storage recovery steps
crates/kiri-init/src/linux/sys.rs #768 on a read-only or emergency_ro storage filesystem, overlayfs silently mounted writable container rootfs read-only instead of refusing with actionable recovery steps
crates/kiri-win/src/wslsync.rs #768 kiri-start and kiri-win reported a generic WSL install failure instead of ext4.vhdx emergency_ro e2fsck recovery steps when Kiri's WSL 2 disk was remounted read-only
tls-company-root-pull #303 a registry signed by a root the system trusts failed UnknownIssuer: only the bundled roots were trusted
tls-company-root-login #303 docker login to a registry signed by a root the system trusts failed UnknownIssuer
tls-unknown-root-refused #303 a root the system does not trust must still be refused
crates/kiri-image/src/roots.rs #303 root store merge, system distrust filtering (macOS Never Trust, Windows Disallowed and disabled Server Auth EKU), cross-cert preservation, caps, and KIRI_TLS_ROOTS=webpki escape hatch
crates/kiri/src/daemon/hostroots.rs #303 Windows host roots persistence in WSL must enforce Caller::Host, 0600 atomic writes, non-symlink/non-FIFO reads, and bounded sizes
Can't render this file because it contains an unexpected character in line 2 and column 52.