Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion crates/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
9 changes: 7 additions & 2 deletions crates/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down Expand Up @@ -83,14 +83,19 @@ 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`.
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"]

Expand Down
2 changes: 1 addition & 1 deletion crates/lib/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2460,7 +2460,7 @@ async fn run_from_opt(opt: Opt) -> Result<CliExitStatus> {
}
},
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");
Expand Down
7 changes: 7 additions & 0 deletions crates/lib/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions crates/lib/src/install/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
56 changes: 56 additions & 0 deletions crates/lib/src/lsm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,58 @@ 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<CString> {
let context =
selinux::SecurityContext::of_initial_kernel_context(SELINUX_INITIAL_SID_UNLABELED, true)
.context("Querying the SELinux unlabeled initial context")?;
context_type(context.as_bytes())
}

#[cfg(not(feature = "selinux"))]
fn unlabeled_type() -> Result<CString> {
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
Expand Down Expand Up @@ -290,6 +324,7 @@ pub(crate) enum SELinuxLabelState {
Labeled,
}

#[cfg(feature = "selinux")]
fn context_type(context: &[u8]) -> Result<CString> {
// security.selinux xattrs may include a trailing NUL terminator.
let context = context.strip_suffix(b"\0").unwrap_or(context);
Expand All @@ -303,6 +338,11 @@ fn context_type(context: &[u8]) -> Result<CString> {
.context("Reading SELinux context type")
}

#[cfg(not(feature = "selinux"))]
fn context_type(_context: &[u8]) -> Result<CString> {
anyhow::bail!(SELINUX_NOT_BUILT)
}

/// Query the SELinux labeling for a particular path
pub(crate) fn has_security_selinux(root: &Dir, path: &Utf8Path) -> Result<SELinuxLabelState> {
let unlabeled_type = unlabeled_type()?;
Expand Down Expand Up @@ -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")),
Expand Down
30 changes: 20 additions & 10 deletions crates/xtask/src/man.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CliCommand> {
pub fn extract_cli_json(sh: &Shell, no_default_features: bool) -> Result<CliCommand> {
// If we have a release binary, assume that we should compile
// in release mode as hopefully we'll have incremental compilation
// enabled.
Expand All @@ -63,9 +66,16 @@ pub fn extract_cli_json(sh: &Shell) -> Result<CliCommand> {
.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")?;
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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");

Expand All @@ -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()?;
Expand Down Expand Up @@ -527,7 +537,7 @@ fn get_package_version() -> Result<String> {
/// 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;
Expand Down Expand Up @@ -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!("");
Expand All @@ -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<String>, acc: &mut Vec<Vec<String>>) {
Expand Down
10 changes: 8 additions & 2 deletions crates/xtask/src/xtask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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 {
Expand Down
16 changes: 16 additions & 0 deletions docs/src/packaging-and-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading