diff --git a/Makefile b/Makefile index 5577e9b0a5..e4baf2e02b 100644 --- a/Makefile +++ b/Makefile @@ -40,16 +40,27 @@ CARGO_FEATURES_DEFAULT ?= $(shell . /usr/lib/os-release; \ echo $$features) # You can set this to override all cargo features, including the defaults CARGO_FEATURES ?= $(CARGO_FEATURES_DEFAULT) +# Set to 1 to build without the crates' default features, such as `selinux` +# (which links libselinux). Re-enable the ones you want via CARGO_FEATURES, +# e.g. `make CARGO_NO_DEFAULT_FEATURES=1 CARGO_FEATURES="install-to-disk pre-6.15"`. +# Note this applies to every crate in the workspace, so it also drops e.g. +# the initramfs crate's default `pre-6.15` unless it is listed again. +# It only affects `bin` and `manpages`; the unit test targets +# (install-unit-tests) still build with the default features and need +# libselinux. +CARGO_NO_DEFAULT_FEATURES ?= +CARGO_NO_DEFAULT_FEATURES_ARG = $(if $(filter 1,$(CARGO_NO_DEFAULT_FEATURES)),--no-default-features) # Build all binaries .PHONY: bin bin: manpages - cargo build --release --features "$(CARGO_FEATURES)" --bins + cargo build --release $(CARGO_NO_DEFAULT_FEATURES_ARG) --features "$(CARGO_FEATURES)" --bins -# Note this cargo build is run without features (such as rhsm) +# Note this build doesn't use CARGO_FEATURES (such as rhsm); the man pages +# document the full CLI regardless. .PHONY: manpages manpages: - cargo run --release --package xtask -- manpages + cargo run --release --package xtask -- manpages $(CARGO_NO_DEFAULT_FEATURES_ARG) .PHONY: completion completion: bin @@ -130,6 +141,8 @@ validate: cargo test --no-run (cd crates/ostree-ext && cargo check --no-default-features) (cd crates/lib && cargo check --no-default-features) + (cd crates/cli && cargo check --no-default-features) + cargo test -p bootc-lib --no-default-features --no-run cargo clippy -- $(CLIPPY_CONFIG) env RUSTDOCFLAGS='-D warnings' cargo doc --workspace --no-deps --document-private-items .PHONY: validate diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index fe1e78cc5c..89818ca2b7 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -15,7 +15,7 @@ platforms = ["*-unknown-linux-gnu"] [dependencies] # Internal crates -bootc-lib = { version = "1.16", path = "../lib" } +bootc-lib = { version = "1.16", path = "../lib", default-features = false } bootc-utils = { package = "bootc-internal-utils", path = "../utils", version = "1.16.14" } # Workspace dependencies @@ -25,5 +25,12 @@ log = { workspace = true } tokio = { workspace = true, features = ["macros"] } tracing = { workspace = true } +[features] +# Forward bootc-lib's defaults (it's a dependency without default features), so +# that `--no-default-features` works for the binary too. +default = ["bootc-lib/default"] +install-to-disk = ["bootc-lib/install-to-disk"] +selinux = ["bootc-lib/selinux"] + [lints] workspace = true diff --git a/crates/lib/Cargo.toml b/crates/lib/Cargo.toml index 27b12759cd..8723193eba 100644 --- a/crates/lib/Cargo.toml +++ b/crates/lib/Cargo.toml @@ -51,7 +51,7 @@ regex = { workspace = true } rustix = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } -selinux = { workspace = true } +selinux = { workspace = true, optional = true } tempfile = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["io-std", "time", "process", "rt", "net"] } @@ -83,7 +83,7 @@ static_assertions = { workspace = true } tokio = { workspace = true, features = ["test-util"] } [features] -default = ["install-to-disk"] +default = ["install-to-disk", "selinux"] # This feature enables `bootc install to-disk`, which is considered just a "demo" # or reference installer; we expect most nontrivial use cases to be using # `bootc install to-filesystem`. @@ -91,6 +91,11 @@ install-to-disk = [] # This featuares enables `bootc internals publish-rhsm-facts` to integrate with # Red Hat Subscription Manager rhsm = [] +# Link to libselinux to query the SELinux state and to recognize `unlabeled_t` +# files when relabeling. Without it bootc still detects an enabled SELinux via +# selinuxfs, but relabeling then fails, so only turn it off for systems that do +# not use SELinux at all. +selinux = ["dep:selinux"] # Implementation detail of man page generation. docgen = ["clap_mangen"] diff --git a/crates/lib/src/cli.rs b/crates/lib/src/cli.rs index bc11e07e2d..3e551f2f70 100644 --- a/crates/lib/src/cli.rs +++ b/crates/lib/src/cli.rs @@ -2460,7 +2460,7 @@ async fn run_from_opt(opt: Opt) -> Result { } }, InternalsOpts::Selinux(SelinuxOpts::IsUnlabeled { path }) => { - ensure!(crate::lsm::selinux_enabled(), "SELinux is not enabled"); + crate::lsm::require_selinux_enabled()?; let path = path .strip_prefix("/") .expect("absolute paths have a root prefix"); diff --git a/crates/lib/src/install.rs b/crates/lib/src/install.rs index 38866768f6..8025d88e92 100644 --- a/crates/lib/src/install.rs +++ b/crates/lib/src/install.rs @@ -1448,6 +1448,12 @@ pub(crate) fn reexecute_self_for_selinux_if_needed( println!("notice: Target has SELinux enabled, overriding to disable"); SELinuxFinalState::ForceTargetDisabled } else if host_selinux { + // Labeling the target needs libselinux (e.g. to detect unlabeled_t + // content), so fail before touching the disk rather than partway + // through the install. + crate::lsm::require_selinux_built().context( + "Target image and host have SELinux enabled; use --disable-selinux to install without it", + )?; // /sys/fs/selinuxfs is not normally mounted, so we do that now. // Because SELinux enablement status is cached process-wide and was very likely // already queried by something else (e.g. glib's constructor), we would also need @@ -3048,6 +3054,7 @@ mod tests { use super::*; #[test] + #[cfg(feature = "install-to-disk")] fn install_opts_serializable() { let c: InstallToDiskOpts = serde_json::from_value(serde_json::json!({ "device": "/dev/vda" diff --git a/crates/lib/src/install/config.rs b/crates/lib/src/install/config.rs index 7f123e45f2..55fdd42f98 100644 --- a/crates/lib/src/install/config.rs +++ b/crates/lib/src/install/config.rs @@ -454,6 +454,7 @@ type = "xfs" } #[test] + #[cfg(feature = "install-to-disk")] fn test_parse_block() { let env = EnvProperties { sys_arch: "x86_64".to_string(), diff --git a/crates/lib/src/lsm.rs b/crates/lib/src/lsm.rs index 38458f2ad0..f88ad97543 100644 --- a/crates/lib/src/lsm.rs +++ b/crates/lib/src/lsm.rs @@ -25,9 +25,13 @@ const SELINUXFS: &str = "/sys/fs/selinux"; /// The SELinux xattr const SELINUX_XATTR: &[u8] = b"security.selinux\0"; /// The kernel initial SID used for objects without a label. +#[cfg(feature = "selinux")] const SELINUX_INITIAL_SID_UNLABELED: &str = "unlabeled"; const SELF_CURRENT: &str = "/proc/self/attr/current"; +/// Error message for operations which require libselinux. +const SELINUX_NOT_BUILT: &str = "bootc was built without SELinux support (the `selinux` feature)"; +#[cfg(feature = "selinux")] fn unlabeled_type() -> Result { let context = selinux::SecurityContext::of_initial_kernel_context(SELINUX_INITIAL_SID_UNLABELED, true) @@ -35,14 +39,44 @@ fn unlabeled_type() -> Result { context_type(context.as_bytes()) } +#[cfg(not(feature = "selinux"))] +fn unlabeled_type() -> Result { + anyhow::bail!(SELINUX_NOT_BUILT) +} + /// Whether SELinux is enabled for the current process. /// /// libselinux caches this state process-wide, so mounting selinuxfs requires a /// re-exec before this result can change. +#[cfg(feature = "selinux")] pub(crate) fn selinux_enabled() -> bool { selinux::kernel_support() != selinux::KernelSupport::Unsupported } +/// Without libselinux, check for a mounted selinuxfs directly (like +/// [`ostree_ext::selinux::is_selinux_enabled`]), so that a build without the +/// `selinux` feature still notices SELinux on the host: it then enters +/// install_t and checks policy compatibility as usual, and operations that +/// need libselinux (such as detecting `unlabeled_t` when relabeling) fail +/// instead of silently doing the wrong thing. +#[cfg(not(feature = "selinux"))] +pub(crate) fn selinux_enabled() -> bool { + Path::new(SELINUXFS).join("enforce").exists() +} + +/// Return an error unless bootc was built with the `selinux` feature. +pub(crate) fn require_selinux_built() -> Result<()> { + anyhow::ensure!(cfg!(feature = "selinux"), SELINUX_NOT_BUILT); + Ok(()) +} + +/// Return an error unless SELinux is enabled for the current process. +pub(crate) fn require_selinux_enabled() -> Result<()> { + require_selinux_built()?; + anyhow::ensure!(selinux_enabled(), "SELinux is not enabled"); + Ok(()) +} + /// Whether SELinux is enabled on the host, as observed from PID 1's mount namespace. /// /// This bypasses libselinux's process-cached state and is only appropriate while @@ -290,6 +324,7 @@ pub(crate) enum SELinuxLabelState { Labeled, } +#[cfg(feature = "selinux")] fn context_type(context: &[u8]) -> Result { // security.selinux xattrs may include a trailing NUL terminator. let context = context.strip_suffix(b"\0").unwrap_or(context); @@ -303,6 +338,11 @@ fn context_type(context: &[u8]) -> Result { .context("Reading SELinux context type") } +#[cfg(not(feature = "selinux"))] +fn context_type(_context: &[u8]) -> Result { + anyhow::bail!(SELINUX_NOT_BUILT) +} + /// Query the SELinux labeling for a particular path pub(crate) fn has_security_selinux(root: &Dir, path: &Utf8Path) -> Result { let unlabeled_type = unlabeled_type()?; @@ -645,6 +685,22 @@ mod tests { } #[test] + #[cfg(not(feature = "selinux"))] + fn test_selinux_not_built() { + let enforce = Path::new(SELINUXFS).join("enforce"); + assert_eq!(selinux_enabled(), enforce.exists()); + for err in [ + require_selinux_built().unwrap_err(), + require_selinux_enabled().unwrap_err(), + unlabeled_type().unwrap_err(), + context_type(b"system_u:object_r:var_t:s0").unwrap_err(), + ] { + assert_eq!(err.to_string(), SELINUX_NOT_BUILT); + } + } + + #[test] + #[cfg(feature = "selinux")] fn test_context_type() { let cases: &[(&[u8], Option<&str>)] = &[ (b"system_u:object_r:unlabeled_t:s0", Some("unlabeled_t")), diff --git a/crates/xtask/src/man.rs b/crates/xtask/src/man.rs index b41565c407..3e2af66423 100644 --- a/crates/xtask/src/man.rs +++ b/crates/xtask/src/man.rs @@ -52,9 +52,12 @@ pub struct CliPositional { pub multiple: bool, } -/// Extract CLI structure by running the JSON dump command +/// Extract CLI structure by running the JSON dump command. +/// +/// With `no_default_features`, bootc is built without its default cargo +/// features, e.g. so that it doesn't need libselinux. #[context("Extracting CLI")] -pub fn extract_cli_json(sh: &Shell) -> Result { +pub fn extract_cli_json(sh: &Shell, no_default_features: bool) -> Result { // If we have a release binary, assume that we should compile // in release mode as hopefully we'll have incremental compilation // enabled. @@ -63,9 +66,16 @@ pub fn extract_cli_json(sh: &Shell) -> Result { .try_exists() .context("Querying release bin")? .then_some("--release"); + // Even without default features, keep install-to-disk: it has no extra + // build dependencies, and the man pages document the full CLI. + let features: &[&str] = if no_default_features { + &["--no-default-features", "--features=docgen,install-to-disk"] + } else { + &["--features=docgen"] + }; let json_output = cmd!( sh, - "cargo run {release...} --features=docgen -- internals dump-cli-json" + "cargo run {release...} {features...} -- internals dump-cli-json" ) .read() .context("Running CLI JSON dump command")?; @@ -380,8 +390,8 @@ fn find_command_path_for_filename( /// Sync all man pages with their corresponding CLI commands #[context("Syncing man pages")] -pub fn sync_all_man_pages(sh: &Shell) -> Result<()> { - let cli_structure = extract_cli_json(sh)?; +pub fn sync_all_man_pages(sh: &Shell, no_default_features: bool) -> Result<()> { + let cli_structure = extract_cli_json(sh, no_default_features)?; // Discover man page files automatically let mappings = discover_man_page_mappings(&cli_structure)?; @@ -432,7 +442,7 @@ pub fn sync_all_man_pages(sh: &Shell) -> Result<()> { /// Generate man pages from hand-written markdown sources #[context("Generating manpages")] -pub fn generate_man_pages(sh: &Shell) -> Result<()> { +pub fn generate_man_pages(sh: &Shell, no_default_features: bool) -> Result<()> { let man_src_dir = Utf8Path::new("docs/src/man"); let man_output_dir = Utf8Path::new("target/man"); @@ -441,7 +451,7 @@ pub fn generate_man_pages(sh: &Shell) -> Result<()> { .with_context(|| format!("Creating {man_output_dir}"))?; // First, sync the markdown files with current CLI options - sync_all_man_pages(sh)?; + sync_all_man_pages(sh, no_default_features)?; // Get version for replacement during generation let version = get_package_version()?; @@ -527,7 +537,7 @@ fn get_package_version() -> Result { /// Single command to update all man pages - auto-discover new commands and sync existing ones pub fn update_manpages(sh: &Shell) -> Result<()> { println!("Discovering CLI structure..."); - let cli_structure = extract_cli_json(sh)?; + let cli_structure = extract_cli_json(sh, false)?; println!("Checking for missing man pages..."); let mut created_count = 0; @@ -634,7 +644,7 @@ TODO: Add practical examples showing how to use this command. } println!("Syncing OPTIONS sections..."); - sync_all_man_pages(sh)?; + sync_all_man_pages(sh, false)?; println!("Man pages updated."); println!(""); @@ -649,7 +659,7 @@ TODO: Add practical examples showing how to use this command. /// Fails with an error if any file would change, similar to `cargo fmt --check`. #[context("Checking man pages")] pub fn check_manpages(sh: &Shell) -> Result<()> { - let cli_structure = extract_cli_json(sh)?; + let cli_structure = extract_cli_json(sh, false)?; // First: check no man pages are missing fn collect_commands(cmd: &CliCommand, path: Vec, acc: &mut Vec>) { diff --git a/crates/xtask/src/xtask.rs b/crates/xtask/src/xtask.rs index 5a55b45ea7..9fbb71180a 100644 --- a/crates/xtask/src/xtask.rs +++ b/crates/xtask/src/xtask.rs @@ -69,7 +69,11 @@ struct Cli { #[derive(Debug, Subcommand)] enum Commands { /// Generate man pages - Manpages, + Manpages { + /// Build bootc without its default cargo features (e.g. `selinux`) + #[arg(long)] + no_default_features: bool, + }, /// Update or check generated files UpdateGenerated { #[command(subcommand)] @@ -367,7 +371,9 @@ fn try_main() -> Result<()> { let sh = xshell::Shell::new()?; match cli.command { - Commands::Manpages => man::generate_man_pages(&sh), + Commands::Manpages { + no_default_features, + } => man::generate_man_pages(&sh, no_default_features), Commands::UpdateGenerated { command } => match command { UpdateGeneratedCommands::Direct { check } => { if check { diff --git a/docs/src/packaging-and-integration.md b/docs/src/packaging-and-integration.md index 0ab936c549..3bad0c4600 100644 --- a/docs/src/packaging-and-integration.md +++ b/docs/src/packaging-and-integration.md @@ -105,6 +105,22 @@ To explicitly control features: make all CARGO_FEATURES="rhsm" ``` +The `selinux` feature is enabled by default and links against libselinux. +Distributions that do not use SELinux (and may not ship libselinux) can +build without the default features and add back the others they want +(`pre-6.15` is only needed to boot composefs systems on kernels older +than 6.15). Such a build still detects an enabled SELinux via selinuxfs, +but operations that need libselinux, such as relabeling files that are +`unlabeled_t`, then fail, so only do this for systems without SELinux: + +```bash +make bin CARGO_NO_DEFAULT_FEATURES=1 CARGO_FEATURES="install-to-disk pre-6.15" +``` + +Note that libostree may still link libselinux itself, depending on how it +was built, and that the unit test targets (`make install-unit-tests`) always +use the default features. + ## Integration Testing For distributions that want to include integration tests, use: