From 5b138f24a66e64a608320a4d7322bc82aefe19c0 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:52:26 -0300 Subject: [PATCH 01/91] refactor(xcat-core): move the xcatconfig SELinux decision into a module xcatconfig held the SELinux decision inline and read the state with xCAT::Utils->isSELINUX, so no unit test can reach it. The script has no sub API. xCAT::SELinux now reports the runtime mode and the mode that /etc/selinux/config selects, and xcatconfig_action returns what xcatconfig must do about it. xcatconfig applies that answer. The behavior does not change: a node with SELinux enabled still gets the permissive write and the /etc/selinux/config rewrite. runtime_mode reads the selinuxfs enforce file instead of running selinuxenabled. Both report SELinux as enabled when selinuxfs is mounted. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 137 ++++++++++++++++++++++++++++++++++++ xCAT-server/sbin/xcatconfig | 27 +++---- 2 files changed, 147 insertions(+), 17 deletions(-) create mode 100644 perl-xCAT/xCAT/SELinux.pm diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm new file mode 100644 index 0000000000..f158f21ec8 --- /dev/null +++ b/perl-xCAT/xCAT/SELinux.pm @@ -0,0 +1,137 @@ +# IBM(c) 2026 EPL license http://www.eclipse.org/legal/epl-v10.html +package xCAT::SELinux; + +use strict; +use warnings; + +# selinuxfs is at /sys/fs/selinux. /selinux is the path a kernel before 2.6.37 uses. +our @ENFORCE_FILES = ('/sys/fs/selinux/enforce', '/selinux/enforce'); +our $CONFIG_FILE = '/etc/selinux/config'; + +#----------------------------------------------------------------------------- + +=head3 runtime_mode + + Descriptions: + Reports the SELinux mode of the running system. + Arguments: + root - a prefix for the paths this module reads. The default is the + empty string, which reads the real system. + Returns: + 'enforcing' - selinuxfs reports enforcing + 'permissive' - selinuxfs reports permissive + 'enabled' - selinuxfs is there and the mode is not readable + 'disabled' - selinuxfs is not there, so SELinux is off + Example: + my $mode = xCAT::SELinux->runtime_mode(); + +=cut + +#----------------------------------------------------------------------------- +sub runtime_mode { + my ($class, %args) = @_; + my $root = defined $args{root} ? $args{root} : ''; + + foreach my $path (@ENFORCE_FILES) { + my $value = _first_line("$root$path"); + next unless defined $value; + $value =~ s/\s+//g; + return 'enforcing' if $value eq '1'; + return 'permissive' if $value eq '0'; + return 'enabled'; + } + + return 'disabled'; +} + +#----------------------------------------------------------------------------- + +=head3 config_mode + + Descriptions: + Reports the mode that /etc/selinux/config selects for the next boot. + Arguments: + root - a prefix for the paths this module reads. + Returns: + The lower case value of the last SELINUX= line, or undef when the file + has no such line and when the file is not there. + Example: + my $mode = xCAT::SELinux->config_mode(); + +=cut + +#----------------------------------------------------------------------------- +sub config_mode { + my ($class, %args) = @_; + my $root = defined $args{root} ? $args{root} : ''; + + my $mode; + open(my $fh, '<', "$root$CONFIG_FILE") or return undef; + while (my $line = <$fh>) { + next if $line =~ /^\s*#/; + $mode = lc($1) if $line =~ /^\s*SELINUX\s*=\s*(\S+)/; + } + close($fh); + + return $mode; +} + +#----------------------------------------------------------------------------- + +=head3 xcatconfig_action + + Descriptions: + Decides what xcatconfig does about SELinux on this node. The caller + makes the changes the answer asks for. + Arguments: + root - a prefix for the paths this module reads. + Returns: + A hash reference: + mode - the mode runtime_mode reports + config_mode - the mode config_mode reports + warning - a message for the admin, or undef + disable - true when xcatconfig must turn SELinux off + enforce_file - the selinuxfs file that sets the running mode + Example: + my $answer = xCAT::SELinux->xcatconfig_action(); + +=cut + +#----------------------------------------------------------------------------- +sub xcatconfig_action { + my ($class, %args) = @_; + my $root = defined $args{root} ? $args{root} : ''; + + my $mode = $class->runtime_mode(root => $root); + my %answer = ( + mode => $mode, + config_mode => $class->config_mode(root => $root), + warning => undef, + disable => 0, + enforce_file => undef, + ); + + return \%answer if $mode eq 'disabled'; + + $answer{warning} = 'SELINUX is not disabled, disabling it now...'; + $answer{disable} = 1; + foreach my $path (@ENFORCE_FILES) { + next unless -f "$root$path"; + $answer{enforce_file} = $path; + last; + } + + return \%answer; +} + +sub _first_line { + my ($path) = @_; + + open(my $fh, '<', $path) or return undef; + my $line = <$fh>; + close($fh); + + return $line; +} + +1; diff --git a/xCAT-server/sbin/xcatconfig b/xCAT-server/sbin/xcatconfig index 81010a53cb..ab1f69fcf8 100755 --- a/xCAT-server/sbin/xcatconfig +++ b/xCAT-server/sbin/xcatconfig @@ -28,6 +28,7 @@ use xCAT::DHCP::Backend; use xCAT::DHCP::OmapiPolicy; use xCAT::TLSPolicy qw(tls_setting_warnings); use xCAT::NetworkUtils; +use xCAT::SELinux; use Getopt::Long; use xCAT::MsgUtils; use xCAT::Table; @@ -509,27 +510,19 @@ if ($::INITIALINSTALL || $::FORCE) if (-f "/etc/redhat-release" || -f "/etc/openEuler-release") { - my $rc = xCAT::Utils->isSELINUX(); - - # rc 0 means SELinux is enabled - # rc 1 means SELinux is not enabled - if ($rc == 0) + my $selinux = xCAT::SELinux->xcatconfig_action(); + if ($selinux->{warning}) + { + xCAT::MsgUtils->message('W', $selinux->{warning}); + } + if ($selinux->{disable}) { - xCAT::MsgUtils->message('W', "SELINUX is not disabled, disabling it now..."); - # set selinux be in permissive mode for running system, # if the user forgot to disable selinux, # try to not hurt xcat too much - my $enforcefile; - if (-f "/selinux/enforce") + if ($selinux->{enforce_file}) { - $enforcefile = "/selinux/enforce"; - } elsif (-f "/sys/fs/selinux/enforce") { - $enforcefile = "/sys/fs/selinux/enforce"; - } - if ($enforcefile) - { - my $cmd = "echo 0 > $enforcefile"; + my $cmd = "echo 0 > $selinux->{enforce_file}"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { @@ -538,7 +531,7 @@ if ($::INITIALINSTALL || $::FORCE) } # Disable selinux through reboots - my $cmd = "sed -i 's/^SELINUX=.*\$/SELINUX=disabled/' /etc/selinux/config"; + my $cmd = "sed -i 's/^SELINUX=.*\$/SELINUX=disabled/' $xCAT::SELinux::CONFIG_FILE"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { From d5a162cc11115def2ba4d757061f546b86f91d2a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:54:49 -0300 Subject: [PATCH 02/91] test(xcat-core): measure what xcatconfig does to the SELinux policy of a node xcatconfig turns SELinux off during an installation. It sets the running system permissive and writes SELINUX=disabled into /etc/selinux/config. A management node therefore loses the SELinux policy of the site, and only a warning in the log reports it. Every CI cell that declares SELINUX=enforcing ran its test cases permissive for this reason. The test drives xCAT::SELinux->xcatconfig_action against a scratch root and asserts that an enforcing node, a permissive node and a node with SELinux already off all get an answer that asks for no change. It also asserts that the call rewrites no file under that root. 10 of the 27 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcatconfig_selinux_policy.t | 160 +++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 xCAT-test/unit/xcatconfig_selinux_policy.t diff --git a/xCAT-test/unit/xcatconfig_selinux_policy.t b/xCAT-test/unit/xcatconfig_selinux_policy.t new file mode 100644 index 0000000000..8964bc6ceb --- /dev/null +++ b/xCAT-test/unit/xcatconfig_selinux_policy.t @@ -0,0 +1,160 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use File::Find; +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use File::Temp qw(tempdir); +use Test::More; + +use xCAT::SELinux; + +# An xCAT installation must not change the SELinux policy of the node. xcatconfig +# used to set the running system permissive and write SELINUX=disabled into +# /etc/selinux/config, so every CI cell that declared SELINUX=enforcing ran its +# test cases permissive. + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'the module under test comes from this checkout, not from /opt/xcat'); + +# Builds a scratch root that holds the files the module reads. +sub selinux_root { + my (%args) = @_; + + my $root = tempdir(CLEANUP => 1); + if (defined $args{enforce}) { + my $path = defined $args{enforce_path} ? $args{enforce_path} : '/sys/fs/selinux/enforce'; + my ($dir) = $path =~ m{^(.*)/[^/]+$}; + make_path("$root$dir"); + write_text("$root$path", $args{enforce}); + } + if (defined $args{config}) { + make_path("$root/etc/selinux"); + write_text("$root/etc/selinux/config", $args{config}); + } + + return $root; +} + +# Every file under $root, with its contents, so a caller can prove the module +# wrote nothing. +sub tree_contents { + my ($root) = @_; + + my %contents; + find({ + no_chdir => 1, + wanted => sub { + return unless -f $File::Find::name; + my $relative = substr($File::Find::name, length($root)); + $contents{$relative} = read_text($File::Find::name); + }, + }, $root); + + return \%contents; +} + +my $CONFIG = "SELINUX=enforcing\nSELINUXTYPE=targeted\n"; + +# An enforcing node keeps enforcing. +{ + my $root = selinux_root(enforce => "1\n", config => $CONFIG); + my $before = tree_contents($root); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'enforcing', 'an enforcing node is reported as enforcing'); + is($answer->{config_mode}, 'enforcing', '... and the config mode is enforcing'); + is_deeply([ sort keys %{$answer} ], [ qw(config_mode mode warning) ], + '... and the answer asks for no change, so it carries only the state and a warning'); + like($answer->{warning}, qr/^SELINUX is enforcing\./, + '... and the warning names the mode the node is in'); + like($answer->{warning}, qr/\Qdoes not change the SELinux mode\E/, + '... and the warning says xCAT leaves the mode alone'); + unlike($answer->{warning}, qr/disabl/i, + '... and the warning does not announce a disable'); + is_deeply(tree_contents($root), $before, + '... and /etc/selinux/config and the enforce file are not rewritten'); +} + +# A permissive node stays permissive. xcatconfig must not write the enforce file. +{ + my $root = selinux_root(enforce => "0\n", config => "SELINUX=permissive\n"); + my $before = tree_contents($root); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'permissive', 'a permissive node is reported as permissive'); + is($answer->{config_mode}, 'permissive', '... and the config mode is permissive'); + is_deeply([ sort keys %{$answer} ], [ qw(config_mode mode warning) ], + '... and the answer asks for no change'); + like($answer->{warning}, qr/^SELINUX is permissive\./, + '... and the warning names the permissive mode'); + unlike($answer->{warning}, qr/disabl/i, + '... and the warning does not announce a disable'); + is_deeply(tree_contents($root), $before, + '... and nothing under the scratch root is rewritten'); +} + +# A node that already has SELinux off behaves as it did: no warning, no change. +{ + my $root = selinux_root(config => "SELINUX=disabled\n"); + my $before = tree_contents($root); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'disabled', 'a node without selinuxfs is reported as disabled'); + is($answer->{config_mode}, 'disabled', '... and the config mode is disabled'); + is($answer->{warning}, undef, '... and a disabled node gets no warning'); + is_deeply([ sort keys %{$answer} ], [ qw(config_mode mode warning) ], + '... and the answer asks for no change'); + is_deeply(tree_contents($root), $before, + '... and /etc/selinux/config is not rewritten'); +} + +# selinuxfs with a value that is neither 0 nor 1 still means SELinux is on. +{ + my $root = selinux_root(enforce => "unknown\n", config => $CONFIG); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'enabled', 'an unreadable enforce value is reported as enabled'); + like($answer->{warning}, qr/^SELINUX is enabled\./, '... and the warning names that state'); + is_deeply([ sort keys %{$answer} ], [ qw(config_mode mode warning) ], + '... and the answer asks for no change'); +} + +# The pre-2.6.37 selinuxfs mount point is read as well. +{ + my $root = selinux_root( + enforce => "1\n", + enforce_path => '/selinux/enforce', + config => $CONFIG, + ); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'enforcing', 'the legacy /selinux/enforce path reports enforcing'); +} + +# A node with no /etc/selinux/config reports no config mode, and the file stays absent. +{ + my $root = selinux_root(enforce => "1\n"); + my $answer = xCAT::SELinux->xcatconfig_action(root => $root); + + is($answer->{mode}, 'enforcing', 'the runtime mode is read without /etc/selinux/config'); + is($answer->{config_mode}, undef, '... and a missing config file has no mode'); + ok(!-e "$root/etc/selinux/config", '... and the missing config file is not created'); +} + +# A commented SELINUX line is not the setting. +{ + my $root = selinux_root( + enforce => "0\n", + config => "# SELINUX=enforcing\nSELINUX=permissive\n", + ); + + is(xCAT::SELinux->config_mode(root => $root), 'permissive', + 'a commented SELINUX line is ignored'); +} + +done_testing(); From e6ba4e4be11eebb61da2f40cc19f7b7ff587a9f6 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:56:06 -0300 Subject: [PATCH 03/91] fix(xcat-core): an xCAT installation turns off the SELinux policy of the node xcatconfig set the running system permissive and wrote SELINUX=disabled into /etc/selinux/config on a Red Hat or openEuler management node. The node lost the SELinux policy of the site during the installation, and the log reported only a warning. Every CI cell that declares SELINUX=enforcing ran its test cases permissive for this reason, and two measurements needed setenforce 1 after the install to get an enforcing node. xCAT::SELinux->xcatconfig_action now returns the mode and asks for no change. xcatconfig reports the mode and leaves the running system and /etc/selinux/config alone. A node that already has SELinux off gets no warning, as before. xCAT-test/unit/xcatconfig_selinux_policy.t fails 10 of its 27 checks on the parent commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 30 +++++++++++------------------- xCAT-server/sbin/xcatconfig | 23 ----------------------- 2 files changed, 11 insertions(+), 42 deletions(-) diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm index f158f21ec8..64c3c1fb7e 100644 --- a/perl-xCAT/xCAT/SELinux.pm +++ b/perl-xCAT/xCAT/SELinux.pm @@ -81,17 +81,16 @@ sub config_mode { =head3 xcatconfig_action Descriptions: - Decides what xcatconfig does about SELinux on this node. The caller - makes the changes the answer asks for. + Decides what xcatconfig does about SELinux on this node. The answer + asks for no change, because the SELinux policy belongs to the site. + The caller reports the warning. Arguments: root - a prefix for the paths this module reads. Returns: A hash reference: - mode - the mode runtime_mode reports - config_mode - the mode config_mode reports - warning - a message for the admin, or undef - disable - true when xcatconfig must turn SELinux off - enforce_file - the selinuxfs file that sets the running mode + mode - the mode runtime_mode reports + config_mode - the mode config_mode reports + warning - a message for the admin, or undef when SELinux is off Example: my $answer = xCAT::SELinux->xcatconfig_action(); @@ -104,22 +103,15 @@ sub xcatconfig_action { my $mode = $class->runtime_mode(root => $root); my %answer = ( - mode => $mode, - config_mode => $class->config_mode(root => $root), - warning => undef, - disable => 0, - enforce_file => undef, + mode => $mode, + config_mode => $class->config_mode(root => $root), + warning => undef, ); return \%answer if $mode eq 'disabled'; - $answer{warning} = 'SELINUX is not disabled, disabling it now...'; - $answer{disable} = 1; - foreach my $path (@ENFORCE_FILES) { - next unless -f "$root$path"; - $answer{enforce_file} = $path; - last; - } + $answer{warning} = + "SELINUX is $mode. xCAT does not change the SELinux mode or $CONFIG_FILE."; return \%answer; } diff --git a/xCAT-server/sbin/xcatconfig b/xCAT-server/sbin/xcatconfig index ab1f69fcf8..c615d9477e 100755 --- a/xCAT-server/sbin/xcatconfig +++ b/xCAT-server/sbin/xcatconfig @@ -515,29 +515,6 @@ if ($::INITIALINSTALL || $::FORCE) { xCAT::MsgUtils->message('W', $selinux->{warning}); } - if ($selinux->{disable}) - { - # set selinux be in permissive mode for running system, - # if the user forgot to disable selinux, - # try to not hurt xcat too much - if ($selinux->{enforce_file}) - { - my $cmd = "echo 0 > $selinux->{enforce_file}"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); - } - } - - # Disable selinux through reboots - my $cmd = "sed -i 's/^SELINUX=.*\$/SELINUX=disabled/' $xCAT::SELinux::CONFIG_FILE"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); - } - } } my $ret = xCAT::Utils->stopservice("firewall"); From 61bc1dc1e968ecd76fc00680e0576ddfc4f00b11 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:42:34 -0300 Subject: [PATCH 04/91] test(xcat-core): capture the shell that starts xcatd xcatd.service starts xcatd through /bin/sh to read /etc/profile.d/xcat.sh. systemd runs that shell in initrc_t, so on an SELinux system xcatd runs in initrc_t. That domain moves rsync, useradd, groupadd, hwclock and setfiles into confined domains, which deny syncfiles, updatenode -F and genimage. xcatd_service_direct_exec.t reads the [Service] section of the unit and checks that ExecStart runs /usr/sbin/xcatd and that Environment= carries XCATROOT, PATH and PERL_BADLANG. 11 of its 14 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcatd_service_direct_exec.t | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 xCAT-test/unit/xcatd_service_direct_exec.t diff --git a/xCAT-test/unit/xcatd_service_direct_exec.t b/xCAT-test/unit/xcatd_service_direct_exec.t new file mode 100644 index 0000000000..22449baf84 --- /dev/null +++ b/xCAT-test/unit/xcatd_service_direct_exec.t @@ -0,0 +1,62 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use File::Slurper qw(read_lines); +use Test::More; + +# The unit file is the artifact: systemd reads it, nothing in the tree runs it. +my $unit_file = "$FindBin::Bin/../../xCAT-server/etc/init.d/xcatd.service"; + +# Returns the [Service] settings as name => [values], in file order. +sub service_settings { + my ($path) = @_; + + my (%settings, $section); + foreach my $line (read_lines($path)) { + next if $line =~ /^\s*(?:#|;|$)/; + if ($line =~ /^\s*\[(\w+)\]\s*$/) { + $section = $1; + next; + } + next unless defined $section && $section eq 'Service'; + my ($name, $value) = $line =~ /^\s*(\w+)\s*=\s*(.*?)\s*$/ or next; + push @{ $settings{$name} }, $value; + } + + return \%settings; +} + +my $service = service_settings($unit_file); + +# systemd starts a shell in initrc_t and a bin_t binary in unconfined_service_t. +my @exec = @{ $service->{ExecStart} || [] }; +is(scalar(@exec), 1, 'the unit has one ExecStart'); +my ($program) = split /\s+/, ($exec[0] // ''); +is($program, '/usr/sbin/xcatd', 'ExecStart runs the xcatd binary, not a shell'); +like($exec[0] // '', qr{\s-p\s+/run/xcatd\.pid(?:\s|$)}, + '... and passes the pid file that PIDFile names'); +is_deeply($service->{PIDFile}, ['/run/xcatd.pid'], 'PIDFile is /run/xcatd.pid'); + +# Environment= replaces what /etc/profile.d/xcat.sh gave xcatd. +my %env; +foreach my $setting (@{ $service->{Environment} || [] }) { + foreach my $pair ($setting =~ /("[^"]*"|\S+)/g) { + $pair =~ s/^"|"$//g; + my ($name, $value) = split /=/, $pair, 2; + $env{$name} = $value; + } +} +is($env{XCATROOT}, '/opt/xcat', 'the unit sets XCATROOT=/opt/xcat'); +is($env{PERL_BADLANG}, '0', 'the unit sets PERL_BADLANG=0'); +my @path = split /:/, ($env{PATH} // ''); +foreach my $dir (qw(/opt/xcat/bin /opt/xcat/sbin /opt/xcat/share/xcat/tools + /usr/sbin /usr/bin /sbin /bin)) { + ok((grep { $_ eq $dir } @path), "the unit PATH has $dir"); +} + +is_deeply($service->{EnvironmentFile}, ['-/etc/sysconfig/xcat'], + '/etc/sysconfig/xcat can still override the environment'); + +done_testing(); From cdeec6668ee383b99f4975ffa1c04b6e2346b929 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:43:29 -0300 Subject: [PATCH 05/91] fix(xcat-core): xcatd runs in initrc_t under SELinux xcatd.service started xcatd through /bin/sh to read /etc/profile.d/xcat.sh. systemd runs the shell in initrc_t, and xcatd inherited that domain. initrc_t moves rsync, useradd, groupadd, hwclock and setfiles into confined domains, so an enforcing management node denies syncfiles, updatenode -F and genimage. ExecStart now runs /usr/sbin/xcatd directly. systemd starts the bin_t binary in unconfined_service_t, which has none of these transitions. The unit sets XCATROOT, PATH and PERL_BADLANG with Environment=, and /etc/sysconfig/xcat can still override them. RPM and Debian packages ship the same unit. The SysV script for hosts without systemd still reads the profile. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-server/etc/init.d/xcatd.service | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xCAT-server/etc/init.d/xcatd.service b/xCAT-server/etc/init.d/xcatd.service index 362b76dea8..a8e1453aee 100644 --- a/xCAT-server/etc/init.d/xcatd.service +++ b/xCAT-server/etc/init.d/xcatd.service @@ -3,12 +3,15 @@ Description=xCAT management service After=network.target syslog.service [Service] +# systemd runs a shell in initrc_t. xcatd must start directly to run in unconfined_service_t. +Environment=XCATROOT=/opt/xcat PERL_BADLANG=0 +Environment=PATH=/opt/xcat/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin EnvironmentFile=-/etc/sysconfig/xcat Type=forking PIDFile=/run/xcatd.pid RuntimeDirectory=xcat RuntimeDirectoryMode=0755 -ExecStart=/bin/sh -c '[ -r /etc/profile.d/xcat.sh ] && . /etc/profile.d/xcat.sh; exec /usr/sbin/xcatd -p /run/xcatd.pid' +ExecStart=/usr/sbin/xcatd -p /run/xcatd.pid ExecStop=/bin/sh -c 'if [ -s /run/xcatd.pid ]; then kill -TERM "$(cat /run/xcatd.pid)" 2>/dev/null || true; fi' LimitNOFILE=16000 RemainAfterExit=no From d53b723379cbb3b72ce6f5f8fd61989af2454c61 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:52:05 -0300 Subject: [PATCH 06/91] test(xcat-core): capture the missing xCAT SELinux policy package xCAT ships no SELinux policy. On an enforcing management node, httpd cannot read /install, which has no file context and is default_t, and cannot read the /tftpboot files that xcat.conf serves. xcatws.cgi cannot connect to xcatd. xcat_selinux_package.t reads the xCAT-selinux spec, its file context list and the xCAT-server and xCATsn specs. It checks the build and the scriptlet macros, the /install labels, and the conditional Requires on xCAT-selinux. 23 of its 31 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 125 ++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 xCAT-test/unit/xcat_selinux_package.t diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t new file mode 100644 index 0000000000..08da10802a --- /dev/null +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -0,0 +1,125 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use File::Slurper qw(read_lines); +use Test::More; + +# The spec files and the file context list are the artifacts: rpmbuild and +# semodule read them as written. +my $root = "$FindBin::Bin/../.."; + +# Returns the lines of a file, or an empty list when the file is not there. +sub lines_of { + my ($path) = @_; + return -f $path ? read_lines($path) : (); +} + +# Splits a spec into its preamble and its %sections, keyed by section name. +sub spec_sections { + my (@lines) = @_; + + my %sections = (preamble => []); + my $current = 'preamble'; + foreach my $line (@lines) { + if ($line =~ /^%(prep|build|install|check|clean|files|changelog|description|package|pre|post|preun|postun|pretrans|posttrans)\b/) { + $current = $1; + $sections{$current} ||= []; + next; + } + push @{ $sections{$current} }, $line; + } + + return \%sections; +} + +# The %if line that encloses line $index, or undef at the top level. +sub enclosing_if { + my ($lines, $index) = @_; + + my $depth = 0; + for (my $i = $index - 1 ; $i >= 0 ; $i--) { + my $line = $lines->[$i]; + if ($line =~ /^%endif\b/) { + $depth++; + } elsif ($line =~ /^%if(?:os|arch|narch|nos)?\b/) { + return $line if $depth == 0; + $depth--; + } + } + + return undef; +} + +my $spec_path = "$root/xCAT-selinux/xCAT-selinux.spec"; +ok(-f $spec_path, 'xCAT-selinux has a spec'); +my $spec = spec_sections(lines_of($spec_path)); +my $preamble = join("\n", @{ $spec->{preamble} }); + +like($preamble, qr/^Name:\s*xCAT-selinux\s*$/m, 'the package is named xCAT-selinux'); +like($preamble, qr/^BuildArch:\s*noarch\s*$/m, '... and is noarch'); +like($preamble, qr/^Source:\s*xCAT-selinux-%\{version\}\.tar\.gz\s*$/m, + '... and builds from the tarball that buildrpms.pl makes of the package directory'); +like($preamble, qr/^BuildRequires:.*\bselinux-policy-devel\b/m, + '... and needs selinux-policy-devel to build the module'); +like($preamble, qr/^Requires:.*\bselinux-policy-targeted\b/m, + '... and needs the targeted policy'); +like($preamble, qr/^Requires\(post\):.*\bpolicycoreutils\b/m, + '... and needs semodule in %post'); +unlike($preamble, qr/selinux_requires/, + '... and does not pin selinux-policy to the version of the build host'); + +my $build = join("\n", @{ $spec->{build} || [] }); +like($build, qr{make -f %\{_datadir\}/selinux/devel/Makefile\b.*\bxcat\.pp\b}, + '%build compiles xcat.pp with the selinux-policy-devel Makefile'); +like($build, qr{checkmodule -M -c 19\b}, + '... at module version 19, which the EL8 policy tools read'); + +my $install = join("\n", @{ $spec->{install} || [] }); +like($install, qr{%\{_datadir\}/selinux/packages/targeted\b}, + '%install puts the module in the targeted package directory'); + +my $files = join("\n", @{ $spec->{files} || [] }); +like($files, qr{^%\{_datadir\}/selinux/packages/targeted/xcat\.pp\.bz2$}m, + '%files ships xcat.pp.bz2'); + +like(join("\n", @{ $spec->{pre} || [] }), qr/^%selinux_relabel_pre -s targeted$/m, + '%pre saves the file contexts before the module changes them'); +like(join("\n", @{ $spec->{post} || [] }), + qr{^%selinux_modules_install -s targeted %\{_datadir\}/selinux/packages/targeted/xcat\.pp\.bz2$}m, + '%post installs the module'); +like(join("\n", @{ $spec->{postun} || [] }), qr/^%selinux_modules_uninstall -s targeted xcat$/m, + '%postun removes the module'); +my $posttrans = join("\n", @{ $spec->{posttrans} || [] }); +like($posttrans, qr/^%selinux_relabel_post -s targeted$/m, + '%posttrans relabels the files whose context changed'); +like($posttrans, qr{\brestorecon -R /install\b}, '... and relabels /install'); +foreach my $section (qw(pre post postun posttrans)) { + unlike(join("\n", @{ $spec->{$section} || [] }), qr/\bsetenforce\b|\/etc\/selinux\/config/, + "%$section does not change the SELinux mode"); +} + +my @fc = grep { !/^\s*(?:#|$)/ } lines_of("$root/xCAT-selinux/xcat.fc"); +my %fc = map { (split /\s+/, $_, 2) } @fc; +is($fc{'/install(/.*)?'}, 'gen_context(system_u:object_r:public_content_t,s0)', + '/install is public_content_t'); +is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg(/.*)?'}, '<>', + '... and restorecon leaves a rootimg alone'); +is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)?'}, '<>', + '... and a statelite rootimg too'); +ok(!(grep { m{^/tftpboot} } keys %fc), '/tftpboot keeps the stock tftpdir_t'); + +# A management node or a service node with the targeted policy installs the module. +foreach my $pkg (qw(xCAT-server xCATsn)) { + my @lines = lines_of("$root/$pkg/$pkg.spec"); + my ($index) = grep { + $lines[$_] =~ /^Requires:\s*\(xCAT-selinux = 4:%\{version\}-%\{release\} if selinux-policy-targeted\)\s*$/ + } 0 .. $#lines; + ok(defined $index, "$pkg requires xCAT-selinux when selinux-policy-targeted is installed"); + my $if = defined $index ? enclosing_if(\@lines, $index) : undef; + like($if // '', qr/\brhel\b/, "... only in a Red Hat family build"); + unlike($if // '', qr/suse/, "... and not in a SUSE build, which has no xCAT-selinux"); +} + +done_testing(); From 414504d0694c2d286c9f676304b6639cedb6e93f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:57:17 -0300 Subject: [PATCH 07/91] feat(xcat-core): add the xCAT-selinux policy package xCAT shipped no SELinux policy. On an enforcing management node httpd could not read /install, which had no file context, or the /tftpboot files that xcat.conf serves, and xcatws.cgi could not connect to xcatd. The new noarch xCAT-selinux package builds the xcat module with the selinux-policy-devel Makefile. The module labels /install public_content_t and leaves each rootimg tree out of the relabel. It lets httpd read tftpdir_t and lets httpd_sys_script_t connect to ntop_port_t. The scriptlets use the selinux-policy macros, and %posttrans relabels /install. They do not change the SELinux mode. checkmodule writes module version 19, so the package built in the EL10 mock root installs on EL8, EL9 and EL10. On a Red Hat family build, xCAT-server and xCATsn require xCAT-selinux when selinux-policy-targeted is installed. SUSE and Debian builds do not change. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- buildrpms.pl | 1 + xCAT-selinux/xCAT-selinux.spec | 59 ++++++++++++++++++++++++++++++++++ xCAT-selinux/xcat.fc | 5 +++ xCAT-selinux/xcat.te | 13 ++++++++ xCAT-server/xCAT-server.spec | 4 +++ xCATsn/xCATsn.spec | 5 +++ 6 files changed, 87 insertions(+) create mode 100644 xCAT-selinux/xCAT-selinux.spec create mode 100644 xCAT-selinux/xcat.fc create mode 100644 xCAT-selinux/xcat.te diff --git a/buildrpms.pl b/buildrpms.pl index fc756a6213..a99253b0bd 100755 --- a/buildrpms.pl +++ b/buildrpms.pl @@ -136,6 +136,7 @@ my @PACKAGES = qw( xCAT-openbmc-py xCAT-probe xCAT-rmc + xCAT-selinux xCAT-server xCAT-test xCAT-vlan diff --git a/xCAT-selinux/xCAT-selinux.spec b/xCAT-selinux/xCAT-selinux.spec new file mode 100644 index 0000000000..cd224a90aa --- /dev/null +++ b/xCAT-selinux/xCAT-selinux.spec @@ -0,0 +1,59 @@ +Summary: SELinux policy module for the xCAT management and service nodes +Name: xCAT-selinux +Version: %{?version:%{version}}%{!?version:%(cat Version)} +Release: %{?release:%{release}}%{!?release:%(cat Release)} +Epoch: 4 +License: EPL +Group: Applications/System +Source: xCAT-selinux-%{version}.tar.gz +Packager: IBM Corp. +Vendor: IBM Corp. +Distribution: %{?_distribution:%{_distribution}}%{!?_distribution:%{_vendor}} +BuildRoot: /var/tmp/%{name}-%{version}-%{release}-root +BuildArch: noarch + +BuildRequires: selinux-policy-devel +BuildRequires: bzip2 +Requires: selinux-policy-targeted +Requires(pre): libselinux-utils +Requires(post): policycoreutils +Requires(post): libselinux-utils +Requires(posttrans): policycoreutils +Requires(posttrans): libselinux-utils + +%description +xCAT-selinux labels /install for the services that read it, and lets httpd +serve /tftpboot and xcatws.cgi connect to xcatd. It does not change the +SELinux mode. + +%prep +%setup -q -n xCAT-selinux + +%build +# One noarch package serves EL8 to EL10, and EL8 reads module versions up to 19. +make -f %{_datadir}/selinux/devel/Makefile CHECKMODULE="%{_bindir}/checkmodule -M -c 19" xcat.pp +bzip2 -9 xcat.pp + +%install +rm -rf $RPM_BUILD_ROOT +mkdir -p $RPM_BUILD_ROOT%{_datadir}/selinux/packages/targeted +install -m 0644 xcat.pp.bz2 $RPM_BUILD_ROOT%{_datadir}/selinux/packages/targeted/ + +%files +%defattr(-,root,root) +%{_datadir}/selinux/packages/targeted/xcat.pp.bz2 + +%pre +%selinux_relabel_pre -s targeted + +%post +%selinux_modules_install -s targeted %{_datadir}/selinux/packages/targeted/xcat.pp.bz2 + +%postun +%selinux_modules_uninstall -s targeted xcat + +%posttrans +%selinux_relabel_post -s targeted +if selinuxenabled && [ -d /install ]; then + restorecon -R /install || : +fi diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc new file mode 100644 index 0000000000..300e3c8d7a --- /dev/null +++ b/xCAT-selinux/xcat.fc @@ -0,0 +1,5 @@ +/install(/.*)? gen_context(system_u:object_r:public_content_t,s0) + +# A rootimg keeps the labels of its own OS, so restorecon must not change them. +/install/netboot/[^/]+/[^/]+/[^/]+/rootimg(/.*)? <> +/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)? <> diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te new file mode 100644 index 0000000000..2e0f6e0e64 --- /dev/null +++ b/xCAT-selinux/xcat.te @@ -0,0 +1,13 @@ +policy_module(xcat, 1.0.0) + +gen_require(` + type httpd_t, httpd_sys_script_t, tftpdir_t, ntop_port_t; +') + +# httpd serves /tftpboot through the AliasMatch in xcat.conf. The stock policy lets only tftpd read tftpdir_t. +allow httpd_t tftpdir_t:dir list_dir_perms; +allow httpd_t tftpdir_t:file read_file_perms; +allow httpd_t tftpdir_t:lnk_file read_lnk_file_perms; + +# xcatws.cgi connects to xcatd on site.xcatdport, and the stock policy labels TCP 3001 ntop_port_t. +allow httpd_sys_script_t ntop_port_t:tcp_socket name_connect; diff --git a/xCAT-server/xCAT-server.spec b/xCAT-server/xCAT-server.spec index f8cf2766d6..b26692aec9 100644 --- a/xCAT-server/xCAT-server.spec +++ b/xCAT-server/xCAT-server.spec @@ -104,6 +104,10 @@ Requires: perl-IO-Tty perl-Crypt-SSLeay make httpd Requires: perl-xCAT = 4:%{version}-%{release} Requires: xCAT-client = 4:%{version}-%{release} +%if 0%{?rhel} >= 8 || 0%{?fedora} || 0%{?openEuler} +Requires: (xCAT-selinux = 4:%{version}-%{release} if selinux-policy-targeted) +%endif + %description xCAT-server provides the core server and configuration management components of xCAT. This package should be installed on your management server diff --git a/xCATsn/xCATsn.spec b/xCATsn/xCATsn.spec index ec36669c10..81c577d8e3 100644 --- a/xCATsn/xCATsn.spec +++ b/xCATsn/xCATsn.spec @@ -24,6 +24,11 @@ Requires: perl-DBD-SQLite Requires: xCAT-client = 4:%{version}-%{release} Requires: xCAT-server = 4:%{version}-%{release} Requires: xCAT-probe = 4:%{version}-%{release} + +%if 0%{?rhel} >= 8 || 0%{?fedora} || 0%{?openEuler} +Requires: (xCAT-selinux = 4:%{version}-%{release} if selinux-policy-targeted) +%endif + # RPM 4.11 does not recognize weak dependency tags. %if 0%{?fedora} || 0%{?rhel} >= 8 || 0%{?suse_version} >= 1500 Recommends: xCAT-genesis-openembedded-x86_64 From 3607c3f7bd2c9b994aa4e1bbfc89f85ee30b3828 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:03:04 -0300 Subject: [PATCH 08/91] test(xcat-core): capture the five measured rules the policy module omits The xcat policy module carries four allow rules and xcat_selinux_package.t reads only the spec and the file context list, so no test reads the module source. The SELinux campaign measured five more accesses that the module does not grant: httpd maps the per-node xnba boot config it serves, rsync reads /etc/shadow and needs CAP_DAC_OVERRIDE to write it, and useradd and groupadd read the rootimg /var/run symlink from an rpm scriptlet. The test parses the allow rules of xcat.te into a permission set per source, target and class, and asserts each access. It also asserts that no rule grants kernel_t anything. Two such rules make an EL10 diskless node boot enforcing, and they grant the pre-pivot domain execute on an unlabelled file, which on that node is the whole root. 7 of the 43 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 61 +++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 08da10802a..d98b64d5ad 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -110,6 +110,67 @@ is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)?'}, '<>' '... and a statelite rootimg too'); ok(!(grep { m{^/tftpboot} } keys %fc), '/tftpboot keeps the stock tftpdir_t'); +# The module source is the artifact: checkmodule compiles this text as written. +# Each rule here is justified by a measured denial; see +# docs/source/advanced/selinux/index.rst and the policy campaign REASONING.md. +my @te = grep { !/^\s*(?:#|$)/ } lines_of("$root/xCAT-selinux/xcat.te"); +my $te = join("\n", @te); + +like($te, qr/^policy_module\(xcat,/m, 'xcat.te declares the xcat policy module'); + +# Collects the permission set of each allow rule, keyed "source target:class". +my %allow; +foreach my $rule (split /;/, $te) { + next unless $rule =~ /\ballow\s+(\S+)\s+(\S+?):(\S+)\s+(.+)/s; + my ($source, $target, $class, $perms) = ($1, $2, $3, $4); + $perms =~ s/[{}]/ /g; + $allow{"$source $target:$class"}{$_} = 1 foreach split ' ', $perms; +} + +# Taken before the lookups below, which autovivify the keys they miss. +my @rules = sort keys %allow; + +# httpd mmaps the per-node xnba boot config it serves out of /tftpboot. +# read_file_perms does not hold map, so httpd is denied on the map. +ok($allow{'httpd_t tftpdir_t:file'}{mmap_read_file_perms} + || $allow{'httpd_t tftpdir_t:file'}{map}, + 'httpd may map a file it serves from /tftpboot'); +ok($allow{'httpd_t tftpdir_t:dir'} && $allow{'httpd_t tftpdir_t:lnk_file'}, + '... and still reads the directory and the symlinks'); + +# xcatws.cgi connects to xcatd, whose port the stock policy labels ntop_port_t. +ok($allow{'httpd_sys_script_t ntop_port_t:tcp_socket'}{name_connect}, + 'the REST API connects to the xcatd port'); + +# rsync copies /etc/shadow to the nodes and into a rootimg. The stock policy +# holds that read behind rsync_export_all_ro, and rsync_full_access does not +# grant it, because shadow_t is not in non_auth_file_type. +foreach my $perm (qw(getattr open read)) { + ok($allow{'rsync_t shadow_t:file'}{$perm}, + "rsync may $perm /etc/shadow when it runs confined"); +} + +# rsync preserves the mode of /etc/shadow, so it writes a target it created at +# mode 0000. As root that needs CAP_DAC_OVERRIDE, which no boolean grants. +ok($allow{'rsync_t self:capability'}{dac_override}, + 'rsync may write a target it created at mode 0000'); + +# useradd and groupadd run from the %pre of a package genimage installs into a +# rootimg, and look for their lock file through the rootimg /var/run symlink. +# It carries public_content_t because the rootimg is under /install, and no +# base rule reaches that type for lnk_file. +foreach my $domain (qw(useradd_t groupadd_t)) { + ok($allow{"$domain public_content_t:lnk_file"}{read}, + "$domain reads the rootimg /var/run symlink"); +} + +# Granting execute on an unlabelled file buys a boot by standing in for a +# labelling step that has not run. See the EL10 note in the SELinux document. +ok(scalar(@rules) >= 4, 'xcat.te carries the allow rules this test reads'); +is_deeply([ grep { /^kernel_t / } @rules ], [], + 'no rule grants kernel_t anything'); + + # A management node or a service node with the targeted policy installs the module. foreach my $pkg (qw(xCAT-server xCATsn)) { my @lines = lines_of("$root/$pkg/$pkg.spec"); From b293dfe7449476604886b80cabe891dbd5a5875b Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:03:15 -0300 Subject: [PATCH 09/91] fix(xcat-core): the policy module omits five measured accesses The xcat policy module granted httpd read of /tftpboot and let xcatws.cgi connect to the xcatd port. Five further accesses were measured denied on a management node and are not granted, so an enforcing node fails at them. httpd mmaps the per-node xnba boot config it serves out of /tftpboot. read_file_perms does not hold map, so the module now grants mmap_read_file_perms. Two sites recorded this denial three days apart, on xCAT 2.19.1 and 2.20. xdcp and "updatenode -F" copy /etc/shadow to the nodes and into a rootimg. rsync_export_all_ro holds that read and rsync_full_access does not grant it, because shadow_t is not in non_auth_file_type. rsync also writes a target it created at mode 0000, which needs CAP_DAC_OVERRIDE. Both rules are reached only where rsync runs in rsync_t, which needs a system-service caller. genimage installs packages into a rootimg with yum in a chroot, and useradd and groupadd read the rootimg /var/run symlink from the rpm scriptlets. The symlink carries public_content_t because the rootimg is under /install, and the base grant for that read names public_content_t nowhere. The module compiles at version 19 in the alma+epel-10-x86_64 mock root, and the five types reach the binary. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 2e0f6e0e64..81d5f5e2d5 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -2,12 +2,36 @@ policy_module(xcat, 1.0.0) gen_require(` type httpd_t, httpd_sys_script_t, tftpdir_t, ntop_port_t; + type rsync_t, shadow_t; + type useradd_t, groupadd_t, public_content_t; ') # httpd serves /tftpboot through the AliasMatch in xcat.conf. The stock policy lets only tftpd read tftpdir_t. +# mmap_read_file_perms, not read_file_perms: httpd maps the per-node xnba boot config it serves. allow httpd_t tftpdir_t:dir list_dir_perms; -allow httpd_t tftpdir_t:file read_file_perms; +allow httpd_t tftpdir_t:file mmap_read_file_perms; allow httpd_t tftpdir_t:lnk_file read_lnk_file_perms; # xcatws.cgi connects to xcatd on site.xcatdport, and the stock policy labels TCP 3001 ntop_port_t. allow httpd_sys_script_t ntop_port_t:tcp_socket name_connect; + +# xdcp and "updatenode -F" copy /etc/shadow to the nodes and into a rootimg. +# rsync_export_all_ro holds the read, and rsync_full_access does not grant it: +# shadow_t is not in non_auth_file_type. These two rules are narrower than +# either boolean. They are reached only where rsync runs in rsync_t, which +# needs a system-service caller; xcatd is unconfined_service_t and does not +# transition there. +allow rsync_t shadow_t:file { getattr open read }; + +# rsync preserves the mode of /etc/shadow, so it writes a target it created at +# mode 0000. As root that needs CAP_DAC_OVERRIDE. rsync_t already holds chown, +# fowner, fsetid and dac_read_search; this is the write side of that set. +allow rsync_t self:capability dac_override; + +# genimage installs packages into a rootimg with yum in a chroot, and the rpm +# scriptlets run useradd and groupadd. Both read the rootimg /var/run symlink +# while they look for their lock file. It carries public_content_t because the +# rootimg is under /install, and the base grant for that read is a list of +# explicit per-type rules that public_content_t is in none of. +allow useradd_t public_content_t:lnk_file read; +allow groupadd_t public_content_t:lnk_file read; From ec2a48dec06fdfbde1b7e13d7cc76b47a85c0f8a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:47:12 -0300 Subject: [PATCH 10/91] test(xcat-core): capture the SELinux context of the staged Genesis kernel mknb stages the legacy Genesis kernel into the TFTP root with cp -a. The flag implies --preserve=all, so the kernel arrives with the SELinux context of the xCAT install tree and not the context the policy declares for that path. The test drives stage_genesis_payload with a recording runner. It asserts that the copy does not preserve the context, and that the staged kernel is relabelled after the copy when SELinux is enabled. It fails on the current code: 4 of its 14 checks are red. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/mknb_genesis_selinux_context.t | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 xCAT-test/unit/mknb_genesis_selinux_context.t diff --git a/xCAT-test/unit/mknb_genesis_selinux_context.t b/xCAT-test/unit/mknb_genesis_selinux_context.t new file mode 100644 index 0000000000..e46c5dac6a --- /dev/null +++ b/xCAT-test/unit/mknb_genesis_selinux_context.t @@ -0,0 +1,105 @@ +#!/usr/bin/env perl +# The Genesis kernel is the one file mknb stages into the TFTP root from the xCAT install tree, +# so it is the one file that can arrive with the install tree's SELinux context. +use strict; +use warnings; + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use Test::More; + +BEGIN { $INC{'xCAT/Utils.pm'} = 1; $INC{'xCAT/MsgUtils.pm'} = 1; + $INC{'xCAT/Table.pm'} = 1; $INC{'xCAT/NetworkUtils.pm'} = 1; + $INC{'xCAT/TableUtils.pm'} = 1; $INC{'xCAT_monitoring/monitorctrl.pm'} = 1; } + +require "$FindBin::Bin/../../xCAT-server/lib/xcat/plugins/mknb.pm"; + +my $TFTPDIR = '/tftpboot'; +my $KERNEL = "$TFTPDIR/xcat/genesis.kernel.x86_64"; + +# cp carries the SELinux context when the preserve set holds context or xattr, because the +# context is stored in the security.selinux xattr. -a sets both, and the last --preserve or +# --no-preserve for an item wins. Model that, so the assertion is about what cp does and not +# about which spelling mknb chose. +sub preserves_context { + my ($command) = @_; + my %keeps = (context => 0, xattr => 0); + foreach my $word (split(/\s+/, $command)) { + if ($word =~ m{\A--(no-)?preserve=(.*)\z}) { + my $value = $1 ? 0 : 1; + foreach my $item (split(/,/, $2)) { + @keeps{ keys %keeps } = ($value) x keys(%keeps) if $item eq 'all'; + $keeps{$item} = $value if exists($keeps{$item}); + } + } elsif ($word =~ m{\A-[a-zA-Z]+\z} && $word =~ m{a}) { + @keeps{ keys %keeps } = (1) x keys(%keeps); + } + } + return ($keeps{context} || $keeps{xattr}) ? 1 : 0; +} + +# Drive the legacy path with a runner that records every command and can fail one of them. +sub stage { + my (%opt) = @_; + my @ran; + no warnings qw(redefine once); + local *xCAT::Utils::isSELINUX = sub { return $opt{selinux} ? 0 : 1 }; + my ($rc, $src) = xCAT_plugin::mknb::stage_genesis_payload( + genesis_type => 'legacy', + genesis_dir => '/opt/xcat/share/xcat/netboot/genesis/x86_64', + tftpdir => $TFTPDIR, + arch => 'x86_64', + tempdir => '/tmp/scratch', + run => sub { + my ($cmd) = @_; + push @ran, $cmd; + return ($opt{fail} && $cmd =~ /$opt{fail}/) ? 256 : 0; + }, + ); + return { rc => $rc, src => $src, ran => \@ran }; +} + +# --- the copy must not carry the install tree's context into the TFTP root --------- +is(preserves_context('cp -a src dst'), 1, + 'the model reads cp -a as context-preserving'); +is(preserves_context('cp -a --no-preserve=context src dst'), 1, + 'and reads cp -a --no-preserve=context the same way, because the xattr still carries it'); +is(preserves_context('cp -a --no-preserve=context,xattr src dst'), 0, + 'and reads a copy that drops both items as not context-preserving'); +is(preserves_context('cp -p src dst'), 0, + 'and reads cp -p as not context-preserving'); + +my $on = stage(selinux => 1); +my ($copy) = grep { m{\Qcp \E} && m{\Q$KERNEL\E} } @{ $on->{ran} }; +ok($copy, 'the legacy path copies the Genesis kernel into the TFTP root') + or diag(join("\n", @{ $on->{ran} })); +is(preserves_context($copy // ''), 0, + 'and the copy does not preserve the SELinux context of the install tree'); + +# --- the staged kernel is relabelled, so an upgraded node is corrected too --------- +my @relabel = grep { m{restorecon} } @{ $on->{ran} }; +is(scalar @relabel, 1, 'one relabel runs when SELinux is enabled'); +like($relabel[0] // '', qr{\Q$KERNEL\E}, + 'and the relabel names the staged Genesis kernel'); +my ($copy_index) = grep { $on->{ran}->[$_] eq ($copy // '') } 0 .. $#{ $on->{ran} }; +my ($relabel_index) = grep { $on->{ran}->[$_] =~ m{restorecon} } 0 .. $#{ $on->{ran} }; +ok(defined($copy_index) && defined($relabel_index) && $relabel_index > $copy_index, + 'and it runs after the copy, not before it'); + +my $off = stage(selinux => 0); +is(scalar(grep { m{restorecon} } @{ $off->{ran} }), 0, + 'a node without SELinux runs no relabel'); + +# --- a relabel that fails must not fail the step ---------------------------------- +my $norelabel = stage(selinux => 1, fail => qr{restorecon}); +is($norelabel->{rc}, 0, 'a failed relabel leaves the staged payload in place'); +is($norelabel->{src}, undef, 'and names no unreadable source'); + +# --- the existing failures still name the copy that failed ------------------------ +my $nokernel = stage(selinux => 1, fail => qr{/kernel\s}); +isnt($nokernel->{rc}, 0, 'an unreadable kernel still fails the step'); +is(scalar(grep { m{restorecon} } @{ $nokernel->{ran} }), 0, + 'and a kernel that was not copied is not relabelled'); + +done_testing(); From 16e20fbb524b06637f97f26c20a9cf23c0fc27d6 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:47:30 -0300 Subject: [PATCH 11/91] fix(xcat-core): Genesis kernel keeps the install tree SELinux context mknb stages the legacy Genesis kernel with cp -a, which implies --preserve=all and copies the SELinux context of /opt/xcat/share/xcat/netboot/genesis with it. On a management node with SELinux enabled the kernel then carries usr_t, while the policy declares tftpdir_t for that path. Measured on an el9 management node, restorecon -nvR /tftpboot names genesis.kernel.x86_64 and no other path, so it is the one file xCAT mislabels under the TFTP root. Nothing in the netboot path relabels it. stage_genesis_payload now copies with --no-preserve=context,xattr, and runs restorecon -F on the staged kernel when xCAT::Utils->isSELINUX reports SELinux enabled. xattr goes with context because cp stores the context in the security.selinux xattr, so --no-preserve=context alone still copies it. The relabel corrects a kernel that an earlier xCAT staged, because a copy over an existing file keeps that file's context. A failed relabel does not fail the step. mknb_genesis_staging.t reports SELinux as disabled, so its command counts stay about the copies it tests. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-server/lib/xcat/plugins/mknb.pm | 9 ++++++++- xCAT-test/unit/mknb_genesis_staging.t | 5 ++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/xCAT-server/lib/xcat/plugins/mknb.pm b/xCAT-server/lib/xcat/plugins/mknb.pm index 38b75d1f28..b450e442b2 100644 --- a/xCAT-server/lib/xcat/plugins/mknb.pm +++ b/xCAT-server/lib/xcat/plugins/mknb.pm @@ -387,8 +387,15 @@ sub stage_genesis_payload { # status nor the name of the unreadable file is lost to the one that follows it. $rc = $run->("shopt -s dotglob; GLOBIGNORE=\".:..\" cp -a $a{genesis_dir}/fs/* $a{tempdir}"); return ($rc, "$a{genesis_dir}/fs") if $rc; - $rc = $run->("cp -a $a{genesis_dir}/kernel $a{tftpdir}/xcat/genesis.kernel.$a{arch}"); + my $kernel = "$a{tftpdir}/xcat/genesis.kernel.$a{arch}"; + # cp -a implies --preserve=all, which carries the SELinux context of the xCAT install + # tree into the TFTP root, where the policy declares tftpdir_t. The context also + # travels in the security.selinux xattr, so xattr has to go with context here. + $rc = $run->("cp -a --no-preserve=context,xattr $a{genesis_dir}/kernel $kernel"); return ($rc, "$a{genesis_dir}/kernel") if $rc; + # A kernel staged by an earlier xCAT keeps its own context through the copy, so set + # the context from the policy. isSELINUX returns 0 when SELinux is enabled. + $run->("restorecon -F $kernel") if xCAT::Utils->isSELINUX() == 0; return (0, undef); } $rc = $run->("cp -a $a{genesis_dir}/nbroot/* $a{tempdir}"); diff --git a/xCAT-test/unit/mknb_genesis_staging.t b/xCAT-test/unit/mknb_genesis_staging.t index 81fb7ae774..1b2d405639 100644 --- a/xCAT-test/unit/mknb_genesis_staging.t +++ b/xCAT-test/unit/mknb_genesis_staging.t @@ -19,7 +19,10 @@ can_ok('xCAT_plugin::mknb', 'stage_genesis_payload') or die('mknb has no stage_genesis_payload to drive'); # Drive the routine with a runner that fails exactly one copy, so each assertion names the -# copy it is about rather than the pair. +# copy it is about rather than the pair. The staging commands are the subject here, so report +# SELinux as disabled and leave the relabel to mknb_genesis_selinux_context.t. +BEGIN { no warnings 'once'; *xCAT::Utils::isSELINUX = sub { return 1 }; } + sub stage { my (%opt) = @_; my @ran; From e35e2f8e194de13832330e87c8e328be68f0cd0d Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 15:12:26 -0300 Subject: [PATCH 12/91] test(xcat-core): the Genesis SELinux checks pass when the relabel fails stage_genesis_payload() runs restorecon and discards its exit status, so a relabel that fails returns 0 and the kernel keeps the context of the install tree. mknb_genesis_selinux_context.t asserted that rc, so the test held the defect in place. It now requires the failure to reach the caller, with the kernel path and a message that names the relabel. selinux_context.sh reads only the output of restorecon -F -n -v, so a non-zero exit with no output reports GENESIS_SELINUX_OK. The helper also builds genesis.kernel. from the architecture it was given. With legacy Genesis, mknb ppc64le resolves share/xcat/netboot/genesis/ ppc64 and writes genesis.kernel.ppc64, so the helper fails on a kernel mknb never staged. Three ppc64le cells run this case. genesis_kernel_selinux_context.bats drives the helper with lsdef, mknb, selinuxenabled and restorecon shadowed and XCATROOT in a scratch tree. Three of its four checks fail without the fix that follows, and the fourth fails when the OpenEmbedded branch is removed. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../bats/genesis_kernel_selinux_context.bats | 96 +++++++++++++++++++ xCAT-test/unit/mknb_genesis_selinux_context.t | 18 +++- 2 files changed, 109 insertions(+), 5 deletions(-) create mode 100644 xCAT-test/bats/genesis_kernel_selinux_context.bats diff --git a/xCAT-test/bats/genesis_kernel_selinux_context.bats b/xCAT-test/bats/genesis_kernel_selinux_context.bats new file mode 100644 index 0000000000..554ab982f7 --- /dev/null +++ b/xCAT-test/bats/genesis_kernel_selinux_context.bats @@ -0,0 +1,96 @@ +#!/usr/bin/env bats +# +# Drive selinux_context.sh, the helper the genesis_kernel_selinux_context case runs on a +# management node. It needs SELinux, mknb and the xCAT site table, so shadow all three and +# point XCATROOT at a scratch image root. + +load 'helpers/shell_source' + +setup() +{ + HELPER="$(repo_path 'xCAT-test/autotest/testcase/genesis/selinux_context.sh')" + [ -r "$HELPER" ] || skip "$HELPER is required" + BIN="${BATS_TEST_TMPDIR}/bin" + TFTPDIR="${BATS_TEST_TMPDIR}/tftpboot" + IMAGE_ROOT="${BATS_TEST_TMPDIR}/xcatroot" + mkdir -p "$BIN" "$TFTPDIR/xcat" "$IMAGE_ROOT" + export HELPER BIN TFTPDIR IMAGE_ROOT +} + +stub() +{ + printf '#!/bin/sh\n%s\n' "$2" >"$BIN/$1" + chmod 0755 "$BIN/$1" +} + +# The commands the helper calls on an SELinux management node. mknb stages a kernel named for +# the architecture it resolved, which is not always the architecture it was asked for. +stub_node() +{ + local staged_arch="$1" restorecon_body="${2:-exit 0}" + stub lsdef "echo ' tftpdir=$TFTPDIR'" + stub selinuxenabled 'exit 0' + stub getenforce 'echo Enforcing' + stub mknb "echo kernel > '$TFTPDIR/xcat/genesis.kernel.$staged_arch'" + stub restorecon "$restorecon_body" +} + +# The image root mknb reads to choose between an OpenEmbedded export and the legacy tree. +install_genesis() +{ + local kind="$1" arch="$2" + mkdir -p "$IMAGE_ROOT/share/xcat/netboot/$kind/$arch" +} + +run_helper() +{ + PATH="$BIN:$PATH" XCATROOT="$IMAGE_ROOT" bash "$HELPER" "$@" 2>&1 +} + +@test "a verification command that fails without output is not a pass" { + install_genesis genesis x86_64 + # restorecon can fail without naming a file: no policy loaded, or a path it cannot read. + stub_node x86_64 'exit 3' + + run run_helper x86_64 + [ "$status" -ne 0 ] + [[ "$output" == *GENESIS_SELINUX_FAIL* ]] + [[ "$output" != *GENESIS_SELINUX_OK* ]] + [[ "$output" == *3* ]] +} + +@test "a legacy POWER node measures the kernel mknb staged" { + # Only xCAT-genesis-openembedded-ppc64le creates the OpenEmbedded directory, and the + # ppc64le genesis-legacy cells do not enable the repository that carries it. mknb then + # uses share/xcat/netboot/genesis/ppc64 and writes genesis.kernel.ppc64. + install_genesis genesis ppc64 + stub_node ppc64 + + run run_helper ppc64le + [ "$status" -eq 0 ] + [[ "$output" == *GENESIS_SELINUX_OK* ]] + [[ "$output" == *genesis.kernel.ppc64* ]] + [[ "$output" != *genesis.kernel.ppc64le* ]] +} + +@test "an OpenEmbedded POWER node keeps the exact architecture" { + install_genesis genesis-openembedded ppc64le + install_genesis genesis ppc64 + stub_node ppc64le + + run run_helper ppc64le + [ "$status" -eq 0 ] + [[ "$output" == *GENESIS_SELINUX_OK* ]] + [[ "$output" == *genesis.kernel.ppc64le* ]] +} + +@test "a kernel staged under another name fails and names both" { + install_genesis genesis ppc64 + stub_node ppc64le + + run run_helper ppc64le + [ "$status" -ne 0 ] + [[ "$output" == *GENESIS_SELINUX_FAIL* ]] + [[ "$output" == *genesis.kernel.ppc64* ]] + [[ "$output" == *genesis.kernel.ppc64le* ]] +} diff --git a/xCAT-test/unit/mknb_genesis_selinux_context.t b/xCAT-test/unit/mknb_genesis_selinux_context.t index e46c5dac6a..1f65b971a9 100644 --- a/xCAT-test/unit/mknb_genesis_selinux_context.t +++ b/xCAT-test/unit/mknb_genesis_selinux_context.t @@ -45,7 +45,7 @@ sub stage { my @ran; no warnings qw(redefine once); local *xCAT::Utils::isSELINUX = sub { return $opt{selinux} ? 0 : 1 }; - my ($rc, $src) = xCAT_plugin::mknb::stage_genesis_payload( + my ($rc, $src, $error) = xCAT_plugin::mknb::stage_genesis_payload( genesis_type => 'legacy', genesis_dir => '/opt/xcat/share/xcat/netboot/genesis/x86_64', tftpdir => $TFTPDIR, @@ -57,7 +57,7 @@ sub stage { return ($opt{fail} && $cmd =~ /$opt{fail}/) ? 256 : 0; }, ); - return { rc => $rc, src => $src, ran => \@ran }; + return { rc => $rc, src => $src, error => $error, ran => \@ran }; } # --- the copy must not carry the install tree's context into the TFTP root --------- @@ -91,14 +91,22 @@ my $off = stage(selinux => 0); is(scalar(grep { m{restorecon} } @{ $off->{ran} }), 0, 'a node without SELinux runs no relabel'); -# --- a relabel that fails must not fail the step ---------------------------------- +# --- a relabel that fails must fail the step -------------------------------------- +# A relabel that is attempted and fails leaves the kernel with the context the copy gave it, +# which is the defect this routine exists to prevent. Reporting success hides it. my $norelabel = stage(selinux => 1, fail => qr{restorecon}); -is($norelabel->{rc}, 0, 'a failed relabel leaves the staged payload in place'); -is($norelabel->{src}, undef, 'and names no unreadable source'); +isnt($norelabel->{rc}, 0, 'a failed relabel fails the step'); +is($norelabel->{src}, $KERNEL, 'and names the staged Genesis kernel'); +like($norelabel->{error} // '', qr{SELinux context}, + 'and the message names the relabel, not a copy'); +like($norelabel->{error} // '', qr{\Q$KERNEL\E}, + 'and the message carries the kernel path'); # --- the existing failures still name the copy that failed ------------------------ my $nokernel = stage(selinux => 1, fail => qr{/kernel\s}); isnt($nokernel->{rc}, 0, 'an unreadable kernel still fails the step'); +like($nokernel->{error} // '', qr{\QFailed to copy\E}, + 'and still reports the copy it could not make'); is(scalar(grep { m{restorecon} } @{ $nokernel->{ran} }), 0, 'and a kernel that was not copied is not relabelled'); From 809e209d9e9d7a83cc57fba4f4ca46969b68da09 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 13:58:50 -0300 Subject: [PATCH 13/91] test(xcat-core): measure the SELinux context of the staged Genesis kernel The unit test in this branch drives stage_genesis_payload with a stub runner, so it reads the command mknb builds and never a context on disk. No xcattest case reads one either, so a cell with SELinux enabled cannot show a Genesis kernel that arrives in the TFTP root with the context of the xCAT install tree. genesis_kernel_selinux_context deletes the staged kernel, runs mknb, and reports whether restorecon -F -n -v finds a difference from the policy. cp keeps the context of a destination that exists, so the delete is what makes the case measure the copy. Where SELinux is disabled, or libselinux-utils is absent, the case prints GENESIS_SELINUX_SKIPPED and passes. A permissive node applies labels and is measured like an enforcing one. Measured on an AlmaLinux 9.8 management node with SELinux permissive: without the fix the case reports system_u:object_r:usr_t:s0 against the policy's tftpdir_t and fails, and with the fix it reports tftpdir_t and passes. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../genesis/genesis_kernel_selinux_context | 7 +++ .../testcase/genesis/selinux_context.sh | 58 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 xCAT-test/autotest/testcase/genesis/genesis_kernel_selinux_context create mode 100755 xCAT-test/autotest/testcase/genesis/selinux_context.sh diff --git a/xCAT-test/autotest/testcase/genesis/genesis_kernel_selinux_context b/xCAT-test/autotest/testcase/genesis/genesis_kernel_selinux_context new file mode 100644 index 0000000000..ea583b6a18 --- /dev/null +++ b/xCAT-test/autotest/testcase/genesis/genesis_kernel_selinux_context @@ -0,0 +1,7 @@ +start:genesis_kernel_selinux_context +label:others,genesis +description:verify the Genesis kernel in the TFTP root carries the SELinux context of that path +cmd:/opt/xcat/share/xcat/tools/autotest/testcase/genesis/selinux_context.sh __GETNODEATTR($$CN,arch)__ +check:rc==0 +check:output=~GENESIS_SELINUX_(OK|SKIPPED) +end diff --git a/xCAT-test/autotest/testcase/genesis/selinux_context.sh b/xCAT-test/autotest/testcase/genesis/selinux_context.sh new file mode 100755 index 0000000000..1cf59f896d --- /dev/null +++ b/xCAT-test/autotest/testcase/genesis/selinux_context.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# Read back the SELinux context of the Genesis kernel that mknb stages into the TFTP root. +# +# Usage: selinux_context.sh +# +# The caller asserts on one of three tokens, so no error message can carry the token of a pass: +# GENESIS_SELINUX_OK the staged kernel carries the context the policy declares +# GENESIS_SELINUX_SKIPPED SELinux is off, or the tools to read a context are absent +# GENESIS_SELINUX_FAIL the context is wrong, or the kernel was not staged + +arch="$1" +if [ -z "$arch" ]; then + echo "GENESIS_SELINUX_FAIL: no architecture given" + exit 1 +fi + +tftpdir=$(lsdef -t site -i tftpdir 2>/dev/null | sed -n 's/^[[:space:]]*tftpdir=//p') +[ -n "$tftpdir" ] || tftpdir=/tftpboot +kernel="$tftpdir/xcat/genesis.kernel.$arch" + +if ! command -v selinuxenabled >/dev/null 2>&1; then + echo "GENESIS_SELINUX_SKIPPED: selinuxenabled is absent, so no context can be read" + exit 0 +fi +if ! selinuxenabled; then + echo "GENESIS_SELINUX_SKIPPED: SELinux is disabled on $(hostname)" + exit 0 +fi +# A permissive node applies labels, so it is measured like an enforcing one. +echo "SELinux mode on $(hostname): $(getenforce)" +if ! command -v restorecon >/dev/null 2>&1; then + echo "GENESIS_SELINUX_FAIL: SELinux is enabled and restorecon is absent" + exit 1 +fi + +# cp keeps the context of a destination that already exists, so a correct label from an earlier +# run hides the defect. +rm -f "$kernel" +if ! mknb "$arch"; then + echo "GENESIS_SELINUX_FAIL: mknb $arch returned non-zero" + exit 1 +fi +if [ ! -f "$kernel" ]; then + echo "GENESIS_SELINUX_FAIL: mknb $arch staged no $kernel" + exit 1 +fi +echo "Context of $kernel: $(stat -c %C "$kernel")" + +# restorecon names each file whose context differs from the policy. -F compares the whole +# context, which is what mknb applies. +difference=$(restorecon -F -n -v "$kernel" 2>&1) +if [ -n "$difference" ]; then + echo "$difference" + echo "GENESIS_SELINUX_FAIL: the staged kernel does not carry the context of the policy" + exit 1 +fi +echo "GENESIS_SELINUX_OK: the staged kernel carries the context the policy declares" +exit 0 From aed2df95c9280f97a5661fb07f25641c97396397 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 7 Oct 2026 15:12:33 -0300 Subject: [PATCH 14/91] fix(xcat-core): a failed Genesis kernel relabel is reported as success stage_genesis_payload() discarded the exit status of restorecon, so mknb reported success with the staged kernel still carrying the context of the xCAT install tree. The routine now returns that status, the kernel path and a message that names the relabel, and process_request reports it. A failed copy keeps its own message. selinux_context.sh reads the exit status of restorecon -F -n -v before its output, so a non-zero exit with no output is a failure. The helper also resolves the name mknb stages instead of the architecture it was given: the exact architecture when an OpenEmbedded export is installed, ppc64 for the legacy POWER image. When that kernel is absent it lists the kernels that are present, so a mapping that no longer matches mknb is named rather than read as a missing file. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-server/lib/xcat/plugins/mknb.pm | 26 +++++++++++------- .../testcase/genesis/selinux_context.sh | 27 +++++++++++++++++-- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/xCAT-server/lib/xcat/plugins/mknb.pm b/xCAT-server/lib/xcat/plugins/mknb.pm index b450e442b2..4e77f8c0a1 100644 --- a/xCAT-server/lib/xcat/plugins/mknb.pm +++ b/xCAT-server/lib/xcat/plugins/mknb.pm @@ -372,8 +372,10 @@ Arguments: genesis_type, genesis_dir, tftpdir, arch, tempdir, and an optional run coderef used in place of system() by the tests. Returns: - (rc, source) -- rc is the exit status of the copy that failed, and source - names it, so the caller reports the file it could not read. + (rc, source, error) -- rc is the exit status of the step that failed, + source names the file it acted on, and error is the message for the caller, + which says WHICH step failed. A copy and a relabel fail for different + reasons and need different messages. =cut @@ -386,20 +388,26 @@ sub stage_genesis_payload { # Two copies, each able to fail on its own. Return on the first, so neither the exit # status nor the name of the unreadable file is lost to the one that follows it. $rc = $run->("shopt -s dotglob; GLOBIGNORE=\".:..\" cp -a $a{genesis_dir}/fs/* $a{tempdir}"); - return ($rc, "$a{genesis_dir}/fs") if $rc; + return ($rc, "$a{genesis_dir}/fs", "Failed to copy $a{genesis_dir}/fs contents") if $rc; my $kernel = "$a{tftpdir}/xcat/genesis.kernel.$a{arch}"; # cp -a implies --preserve=all, which carries the SELinux context of the xCAT install # tree into the TFTP root, where the policy declares tftpdir_t. The context also # travels in the security.selinux xattr, so xattr has to go with context here. $rc = $run->("cp -a --no-preserve=context,xattr $a{genesis_dir}/kernel $kernel"); - return ($rc, "$a{genesis_dir}/kernel") if $rc; + return ($rc, "$a{genesis_dir}/kernel", "Failed to copy $a{genesis_dir}/kernel contents") if $rc; # A kernel staged by an earlier xCAT keeps its own context through the copy, so set # the context from the policy. isSELINUX returns 0 when SELinux is enabled. - $run->("restorecon -F $kernel") if xCAT::Utils->isSELINUX() == 0; - return (0, undef); + if (xCAT::Utils->isSELINUX() == 0) { + # A relabel that fails leaves the kernel with the context of the install tree, + # which is the state this routine exists to prevent. Report it. + $rc = $run->("restorecon -F $kernel"); + return ($rc, $kernel, "Failed to set the SELinux context of $kernel") if $rc; + } + return (0, undef, undef); } $rc = $run->("cp -a $a{genesis_dir}/nbroot/* $a{tempdir}"); - return ($rc, "$a{genesis_dir}/nbroot"); + return ($rc, "$a{genesis_dir}/nbroot", + $rc ? "Failed to copy $a{genesis_dir}/nbroot contents" : undef); } sub process_request { @@ -631,12 +639,12 @@ sub process_request { mkpath("$tftpdir/xcat"); } $invisibletouch = 1 if $genesis_type eq 'legacy'; - my ($rc, $failed_src) = stage_genesis_payload( + my ($rc, $failed_src, $failed_error) = stage_genesis_payload( genesis_type => $genesis_type, genesis_dir => $genesis_dir, tftpdir => $tftpdir, arch => $arch, tempdir => $tempdir); if ($rc) { system("rm -rf $tempdir"); - $callback->({ error => ["Failed to copy $failed_src contents"], errorcode => [1] }); + $callback->({ error => [$failed_error], errorcode => [1] }); return; } my $sshdir; diff --git a/xCAT-test/autotest/testcase/genesis/selinux_context.sh b/xCAT-test/autotest/testcase/genesis/selinux_context.sh index 1cf59f896d..1c51000de5 100755 --- a/xCAT-test/autotest/testcase/genesis/selinux_context.sh +++ b/xCAT-test/autotest/testcase/genesis/selinux_context.sh @@ -13,10 +13,23 @@ if [ -z "$arch" ]; then echo "GENESIS_SELINUX_FAIL: no architecture given" exit 1 fi +[ "$arch" = ppc64el ] && arch=ppc64le tftpdir=$(lsdef -t site -i tftpdir 2>/dev/null | sed -n 's/^[[:space:]]*tftpdir=//p') [ -n "$tftpdir" ] || tftpdir=/tftpboot -kernel="$tftpdir/xcat/genesis.kernel.$arch" + +# mknb names the kernel for the architecture of the image it resolved, not for the one it was +# asked about. An OpenEmbedded export keeps the exact architecture. The legacy tree holds one +# combined POWER image under ppc64, so mknb ppc64le writes genesis.kernel.ppc64 there. +netboot="${XCATROOT:-/opt/xcat}/share/xcat/netboot" +if [ -d "$netboot/genesis-openembedded/$arch" ]; then + staged_arch="$arch" +elif [ "$arch" = ppc64le ]; then + staged_arch=ppc64 +else + staged_arch="$arch" +fi +kernel="$tftpdir/xcat/genesis.kernel.$staged_arch" if ! command -v selinuxenabled >/dev/null 2>&1; then echo "GENESIS_SELINUX_SKIPPED: selinuxenabled is absent, so no context can be read" @@ -41,14 +54,24 @@ if ! mknb "$arch"; then exit 1 fi if [ ! -f "$kernel" ]; then + # Name what mknb did stage. A kernel under another name means the architecture mapping + # above no longer matches mknb, which is a different defect from an absent kernel. + echo "Kernels in $tftpdir/xcat: $(ls "$tftpdir"/xcat/genesis.kernel.* 2>/dev/null | tr '\n' ' ')" echo "GENESIS_SELINUX_FAIL: mknb $arch staged no $kernel" exit 1 fi echo "Context of $kernel: $(stat -c %C "$kernel")" # restorecon names each file whose context differs from the policy. -F compares the whole -# context, which is what mknb applies. +# context, which is what mknb applies. It can also fail without naming a file -- no policy +# loaded, or a path it cannot read -- so its exit status decides first. difference=$(restorecon -F -n -v "$kernel" 2>&1) +status=$? +if [ "$status" -ne 0 ]; then + [ -n "$difference" ] && echo "$difference" + echo "GENESIS_SELINUX_FAIL: restorecon -F -n -v exited $status and read no context for $kernel" + exit 1 +fi if [ -n "$difference" ]; then echo "$difference" echo "GENESIS_SELINUX_FAIL: the staged kernel does not carry the context of the policy" From 8e9c1e2ab114b0c2c08b6f854e169f9750e2c68d Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 06:06:33 -0300 Subject: [PATCH 15/91] fix(xcat-core): mysqlsetup leaves /etc/my.cnf with the label of /tmp mysqlsetup commented the bind-address line by writing the result to /tmp/my.cnf and renaming it over the configuration file. A file created in /tmp takes user_tmp_t, and a rename keeps the type of the file it moves, so the management node was left with a MySQL configuration that mysqld is denied read of. The denial survives the command and was seen in three rounds of the SELinux campaign. The temporary path is also a fixed name in a world writable directory, written as root. comment_bind_address now reads the file, substitutes the line and writes the result back through the same file. Truncating in place keeps the inode, which is what carries the label, so no relabel is needed afterwards. The candidate list moves to @BIND_FILES and the resolution order does not change: the Ubuntu mariadb.conf.d file, then /etc/mysql/my.cnf, then /etc/my.cnf. mysqlsetup_bind_address_label.t drives the sub against a scratch tree and asserts the inode survives, that only a line starting with bind is commented, and that no temporary file is left beside the target. With the rewrite put back through a renamed file in /tmp, the inode check is the one check of the thirteen that fails. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-client/bin/mysqlsetup | 82 ++++++++--- .../unit/mysqlsetup_bind_address_label.t | 130 ++++++++++++++++++ 2 files changed, 195 insertions(+), 17 deletions(-) create mode 100644 xCAT-test/unit/mysqlsetup_bind_address_label.t diff --git a/xCAT-client/bin/mysqlsetup b/xCAT-client/bin/mysqlsetup index 2db1a81874..2bb15dcd65 100755 --- a/xCAT-client/bin/mysqlsetup +++ b/xCAT-client/bin/mysqlsetup @@ -764,6 +764,68 @@ sub fixinstalldir =cut #----------------------------------------------------------------------------- +#----------------------------------------------------------------------------- + +=head3 comment_bind_address + + Descriptions: + Comments out the bind-address line of the MySQL configuration, so the + daemon listens on every interface. + + The rewrite goes through the existing file. A temporary file somewhere + else takes the SELinux type of that place, and a rename over the + configuration keeps it, so mysqld is then denied read of its own + configuration. Truncating the file in place keeps its inode and its + label. + Arguments: + None. The candidates are @BIND_FILES. + Returns: + (0, the file it rewrote) or (1, a message). + Example: + my ($rc, $file) = comment_bind_address(); + +=cut + +#----------------------------------------------------------------------------- + +# The candidate configuration files, in the order mysqlsetup reads them. On +# Ubuntu 16.04 the bind-address line is in mariadb.conf.d/50-server.cnf, and on +# SLE15 it is in /etc/my.cnf. The last one is the fallback. +our @BIND_FILES = ( + "/etc/mysql/mariadb.conf.d/50-server.cnf", + "/etc/mysql/my.cnf", + "/etc/my.cnf", +); + +sub comment_bind_address +{ + my $bind_file = $BIND_FILES[-1]; + foreach my $candidate (@BIND_FILES) + { + if (-e $candidate) + { + $bind_file = $candidate; + last; + } + } + + open(my $in, '<', $bind_file) or return (1, "cannot read $bind_file: $!"); + my @lines = <$in>; + close($in); + + foreach my $line (@lines) + { + $line =~ s/^bind/#bind/; + } + + open(my $out, '>', $bind_file) or return (1, "cannot write $bind_file: $!"); + print {$out} @lines or return (1, "cannot write $bind_file: $!"); + close($out) or return (1, "cannot write $bind_file: $!"); + chmod(0644, $bind_file); + + return (0, $bind_file); +} + sub initmysqldb { my $cmd; @@ -868,24 +930,10 @@ sub initmysqldb } } # end AIX only - #bind-adress line in my.cnf should comment out - #on Ubuntu16.04, the bind-address line is in the mariadb.conf.d/50-server.cnf - #on SLE15, the bind-address line is in the /etc/my.cnf - my $bind_file; - if (-e "/etc/mysql/mariadb.conf.d/50-server.cnf") + my ($bind_rc, $bind_file) = comment_bind_address(); + if ($bind_rc != 0) { - $bind_file = "/etc/mysql/mariadb.conf.d/50-server.cnf"; - } elsif (-e "/etc/mysql/my.cnf") - { - $bind_file = "/etc/mysql/my.cnf"; - } else { - $bind_file = "/etc/my.cnf"; - } - $cmd = "sed 's/^bind/#&/' $bind_file > /tmp/my.cnf; mv -f /tmp/my.cnf $bind_file;chmod 644 $bind_file"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " comment the bind-address line in $bind_file failed: $cmd."); + xCAT::MsgUtils->message("E", " comment the bind-address line failed: $bind_file."); exit(1); } diff --git a/xCAT-test/unit/mysqlsetup_bind_address_label.t b/xCAT-test/unit/mysqlsetup_bind_address_label.t new file mode 100644 index 0000000000..562f4e1eab --- /dev/null +++ b/xCAT-test/unit/mysqlsetup_bind_address_label.t @@ -0,0 +1,130 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../perl-xCAT"; +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use File::Temp qw(tempdir); +use Test::More; +use XCAT::Test::File qw(repo_path); + +# mysqlsetup exits on an error, so the CLI load below needs a trap. +BEGIN { + *CORE::GLOBAL::exit = sub { + die bless { status => $_[0] || 0 }, 'MysqlSetupTestExit'; + }; +} + +my $script = $ENV{XCAT_MYSQLSETUP_SOURCE} || repo_path('xCAT-client/bin/mysqlsetup'); +my ($help, $load_error); +{ + local @ARGV = ('--help'); + open(my $output, '>', \$help) or die $!; + local *STDOUT = $output; + do $script; + $load_error = $@; +} +die("Unable to load mysqlsetup: $load_error") + unless ref($load_error) eq 'MysqlSetupTestExit' && $load_error->{status} == 0; + +my $CONF = <<'CONF'; +[mysqld] +datadir=/var/lib/mysql +bind-address = 127.0.0.1 +port=3306 +CONF + +# Writes $CONF to each named path under a fresh scratch tree and points +# mysqlsetup's candidate list at those paths. +sub scratch { + my (@present) = @_; + my $dir = tempdir(CLEANUP => 1); + my @candidates = map { "$dir/$_" } qw( + etc/mysql/mariadb.conf.d/50-server.cnf + etc/mysql/my.cnf + etc/my.cnf + ); + foreach my $index (@present) { + my $path = $candidates[$index]; + (my $parent = $path) =~ s{/[^/]+$}{}; + make_path($parent); + write_text($path, $CONF); + } + return ($dir, \@candidates); +} + +# The first candidate that exists is the one it rewrites. +{ + my ($dir, $candidates) = scratch(0, 2); + local @main::BIND_FILES = @{$candidates}; + my ($rc, $file) = main::comment_bind_address(); + is($rc, 0, 'the rewrite succeeds'); + is($file, $candidates->[0], 'the first candidate that exists is the one it rewrites'); + like(read_text($candidates->[0]), qr/^#bind-address/m, '... and its bind line is commented'); + unlike(read_text($candidates->[2]), qr/^#bind/m, '... and a later candidate is untouched'); +} + +# With no candidate present it falls back to the last one, which is /etc/my.cnf. +{ + my ($dir, $candidates) = scratch(1); + local @main::BIND_FILES = @{$candidates}; + my ($rc, $file) = main::comment_bind_address(); + is($rc, 0, 'the second candidate is rewritten when the first is absent'); + is($file, $candidates->[1], '... and it is the file that exists'); +} + +# THE DEFECT. A temporary file written somewhere else takes the SELinux type of +# that place, and a rename over the configuration keeps it. mysqld is then +# denied read of its own configuration. The inode is what carries the label, so +# an in-place rewrite is measured by the inode surviving. +{ + my ($dir, $candidates) = scratch(2); + local @main::BIND_FILES = @{$candidates}; + my $target = $candidates->[2]; + my $before = (stat($target))[1]; + my ($rc, $file) = main::comment_bind_address(); + is($rc, 0, 'the fallback candidate is rewritten'); + my $after = (stat($target))[1]; + is($after, $before, 'the rewrite keeps the inode of the configuration file'); + + # A leftover temporary file beside the target is the other half of the + # anti-pattern: it says a rename was used. + opendir(my $dh, "$dir/etc") or die $!; + my @left = sort grep { !/^\.\.?$/ } readdir($dh); + closedir($dh); + is_deeply(\@left, ['my.cnf'], 'no temporary file is left beside the configuration'); +} + +# The content is rewritten, and only the bind line changes. +{ + my ($dir, $candidates) = scratch(2); + local @main::BIND_FILES = @{$candidates}; + main::comment_bind_address(); + my $after = read_text($candidates->[2]); + is($after, "[mysqld]\ndatadir=/var/lib/mysql\n#bind-address = 127.0.0.1\nport=3306\n", + 'only the bind-address line is commented'); +} + +# A line that merely contains "bind" is not a bind-address line. +{ + my ($dir, $candidates) = scratch(2); + local @main::BIND_FILES = @{$candidates}; + write_text($candidates->[2], "skip-name-resolve\n# bind-address = 1.2.3.4\nbind-address=0.0.0.0\n"); + main::comment_bind_address(); + is(read_text($candidates->[2]), + "skip-name-resolve\n# bind-address = 1.2.3.4\n#bind-address=0.0.0.0\n", + 'a line that does not start with bind is left alone'); +} + +# An unreadable file is reported rather than ignored. +{ + my ($dir, $candidates) = scratch(); + local @main::BIND_FILES = @{$candidates}; + my ($rc, $message) = main::comment_bind_address(); + is($rc, 1, 'an absent configuration file is an error'); + like($message, qr/\Q$candidates->[2]\E/, '... and the message names the file'); +} + +done_testing(); From 07ba4abbac5ba609a45531ac608663a79d06125e Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:59:12 -0300 Subject: [PATCH 16/91] test(xcat-core): measure xCAT on an enforcing management node No xcattest case checks xCAT on an enforcing management node, so an SELinux denial in xcatd, httpd or the REST API reaches a release unseen. selinux_xcatd_domain checks that xcatd and its workers run in unconfined_service_t and not in initrc_t. selinux_mn_labels checks the xcat module, the /install and rootimg file contexts, and that httpd serves a file from /install and from /tftpboot. selinux_restapi_avc gets a site attribute through xcatws.cgi. The last two read the audit log from the start of the case and expect no AVC record. Every case first requires getenforce to report Enforcing, and none carries the ci_test label. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases0 | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 xCAT-test/autotest/testcase/selinux/cases0 diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 new file mode 100644 index 0000000000..ca37c7c01c --- /dev/null +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -0,0 +1,82 @@ +start:selinux_xcatd_domain +description:on an enforcing management node, xcatd and its workers run in unconfined_service_t +label:mn_only,selinux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:ps -o label= -p "$(cat /run/xcatd.pid)" +check:rc==0 +check:output=~:unconfined_service_t: +cmd:ps -eo label,args | grep '[x]catd:' +check:rc==0 +check:output=~:unconfined_service_t: +check:output!~initrc_t +end + +start:selinux_mn_labels +description:on an enforcing management node, xCAT-selinux labels /install, httpd serves /install and /tftpboot, and SELinux denies nothing +label:mn_only,selinux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_mn_labels.start' +check:rc==0 +cmd:rpm -q xCAT-selinux +check:rc==0 +cmd:sh -c 'semodule -l | grep -x -E "xcat([[:space:]].*)?"' +check:rc==0 +cmd:matchpathcon /install +check:rc==0 +check:output=~:public_content_t: +cmd:matchpathcon /install/netboot/alma10/x86_64/compute/rootimg/etc/passwd +check:rc==0 +check:output=~<> +cmd:ls -dZ /install +check:rc==0 +check:output=~:public_content_t: +cmd:ls -dZ /install/postscripts +check:rc==0 +check:output=~:public_content_t: +cmd:matchpathcon /tftpboot/xcat +check:rc==0 +check:output=~:tftpdir_t: +cmd:curl -s -f -o /dev/null http://localhost/install/postscripts/xcatdsklspost +check:rc==0 +cmd:sh -c 'mkdir -p /tftpboot/xcat && echo xcat-selinux-probe-ok > /tftpboot/xcat/selinux_mn_labels.probe' +check:rc==0 +cmd:ls -Z /tftpboot/xcat/selinux_mn_labels.probe +check:rc==0 +check:output=~:tftpdir_t: +cmd:curl -s -f http://localhost/tftpboot/xcat/selinux_mn_labels.probe +check:rc==0 +check:output=~^xcat-selinux-probe-ok$ +cmd:rm -f /tftpboot/xcat/selinux_mn_labels.probe +check:rc==0 +cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_mn_labels.start)' +check:rc==1 +check:output=~ +cmd:rm -f /tmp/selinux_mn_labels.start +end + +start:selinux_restapi_avc +description:on an enforcing management node, xcatws.cgi reaches xcatd and SELinux denies nothing +label:mn_only,selinux,restapi +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_restapi_avc.start' +check:rc==0 +cmd:sh -c 'rpm -q mod_ssl || dnf install -y mod_ssl' +check:rc==0 +cmd:systemctl restart httpd +check:rc==0 +cmd:tabch key=xcat,username=__GETTABLEVALUE(key,system,username,passwd)__ passwd.password=__GETTABLEVALUE(key,system,password,passwd)__ +check:rc==0 +cmd:username=__GETTABLEVALUE(key,system,username,passwd)__;password=__GETTABLEVALUE(key,system,password,passwd)__;curl -k -s -f "https://localhost/xcatws/globalconf/attrs/master?userName=$username&userPW=$password" +check:rc==0 +check:output=~clustersite +cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_restapi_avc.start)' +check:rc==1 +check:output=~ +cmd:rm -f /tmp/selinux_restapi_avc.start +end From 2efdce66b9daf53c426cee9224a89c410575b79e Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:52:43 -0300 Subject: [PATCH 17/91] test(xcat-core): capture the missing xcat_t domain xCAT ships no process domain. xcatd runs in unconfined_service_t, and a client command runs in the domain of its caller, so no rule in the policy module reaches either of them. xcat_selinux_package.t now asserts the domain, the two entrypoint types, the file contexts of the three entrypoints, the transition from systemd and the transition from unconfined_t, and that no confined user domain gets a transition. 9 of its 59 checks fail on this commit. selinux_xcatd_domain asserts the live context of xcatd and its workers, and the new selinux_client_domain case asserts the entrypoint labels and the transition rules the loaded policy holds. The two no-denial cases now count only the denials the kernel enforced, because xcat_t is permissive and each access it needs is recorded. They also pass --input-logs: on EL10 audit 4.0.3 ausearch reads the journal rather than the file auditd.conf names, and answered "" on a node whose log held 1032 denials. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases0 | 57 +++++++++++++++++----- xCAT-test/unit/xcat_selinux_package.t | 46 +++++++++++++++++ 2 files changed, 90 insertions(+), 13 deletions(-) diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index ca37c7c01c..649f542986 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -1,20 +1,47 @@ start:selinux_xcatd_domain -description:on an enforcing management node, xcatd and its workers run in unconfined_service_t +description:on an enforcing management node, xcatd and its workers run in xcat_t label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ cmd:ps -o label= -p "$(cat /run/xcatd.pid)" check:rc==0 -check:output=~:unconfined_service_t: +check:output=~:xcat_t: cmd:ps -eo label,args | grep '[x]catd:' check:rc==0 -check:output=~:unconfined_service_t: +check:output=~:xcat_t: check:output!~initrc_t +check:output!~unconfined_service_t +end + +start:selinux_client_domain +description:on an enforcing management node, a client command entered through xcatclient runs in xcat_t +label:mn_only,selinux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:ls -Z /opt/xcat/bin/xcatclient +check:rc==0 +check:output=~:xcat_client_exec_t: +cmd:ls -Z /opt/xcat/sbin/xcatd +check:rc==0 +check:output=~:xcatd_exec_t: +cmd:sh -c 'rpm -q setools-console || dnf install -y setools-console' +check:rc==0 +cmd:sesearch -T -s init_t -t xcatd_exec_t -c process +check:rc==0 +check:output=~xcat_t +cmd:sesearch -T -s unconfined_t -t xcat_client_exec_t -c process +check:rc==0 +check:output=~xcat_t +cmd:sesearch -T -s unconfined_t -t bin_t -c process +check:output!~xcat_t +cmd:lsxcatd -v +check:rc==0 end start:selinux_mn_labels -description:on an enforcing management node, xCAT-selinux labels /install, httpd serves /install and /tftpboot, and SELinux denies nothing +description:on an enforcing management node, xCAT-selinux labels /install, httpd serves /install and /tftpboot, and no denial is enforced label:mn_only,selinux cmd:getenforce check:rc==0 @@ -52,14 +79,16 @@ check:rc==0 check:output=~^xcat-selinux-probe-ok$ cmd:rm -f /tftpboot/xcat/selinux_mn_labels.probe check:rc==0 -cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_mn_labels.start)' -check:rc==1 -check:output=~ -cmd:rm -f /tmp/selinux_mn_labels.start +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts "$(cat /tmp/selinux_mn_labels.start)" > /tmp/selinux_mn_labels.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_mn_labels.avc' +check:rc==0 +cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_mn_labels.avc | wc -l' +check:rc==0 +check:output=~^0$ +cmd:rm -f /tmp/selinux_mn_labels.start /tmp/selinux_mn_labels.avc end start:selinux_restapi_avc -description:on an enforcing management node, xcatws.cgi reaches xcatd and SELinux denies nothing +description:on an enforcing management node, xcatws.cgi reaches xcatd and no denial is enforced label:mn_only,selinux,restapi cmd:getenforce check:rc==0 @@ -75,8 +104,10 @@ check:rc==0 cmd:username=__GETTABLEVALUE(key,system,username,passwd)__;password=__GETTABLEVALUE(key,system,password,passwd)__;curl -k -s -f "https://localhost/xcatws/globalconf/attrs/master?userName=$username&userPW=$password" check:rc==0 check:output=~clustersite -cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_restapi_avc.start)' -check:rc==1 -check:output=~ -cmd:rm -f /tmp/selinux_restapi_avc.start +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts "$(cat /tmp/selinux_restapi_avc.start)" > /tmp/selinux_restapi_avc.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_restapi_avc.avc' +check:rc==0 +cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_restapi_avc.avc | wc -l' +check:rc==0 +check:output=~^0$ +cmd:rm -f /tmp/selinux_restapi_avc.start /tmp/selinux_restapi_avc.avc end diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index d98b64d5ad..478d426592 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -110,6 +110,22 @@ is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)?'}, '<>' '... and a statelite rootimg too'); ok(!(grep { m{^/tftpboot} } keys %fc), '/tftpboot keeps the stock tftpdir_t'); +# The type of an fc entry, dropping the file-type flag that executables carry. +sub fc_type { + my ($path) = @_; + my $spec = $fc{$path} // return undef; + return $spec =~ /gen_context\(system_u:object_r:(\w+),s0\)/ ? $1 : $spec; +} + +# restorecon labels the file that execve resolves to. /usr/sbin/xcatd is a +# symlink, and a symlink is never an entrypoint. +is(fc_type('/opt/xcat/sbin/xcatd'), 'xcatd_exec_t', 'xcatd is the entrypoint of the daemon'); +ok(!exists $fc{'/usr/sbin/xcatd'}, '... and the symlink to it carries no context'); +foreach my $client (qw(xcatclient xcatclientnnr)) { + is(fc_type("/opt/xcat/bin/$client"), 'xcat_client_exec_t', + "$client is the entrypoint of the client commands"); +} + # The module source is the artifact: checkmodule compiles this text as written. # Each rule here is justified by a measured denial; see # docs/source/advanced/selinux/index.rst and the policy campaign REASONING.md. @@ -171,6 +187,36 @@ is_deeply([ grep { /^kernel_t / } @rules ], [], 'no rule grants kernel_t anything'); +######################################## +# +# The xcat_t domain +# + +like($te, qr/^type xcat_t;$/m, 'xcat.te declares one domain for xcatd and the clients'); +like($te, qr/^permissive xcat_t;$/m, + '... which is permissive while the CI collects the accesses it needs'); +unlike($te, qr/^permissive (?!xcat_t\b)/m, '... and no other domain is made permissive'); + +like($te, qr/^init_daemon_domain\(xcat_t, xcatd_exec_t\)$/m, + 'systemd starts xcatd in xcat_t'); +like($te, qr/^application_domain\(xcat_t, xcat_client_exec_t\)$/m, + 'a client command entered through xcatclient runs in xcat_t'); + +# xcatd and xcatclient are Perl scripts. The kernel labels the new process from +# the script, then the domain runs the interpreter named in the shebang. +like($te, qr/^corecmd_exec_bin\(xcat_t\)$/m, 'xcat_t runs the interpreter of its own script'); + +# Collects the source domains that xcat.te gives an automatic transition. +my @domtrans = $te =~ /^\s*domtrans_pattern\((\w+), xcat_client_exec_t, xcat_t\)$/mg; +is_deeply(\@domtrans, ['unconfined_t'], + 'only the unconfined domain transitions into xcat_t'); + +# A confined user domain that entered a permissive xcat_t would leave its own +# confinement, so the module gives it no transition. +foreach my $domain (qw(user_t staff_t sysadm_t guest_t xguest_t)) { + unlike($te, qr/\b\Q$domain\E\b/, "$domain gets no rule in xcat.te"); +} + # A management node or a service node with the targeted policy installs the module. foreach my $pkg (qw(xCAT-server xCATsn)) { my @lines = lines_of("$root/$pkg/$pkg.spec"); From 0f0c2a1f94570b759bf64ae1da7e552c6ded7cd1 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:55:21 -0300 Subject: [PATCH 18/91] feat(xcat-core): run xcatd and the xCAT clients in the xcat_t domain xCAT had no process domain. xcatd ran in unconfined_service_t, where the policy constrains nothing, and each client command ran in the domain of its caller. The module could therefore only grant access to other services. xcat.te declares the xcat_t domain, the xcatd_exec_t and xcat_client_exec_t entrypoints, the transition from systemd, and the transition from unconfined_t for a client command. xcat.fc labels /opt/xcat/sbin/xcatd and the two xcatclient scripts, which 115 command names reach through a symlink. xcat_t is permissive, and the policy source declares it. The host stays enforcing, and the CI collects the accesses the domain needs. The module grants the domain one access of its own: the execute of the interpreter that its Perl entrypoint names. A confined user domain gets no transition, so it keeps its own confinement. The module compiles at version 19 in the alma+epel-10-x86_64 mock root, and the binary carries (typepermissive xcat_t) and both type transitions. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 6 ++++++ xCAT-selinux/xcat.te | 46 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 300e3c8d7a..6466a70e29 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -1,3 +1,9 @@ +# The entrypoints of the xcat_t domain. /usr/sbin/xcatd is a symlink, and +# execve resolves it, so the context belongs to the file it names. +/opt/xcat/sbin/xcatd -- gen_context(system_u:object_r:xcatd_exec_t,s0) +/opt/xcat/bin/xcatclient -- gen_context(system_u:object_r:xcat_client_exec_t,s0) +/opt/xcat/bin/xcatclientnnr -- gen_context(system_u:object_r:xcat_client_exec_t,s0) + /install(/.*)? gen_context(system_u:object_r:public_content_t,s0) # A rootimg keeps the labels of its own OS, so restorecon must not change them. diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 81d5f5e2d5..5e60003961 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -1,4 +1,4 @@ -policy_module(xcat, 1.0.0) +policy_module(xcat, 1.1.0) gen_require(` type httpd_t, httpd_sys_script_t, tftpdir_t, ntop_port_t; @@ -6,6 +6,45 @@ gen_require(` type useradd_t, groupadd_t, public_content_t; ') +######################################## +# +# The xCAT domain +# + +# xcatd and the client commands share one domain. Each command sends its +# request to xcatd, and the two read the same tables and the same /install tree. +type xcat_t; +type xcatd_exec_t; +init_daemon_domain(xcat_t, xcatd_exec_t) + +# /opt/xcat/bin/xcatclient is the entrypoint of every dispatching command. +type xcat_client_exec_t; +application_domain(xcat_t, xcat_client_exec_t) + +# The CI collects the accesses xcat_t needs while the host stays enforcing. +# A later release removes this line and the domain becomes enforcing. +permissive xcat_t; + +# xcatd and xcatclient are Perl scripts. The kernel enters the domain on the +# script, so the domain runs the interpreter of the shebang line itself. +corecmd_exec_bin(xcat_t) + +optional_policy(` + gen_require(` + type unconfined_t; + ') + + # Targeted policy gives root unconfined_t, which is where the administrator + # and the CI run the commands. A confined user domain gets no transition: it + # would leave its own confinement for a permissive domain. + domtrans_pattern(unconfined_t, xcat_client_exec_t, xcat_t) +') + +######################################## +# +# Access for the services that read the xCAT trees +# + # httpd serves /tftpboot through the AliasMatch in xcat.conf. The stock policy lets only tftpd read tftpdir_t. # mmap_read_file_perms, not read_file_perms: httpd maps the per-node xnba boot config it serves. allow httpd_t tftpdir_t:dir list_dir_perms; @@ -18,9 +57,8 @@ allow httpd_sys_script_t ntop_port_t:tcp_socket name_connect; # xdcp and "updatenode -F" copy /etc/shadow to the nodes and into a rootimg. # rsync_export_all_ro holds the read, and rsync_full_access does not grant it: # shadow_t is not in non_auth_file_type. These two rules are narrower than -# either boolean. They are reached only where rsync runs in rsync_t, which -# needs a system-service caller; xcatd is unconfined_service_t and does not -# transition there. +# either boolean. They are reached only where rsync runs in rsync_t, and xcat_t +# has no transition to it. allow rsync_t shadow_t:file { getattr open read }; # rsync preserves the mode of /etc/shadow, so it writes a target it created at From 07b7041011e8b667a5a3e989a5043b5181da5a97 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:55:48 -0300 Subject: [PATCH 19/91] docs(xcat-core): two comments name the domain xcatd no longer runs in The unit file and xcatd_service_direct_exec.t said that a direct ExecStart keeps xcatd out of initrc_t and in unconfined_service_t. The entrypoint of the xcat_t domain is the xcatd script, so a shell in ExecStart now costs the domain, not the confinement. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-server/etc/init.d/xcatd.service | 3 ++- xCAT-test/unit/xcatd_service_direct_exec.t | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/xCAT-server/etc/init.d/xcatd.service b/xCAT-server/etc/init.d/xcatd.service index a8e1453aee..6e368ef37b 100644 --- a/xCAT-server/etc/init.d/xcatd.service +++ b/xCAT-server/etc/init.d/xcatd.service @@ -3,7 +3,8 @@ Description=xCAT management service After=network.target syslog.service [Service] -# systemd runs a shell in initrc_t. xcatd must start directly to run in unconfined_service_t. +# A shell in ExecStart runs in initrc_t. xcatd must start directly, so the +# kernel enters xcat_t on the xcatd script. Environment=XCATROOT=/opt/xcat PERL_BADLANG=0 Environment=PATH=/opt/xcat/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin EnvironmentFile=-/etc/sysconfig/xcat diff --git a/xCAT-test/unit/xcatd_service_direct_exec.t b/xCAT-test/unit/xcatd_service_direct_exec.t index 22449baf84..3919da56c1 100644 --- a/xCAT-test/unit/xcatd_service_direct_exec.t +++ b/xCAT-test/unit/xcatd_service_direct_exec.t @@ -30,7 +30,7 @@ sub service_settings { my $service = service_settings($unit_file); -# systemd starts a shell in initrc_t and a bin_t binary in unconfined_service_t. +# systemd starts a shell in initrc_t, which is not an entrypoint of xcat_t. my @exec = @{ $service->{ExecStart} || [] }; is(scalar(@exec), 1, 'the unit has one ExecStart'); my ($program) = split /\s+/, ($exec[0] // ''); From 167f04d2e9b8de29fcc28c9a0d749a1fa3946b31 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:56:37 -0300 Subject: [PATCH 20/91] docs(selinux): document the xcat_t domain and the management-node scope The pull request adds a process domain and says nowhere which machine it covers, which commands enter it, or why the domain is permissive while the host is enforcing. The new page names the scope as the management node, lists the three entrypoint files and the rule that the unit must exec xcatd and not a shell, and states that the permissive declaration is in the policy source and a later release removes it. It gives the commands that read the domain of xcatd and the enforced denials of a run, with the --input-logs finding: ausearch read the journal on an EL10 node whose log held 1032 denials. It also records why a confined user domain gets no transition, and that the file permissions still decide what a user can read. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/index.rst | 1 + docs/source/advanced/selinux/index.rst | 95 ++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 docs/source/advanced/selinux/index.rst diff --git a/docs/source/advanced/index.rst b/docs/source/advanced/index.rst index 9bf823c5d9..04d6f3dc02 100644 --- a/docs/source/advanced/index.rst +++ b/docs/source/advanced/index.rst @@ -9,6 +9,7 @@ Advanced Topics migration/index.rst confluent/index.rst goconserver/index.rst + selinux/index.rst docker/dockerized_xcat/run_xcat_in_docker_host.rst domain_name_resolution/index.rst gpu/index.rst diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst new file mode 100644 index 0000000000..1a9ef99818 --- /dev/null +++ b/docs/source/advanced/selinux/index.rst @@ -0,0 +1,95 @@ +SELinux +======= + +xCAT runs on a management node that has SELinux in enforcing mode. An xCAT +installation does not change the SELinux mode of the machine. + +Scope +----- + +This version covers the management node. A service node and a compute node are +out of scope: no run measures them, and xCAT does not select their mode. + +The xcat_t domain +----------------- + +``xcatd`` and the xCAT client commands run in one domain, ``xcat_t``. The +``xCAT-selinux`` package labels the three files the domain is entered through: + +============================== ======================= +File Type +============================== ======================= +/opt/xcat/sbin/xcatd ``xcatd_exec_t`` +/opt/xcat/bin/xcatclient ``xcat_client_exec_t`` +/opt/xcat/bin/xcatclientnnr ``xcat_client_exec_t`` +============================== ======================= + +systemd enters ``xcat_t`` on the ``xcatd`` script, so the ``ExecStart`` of the +unit must name ``xcatd`` and not a shell. 115 command names are symlinks to +``xcatclient`` or ``xcatclientnnr``, and each one enters the domain through the +file it points to. ``/usr/sbin/xcatd`` is a symlink, and ``execve`` resolves it, +so the context belongs to the file in ``/opt/xcat``. + +Read the domain of the running daemon with:: + + ps -o label= -p "$(cat /run/xcatd.pid)" + ps -eo label,args | grep '[x]catd:' + +The domain is permissive +------------------------ + +The policy source declares ``permissive xcat_t;``. The host policy stays +enforcing, and the kernel records each access that ``xcat_t`` makes outside the +rules rather than refusing it. The CI collects those records, and each rule the +module gains comes from one of them. A later release removes the declaration +and the domain becomes enforcing. + +List the permissive domains of the loaded policy with:: + + semodule -l | grep -x xcat + seinfo --permissive + +A denial that the kernel enforced carries ``permissive=0``. On a management node +of this version, only such a record reports a refused access:: + + ausearch --input-logs -m AVC,USER_AVC -ts today | grep permissive=0 + +Commands run by a user +---------------------- + +Targeted policy gives root the ``unconfined_t`` domain, and the module +transitions from there into ``xcat_t``. A confined user domain, such as +``staff_t``, gets no transition: it would leave its own confinement for a +permissive domain. A command run from such a domain stays in it, and SELinux +still applies the rules of that domain. + +SELinux does not replace the file permissions. A user who cannot read +``/etc/xcat`` cannot read it in ``xcat_t`` either. + +The access the module grants other services +------------------------------------------- + +``xcat_t`` is one part of the module. The rest grants the access that the +services around xCAT need: + +* ``/install`` is ``public_content_t``, so ``httpd`` serves it. Each ``rootimg`` + tree is left out of the relabel, because it keeps the labels of its own + operating system. +* ``httpd`` reads and maps the ``/tftpboot`` files that ``xcat.conf`` serves. +* ``xcatws.cgi`` connects to the ``xcatd`` port. +* ``rsync`` reads ``/etc/shadow`` and writes a copy it created at mode 0000. +* ``useradd`` and ``groupadd`` read the ``rootimg`` ``/var/run`` symlink, which + the rpm scriptlets of a ``genimage`` build need. + +Reading denials +--------------- + +``ausearch`` without ``--input-logs`` reported nothing on an AlmaLinux 10 node +whose log held 1032 denials, because audit 4.0.3 reads the journal rather than +the file ``auditd.conf`` names. Pass ``--input-logs``, or read the log file, +before you conclude that a machine is clean. + +The kernel also drops audit records printed before ``auditd`` starts, at +``printk_ratelimit_burst`` and with no notice. Boot with +``sysctl.kernel.printk_ratelimit=0`` to see that window whole. A count taken +without it is a lower bound. From 7b92b9503497cc41f7ac061ea4c6e8ee8dec8bbb Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:28:02 -0300 Subject: [PATCH 21/91] test(xcat-core): capture the client exec that SELinux refuses A client command run from unconfined_t fails under enforcing: /opt/xcat/bin/lsxcatd: /usr/bin/perl: bad interpreter: Permission denied Measured on xcat162-mn-tmp-286, AlmaLinux 10.2, with the module loaded and the entrypoints labelled. The same command returns 0 under setenforce 0. The transition computes unconfined_u:unconfined_r:xcat_t, and the module does not authorize unconfined_r for xcat_t, so the context is invalid and the kernel refuses the exec. The permissive declaration does not help, because an invalid context is not a permission check. The record is SELINUX_ERR, op=security_compute_sid, which no AVC query finds. xcat_selinux_package.t asserts the role statement, and check 49 of 60 fails on this commit. selinux_client_domain asserts that lsxcatd returns 0 and prints its version under enforcing, that seinfo reports xcat_t for unconfined_r, and that the run leaves no invalid_context record. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases0 | 10 ++++++++++ xCAT-test/unit/xcat_selinux_package.t | 8 ++++++++ 2 files changed, 18 insertions(+) diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index 649f542986..8a7961d35e 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -20,6 +20,8 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_client_domain.start' +check:rc==0 cmd:ls -Z /opt/xcat/bin/xcatclient check:rc==0 check:output=~:xcat_client_exec_t: @@ -36,8 +38,16 @@ check:rc==0 check:output=~xcat_t cmd:sesearch -T -s unconfined_t -t bin_t -c process check:output!~xcat_t +cmd:sh -c 'seinfo -runconfined_r -x | grep -w xcat_t' +check:rc==0 cmd:lsxcatd -v check:rc==0 +check:output=~^Version +cmd:sh -c 'ausearch --input-logs -m SELINUX_ERR -ts "$(cat /tmp/selinux_client_domain.start)" 2>&1 | grep -F invalid_context | wc -l' +check:rc==0 +check:output=~^0$ +cmd:rm -f /tmp/selinux_client_domain.start +check:rc==0 end start:selinux_mn_labels diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 478d426592..e59621d7bd 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -211,6 +211,14 @@ my @domtrans = $te =~ /^\s*domtrans_pattern\((\w+), xcat_client_exec_t, xcat_t\) is_deeply(\@domtrans, ['unconfined_t'], 'only the unconfined domain transitions into xcat_t'); +# The transition computes unconfined_u:unconfined_r:xcat_t. Without this +# statement that context is invalid, and the kernel refuses the exec with +# EACCES whether or not xcat_t is permissive. A permissive domain does not +# help: an invalid context is not a permission check, and the record is +# SELINUX_ERR, which no AVC query finds. +like($te, qr/^\s*role unconfined_r types xcat_t;$/m, + 'unconfined_r is authorized for xcat_t'); + # A confined user domain that entered a permissive xcat_t would leave its own # confinement, so the module gives it no transition. foreach my $domain (qw(user_t staff_t sysadm_t guest_t xguest_t)) { From 7086f2de957882d9d23b05b159a4710cec45cee0 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:28:27 -0300 Subject: [PATCH 22/91] fix(xcat-core): a client command cannot exec under enforcing The transition into xcat_t computes unconfined_u:unconfined_r:xcat_t, and the module did not authorize unconfined_r for that type. The context is then invalid, so the kernel refuses the exec of the interpreter and the command fails with "bad interpreter: Permission denied". Every client command run by the administrator or the CI failed this way on an enforcing node, while xcatd itself was unaffected: a daemon domain carries the daemon attribute, which system_r already holds. xcat.te now states "role unconfined_r types xcat_t" beside the transition. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 5e60003961..184522d08e 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -32,8 +32,15 @@ corecmd_exec_bin(xcat_t) optional_policy(` gen_require(` type unconfined_t; + role unconfined_r; ') + # The transition computes unconfined_u:unconfined_r:xcat_t. The role must + # hold the type, or the context is invalid and the kernel refuses the exec + # with EACCES. Permissive does not cover it: an invalid context is not a + # permission check, and the record is SELINUX_ERR, not AVC. + role unconfined_r types xcat_t; + # Targeted policy gives root unconfined_t, which is where the administrator # and the CI run the commands. A confined user domain gets no transition: it # would leave its own confinement for a permissive domain. From 8858c2f636dbe98524f56eaa353e2c9c1a909fe8 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:31:23 -0300 Subject: [PATCH 23/91] fix(xcat-test): ausearch refuses the start time the SELinux cases pass The cases marked the start of a window with date "+%x %T" and passed the result to ausearch -ts. Audit 4.0.3 rejects it: Invalid start time (10/14/2026 20:00:00). Hour, Minute, and Second are required. ausearch then exits 1 with that message and no records. Measured on xcat162-mn-tmp-286: the query returned 0 records where 653 were in the log, and MM/DD/YY and ISO forms are refused the same way. Only a bare HH:MM:SS is accepted. Each no-denial check therefore reported a clean node whatever the node did, which is the defect --input-logs was meant to remove. Each case now seeds an ausearch --checkpoint file at its start and reads the new events with the same file, which is audit's own mechanism and has no date to misparse. A check before the count asserts that ausearch answered at all: the output has to hold a record or "", and an error message holds neither. Verified on the same node, where the guard exits 1 on a deliberately broken query, 0 on an empty window, and the read after a client run returned 63 new records. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases0 | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index 8a7961d35e..364ac84ab1 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -20,7 +20,7 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_client_domain.start' +cmd:sh -c 'rm -f /tmp/selinux_client_domain.ck; ausearch --input-logs -m SELINUX_ERR --checkpoint /tmp/selinux_client_domain.ck -ts today > /dev/null 2>&1; true' check:rc==0 cmd:ls -Z /opt/xcat/bin/xcatclient check:rc==0 @@ -43,10 +43,12 @@ check:rc==0 cmd:lsxcatd -v check:rc==0 check:output=~^Version -cmd:sh -c 'ausearch --input-logs -m SELINUX_ERR -ts "$(cat /tmp/selinux_client_domain.start)" 2>&1 | grep -F invalid_context | wc -l' +cmd:sh -c 'ausearch --input-logs -m SELINUX_ERR --checkpoint /tmp/selinux_client_domain.ck > /tmp/selinux_client_domain.err 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_client_domain.err' +check:rc==0 +cmd:sh -c 'grep -F invalid_context /tmp/selinux_client_domain.err | wc -l' check:rc==0 check:output=~^0$ -cmd:rm -f /tmp/selinux_client_domain.start +cmd:rm -f /tmp/selinux_client_domain.ck /tmp/selinux_client_domain.err check:rc==0 end @@ -56,7 +58,7 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_mn_labels.start' +cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; true' check:rc==0 cmd:rpm -q xCAT-selinux check:rc==0 @@ -89,12 +91,12 @@ check:rc==0 check:output=~^xcat-selinux-probe-ok$ cmd:rm -f /tftpboot/xcat/selinux_mn_labels.probe check:rc==0 -cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts "$(cat /tmp/selinux_mn_labels.start)" > /tmp/selinux_mn_labels.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_mn_labels.avc' +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck > /tmp/selinux_mn_labels.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_mn_labels.avc' check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_mn_labels.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:rm -f /tmp/selinux_mn_labels.start /tmp/selinux_mn_labels.avc +cmd:rm -f /tmp/selinux_mn_labels.ck /tmp/selinux_mn_labels.avc end start:selinux_restapi_avc @@ -103,7 +105,7 @@ label:mn_only,selinux,restapi cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_restapi_avc.start' +cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; true' check:rc==0 cmd:sh -c 'rpm -q mod_ssl || dnf install -y mod_ssl' check:rc==0 @@ -114,10 +116,10 @@ check:rc==0 cmd:username=__GETTABLEVALUE(key,system,username,passwd)__;password=__GETTABLEVALUE(key,system,password,passwd)__;curl -k -s -f "https://localhost/xcatws/globalconf/attrs/master?userName=$username&userPW=$password" check:rc==0 check:output=~clustersite -cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts "$(cat /tmp/selinux_restapi_avc.start)" > /tmp/selinux_restapi_avc.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_restapi_avc.avc' +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck > /tmp/selinux_restapi_avc.avc 2>&1; grep -q -e "^type=" -e "no matches" /tmp/selinux_restapi_avc.avc' check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_restapi_avc.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:rm -f /tmp/selinux_restapi_avc.start /tmp/selinux_restapi_avc.avc +cmd:rm -f /tmp/selinux_restapi_avc.ck /tmp/selinux_restapi_avc.avc end From d3739aa512421528f3b97e596c6d64692c9d344b Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:33:39 -0300 Subject: [PATCH 24/91] test(xcat-core): capture the labels the erase of xCAT-selinux leaves behind Removing the package removes the module, so xcatd_exec_t and xcat_client_exec_t leave the policy and each file that carried one becomes unlabeled_t. Measured on xcat162-mn-tmp-286 after dnf remove: system_u:object_r:unlabeled_t:s0 /opt/xcat/sbin/xcatd system_u:object_r:unlabeled_t:s0 /opt/xcat/bin/xcatclient system_u:object_r:unlabeled_t:s0 /opt/xcat/bin/xcatclientnnr restorecon -n reported all three as pending, and /install kept public_content_t, which the stock policy does not define for it. xcat_selinux_package.t asserts the %preun snapshot and the %postun relabel that an erase needs, guarded for the erase only. 3 of its 64 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index e59621d7bd..dfbd6b86bd 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -91,11 +91,22 @@ like(join("\n", @{ $spec->{post} || [] }), '%post installs the module'); like(join("\n", @{ $spec->{postun} || [] }), qr/^%selinux_modules_uninstall -s targeted xcat$/m, '%postun removes the module'); +# On an erase the module leaves the policy, so each file labelled with one of +# its types becomes unlabeled_t. %preun takes the snapshot that %postun needs +# to relabel them, because %pre does not run on an erase. +like(join("\n", @{ $spec->{preun} || [] }), qr/^%selinux_relabel_pre -s targeted$/m, + '%preun saves the file contexts before the module leaves the policy'); +my $postun = join("\n", @{ $spec->{postun} || [] }); +like($postun, qr/^%selinux_relabel_post -s targeted$/m, + '%postun relabels the files the removed module had labelled'); +like($postun, qr/\[ \$1 -eq 0 \]/, + '... on an erase only, so an upgrade keeps the labels'); + my $posttrans = join("\n", @{ $spec->{posttrans} || [] }); like($posttrans, qr/^%selinux_relabel_post -s targeted$/m, '%posttrans relabels the files whose context changed'); like($posttrans, qr{\brestorecon -R /install\b}, '... and relabels /install'); -foreach my $section (qw(pre post postun posttrans)) { +foreach my $section (qw(pre preun post postun posttrans)) { unlike(join("\n", @{ $spec->{$section} || [] }), qr/\bsetenforce\b|\/etc\/selinux\/config/, "%$section does not change the SELinux mode"); } From 7f5cf08ad86e9a48deee9c3f9ef77ed6934872fb Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:33:44 -0300 Subject: [PATCH 25/91] fix(xcat-core): the erase of xCAT-selinux leaves three files unlabeled_t %postun removed the module and relabelled nothing, so the two entrypoint types left the policy while three files still carried them. The files became unlabeled_t, and /install kept public_content_t, which the stock policy does not define for it. %preun now saves the file contexts, because %pre does not run on an erase, and %postun relabels after the module is removed, on an erase only. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xCAT-selinux.spec | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/xCAT-selinux/xCAT-selinux.spec b/xCAT-selinux/xCAT-selinux.spec index cd224a90aa..9751811c2d 100644 --- a/xCAT-selinux/xCAT-selinux.spec +++ b/xCAT-selinux/xCAT-selinux.spec @@ -49,8 +49,16 @@ install -m 0644 xcat.pp.bz2 $RPM_BUILD_ROOT%{_datadir}/selinux/packages/targeted %post %selinux_modules_install -s targeted %{_datadir}/selinux/packages/targeted/xcat.pp.bz2 +%preun +# %pre does not run on an erase, and %postun needs the snapshot to find the +# files whose context the removed module defined. +%selinux_relabel_pre -s targeted + %postun %selinux_modules_uninstall -s targeted xcat +if [ $1 -eq 0 ]; then +%selinux_relabel_post -s targeted +fi %posttrans %selinux_relabel_post -s targeted From 2f5a4dbd3af0277814064181d007e8829a1eb598 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:48:54 -0300 Subject: [PATCH 26/91] test(xcat-core): capture the empty candidate list of mysqlsetup mysqlsetup -i reports comment the bind-address line failed: cannot read : No such file or directory on every MySQL cluster, with no file named. Measured on xcat185-mn-tmp-84 through SN_setup_case, which then stops: the Kea configuration and the service node install never happen. @BIND_FILES is assigned by a top-level statement that sits below the main flow's exit, so the statement never runs and the list is empty at run time. $BIND_FILES[-1] is then undef. Each case in the test localizes the list, so none of them read the value the script itself holds. The test now asserts the list of the loaded script. 2 of its 15 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/mysqlsetup_bind_address_label.t | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/xCAT-test/unit/mysqlsetup_bind_address_label.t b/xCAT-test/unit/mysqlsetup_bind_address_label.t index 562f4e1eab..dab748e531 100644 --- a/xCAT-test/unit/mysqlsetup_bind_address_label.t +++ b/xCAT-test/unit/mysqlsetup_bind_address_label.t @@ -29,6 +29,18 @@ my ($help, $load_error); die("Unable to load mysqlsetup: $load_error") unless ref($load_error) eq 'MysqlSetupTestExit' && $load_error->{status} == 0; +# THE SECOND DEFECT. The candidate list was a top-level statement below the +# main flow's exit, so it never ran and the list was empty at run time: every +# call reported "cannot read : No such file or directory". Each case below +# localizes the list, so only this check sees the loaded script's own value. +{ + no warnings 'once'; + ok(scalar(@main::BIND_FILES) > 0, 'the loaded script has candidate files'); + is_deeply([ @main::BIND_FILES ], + [ '/etc/mysql/mariadb.conf.d/50-server.cnf', '/etc/mysql/my.cnf', '/etc/my.cnf' ], + '... the three the POD names, in order'); +} + my $CONF = <<'CONF'; [mysqld] datadir=/var/lib/mysql From c18e41528023fc63ec685d41ad1cb593eb237b75 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:49:02 -0300 Subject: [PATCH 27/91] fix(xcat-core): mysqlsetup cannot find a configuration file to rewrite The candidate list of comment_bind_address was assigned by a top-level statement below the main flow's exit, so the statement never ran. The list was empty, the fallback index read undef, and mysqlsetup -i failed with "cannot read : No such file or directory" on every MySQL cluster. The service node install stops there. A BEGIN block now fills the list at compile time. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-client/bin/mysqlsetup | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/xCAT-client/bin/mysqlsetup b/xCAT-client/bin/mysqlsetup index 2bb15dcd65..0091ced6b3 100755 --- a/xCAT-client/bin/mysqlsetup +++ b/xCAT-client/bin/mysqlsetup @@ -791,11 +791,17 @@ sub fixinstalldir # The candidate configuration files, in the order mysqlsetup reads them. On # Ubuntu 16.04 the bind-address line is in mariadb.conf.d/50-server.cnf, and on # SLE15 it is in /etc/my.cnf. The last one is the fallback. -our @BIND_FILES = ( - "/etc/mysql/mariadb.conf.d/50-server.cnf", - "/etc/mysql/my.cnf", - "/etc/my.cnf", -); +# BEGIN, because the main flow exits above this line: a plain assignment here +# never runs, and the list is empty when comment_bind_address reads it. +our @BIND_FILES; + +BEGIN { + @BIND_FILES = ( + "/etc/mysql/mariadb.conf.d/50-server.cnf", + "/etc/mysql/my.cnf", + "/etc/my.cnf", + ); +} sub comment_bind_address { From 52605e39591cfb8a037cc90940f05382fa657e18 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:27:38 -0300 Subject: [PATCH 28/91] test(xcat-core): capture the missing image-build domain The image build creates an operating system tree, so it writes and relabels files of every type the packages own. xcat_t holds that authority today, and the same domain listens on the xcatd port. xcat_selinux_package.t now asserts a second domain for the build: the xcat_image_t declaration, its permissive line, the entrypoint, the transition from xcat_t with the three inherited process permissions, the role statements for system_r and unconfined_r, and the file contexts of the two genimage programs. One check holds the security property of the split: only xcat_image_t may manage or relabel every file type, and the daemon domain gets no filesystem-wide grant. 9 of the 74 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index dfbd6b86bd..8077b17cad 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -4,6 +4,7 @@ use warnings; use FindBin; use File::Slurper qw(read_lines); +use List::Util (); use Test::More; # The spec files and the file context list are the artifacts: rpmbuild and @@ -236,6 +237,40 @@ foreach my $domain (qw(user_t staff_t sysadm_t guest_t xguest_t)) { unlike($te, qr/\b\Q$domain\E\b/, "$domain gets no rule in xcat.te"); } +######################################## +# +# The image-build domain +# + +like($te, qr/^type xcat_image_t;$/m, 'xcat.te declares a domain for the image build'); +like($te, qr/^permissive xcat_image_t;$/m, '... which is permissive too'); +like($te, qr/^application_domain\(xcat_image_t, xcat_image_exec_t\)$/m, + 'genimage is the entrypoint of that domain'); +like($te, qr/^domtrans_pattern\(xcat_t, xcat_image_exec_t, xcat_image_t\)$/m, + 'xcatd running genimage enters it'); +like($te, qr/^allow xcat_t xcat_image_t:process \{[^}]*\bnoatsecure\b/m, + '... and hands the child the three inherited process permissions'); + +# The transition from a system service computes system_u:system_r:xcat_image_t. +# application_domain does not authorize a role, and without the statement the +# context is invalid: EACCES, reported as SELINUX_ERR and not as an AVC. +like($te, qr/^role system_r types xcat_image_t;$/m, 'system_r is authorized for xcat_image_t'); +like($te, qr/^\s*role unconfined_r types xcat_image_t;$/m, + '... and so is unconfined_r, for an administrator who runs genimage'); + +is_deeply([ grep { fc_type($_) eq 'xcat_image_exec_t' } sort keys %fc ], + [ '/opt/xcat/bin/genimage', '/opt/xcat/share/xcat/netboot/[^/]+/genimage' ], + 'the two genimage programs carry the entrypoint, and nothing else does'); + +# THE SECURITY PROPERTY OF THE SPLIT. The image build writes and relabels files +# of every type, because it creates an operating system tree. The daemon that +# listens on the network must not hold that authority. +my @wide = $te =~ /^allow (\w+) file_type:\w+ \w+;$/mg; +is_deeply([ sort(List::Util::uniq(@wide)) ], [ 'xcat_image_t' ], + 'only the image domain may manage and relabel every file type'); +unlike($te, qr/^files_(manage|relabel)_all_files\(xcat_t\)$/m, + 'the daemon domain gets no filesystem-wide grant by interface either'); + # A management node or a service node with the targeted policy installs the module. foreach my $pkg (qw(xCAT-server xCATsn)) { my @lines = lines_of("$root/$pkg/$pkg.spec"); From 078f607448821050f11a33732503cff3c65a6a98 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:28:20 -0300 Subject: [PATCH 29/91] feat(xcat-core): build the image in a domain of its own The policy granted xcat_t everything the image build needs, so the domain that listens on the xcatd port could also write and relabel a file of any type. The rules were one per target type, 558 of them from the measured denials, and 85 per cent of those repeated one of 58 permission patterns. xcat.te now carries two domains. xcat_image_t is entered through /opt/xcat/bin/genimage and the per-OS genimage program, from xcat_t and from the administrator, and it holds the filesystem-wide manage and relabel grants: the build creates an operating system tree, and the kernel cannot tell a path inside that tree from the same type on the management node. xcat_t keeps the daemon surface -- its sockets and ports, /install, /tftpboot, /etc, the credentials, the service class for the units it restarts -- and no grant over the file_type attribute. The rules are Reference Policy interface calls where one exists: domain_read_all_domains_state replaces 93 of them, dev_getattr_all_chr_files 31, files_read_etc_files, auth_read_shadow, seutil_read_config, logging_send_syslog_msg, fs_mount_all_fs and corecmd_exec_bin the rest. The module is 203 statements where the generated set was 806 rules. packimage and liteimg are symlinks to xcatclientnnr, so their work runs in the xcatd plugin and the tree authority stays in xcat_t with them. It can move to xcat_image_t when the plugin execs a helper instead. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 6 + xCAT-selinux/xcat.te | 356 +++++++++++++++++++++++++- xCAT-test/unit/xcat_selinux_package.t | 3 +- 3 files changed, 355 insertions(+), 10 deletions(-) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 6466a70e29..26ed9b766a 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -4,6 +4,12 @@ /opt/xcat/bin/xcatclient -- gen_context(system_u:object_r:xcat_client_exec_t,s0) /opt/xcat/bin/xcatclientnnr -- gen_context(system_u:object_r:xcat_client_exec_t,s0) +# The entrypoints of the image build. The wrapper and the per-OS program are +# both real files; packimage and liteimg are symlinks to xcatclientnnr, so the +# work they ask for runs in xcat_t. +/opt/xcat/bin/genimage -- gen_context(system_u:object_r:xcat_image_exec_t,s0) +/opt/xcat/share/xcat/netboot/[^/]+/genimage -- gen_context(system_u:object_r:xcat_image_exec_t,s0) + /install(/.*)? gen_context(system_u:object_r:public_content_t,s0) # A rootimg keeps the labels of its own OS, so restorecon must not change them. diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 184522d08e..048dade3c2 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -1,14 +1,22 @@ -policy_module(xcat, 1.1.0) +policy_module(xcat, 1.2.0) gen_require(` type httpd_t, httpd_sys_script_t, tftpdir_t, ntop_port_t; type rsync_t, shadow_t; type useradd_t, groupadd_t, public_content_t; + type named_zone_t, named_unit_file_t, systemd_unit_file_t; + type auditd_etc_t, selinux_config_t, ldconfig_cache_t, setfiles_t, tmp_t; + type device_t; + attribute file_type; + type admin_home_t, cert_t, krb5_keytab_t, var_run_t; + class service { start status stop reload enable disable }; + class system { reload status start stop }; + class dbus { send_msg }; ') ######################################## # -# The xCAT domain +# The xCAT domains # # xcatd and the client commands share one domain. Each command sends its @@ -21,13 +29,29 @@ init_daemon_domain(xcat_t, xcatd_exec_t) type xcat_client_exec_t; application_domain(xcat_t, xcat_client_exec_t) -# The CI collects the accesses xcat_t needs while the host stays enforcing. -# A later release removes this line and the domain becomes enforcing. -permissive xcat_t; +# genimage builds a whole operating system in a directory, so it creates and +# relabels files of every type. It runs in its own domain to keep that out of +# the daemon that also listens on the network. +type xcat_image_t; +type xcat_image_exec_t; +application_domain(xcat_image_t, xcat_image_exec_t) +domtrans_pattern(xcat_t, xcat_image_exec_t, xcat_image_t) +# domtrans_pattern does not carry these three, and a parent that execs into +# another domain needs them: the child inherits the signal mask, the rlimits +# and the AT_SECURE flag of the exec. +allow xcat_t xcat_image_t:process { noatsecure rlimitinh siginh }; -# xcatd and xcatclient are Perl scripts. The kernel enters the domain on the -# script, so the domain runs the interpreter of the shebang line itself. -corecmd_exec_bin(xcat_t) +# xcatd runs genimage, so the transition computes system_u:system_r:xcat_image_t. +# application_domain does not authorize a role for the type, and without this +# the context is invalid: the kernel refuses the exec with EACCES and reports +# SELINUX_ERR, not AVC. init_daemon_domain does this through the daemon +# attribute, which is why xcat_t needs no such line. +role system_r types xcat_image_t; + +# The CI collects the accesses each domain needs while the host stays +# enforcing. A later release removes these two lines. +permissive xcat_t; +permissive xcat_image_t; optional_policy(` gen_require(` @@ -35,18 +59,332 @@ optional_policy(` role unconfined_r; ') - # The transition computes unconfined_u:unconfined_r:xcat_t. The role must + # The transition computes unconfined_u:unconfined_r:. The role must # hold the type, or the context is invalid and the kernel refuses the exec # with EACCES. Permissive does not cover it: an invalid context is not a # permission check, and the record is SELINUX_ERR, not AVC. role unconfined_r types xcat_t; + role unconfined_r types xcat_image_t; # Targeted policy gives root unconfined_t, which is where the administrator # and the CI run the commands. A confined user domain gets no transition: it # would leave its own confinement for a permissive domain. domtrans_pattern(unconfined_t, xcat_client_exec_t, xcat_t) + domtrans_pattern(unconfined_t, xcat_image_exec_t, xcat_image_t) ') +######################################## +# +# xcat_t, the daemon and the commands +# + +allow xcat_t self:capability { audit_control audit_write chown dac_override + dac_read_search fowner fsetid mknod net_admin net_bind_service setfcap + setgid setuid sys_admin sys_chroot sys_ptrace sys_resource sys_time }; +allow xcat_t self:process { setcap setfscreate setpgid setrlimit setsched signal_perms }; +allow xcat_t self:fifo_file rw_fifo_file_perms; +allow xcat_t self:tcp_socket { create_stream_socket_perms accept listen }; +allow xcat_t self:udp_socket create_socket_perms; +allow xcat_t self:unix_stream_socket { create_stream_socket_perms connectto }; +allow xcat_t self:unix_dgram_socket create_socket_perms; +allow xcat_t self:netlink_route_socket { create_netlink_socket_perms nlmsg_read nlmsg_write }; +allow xcat_t self:netlink_audit_socket { create_netlink_socket_perms nlmsg_read nlmsg_write nlmsg_relay }; +allow xcat_t self:alg_socket create_socket_perms; + +# xcatd and xcatclient are Perl scripts, and both run ordinary commands: ip, +# systemctl, hostname, mount, rsync, named, rpm. +corecmd_exec_bin(xcat_t) +corecmd_exec_shell(xcat_t) +corecmd_exec_all_executables(xcat_t) + +# ps and pidof read /proc of the services xCAT manages. +domain_read_all_domains_state(xcat_t) +init_read_state(xcat_t) +init_stream_connect(xcat_t) +init_telinit(xcat_t) +kernel_read_system_state(xcat_t) +kernel_read_network_state(xcat_t) + +dev_getattr_all_chr_files(xcat_t) +dev_read_sysfs(xcat_t) +dev_read_urand(xcat_t) +term_use_all_ttys(xcat_t) +term_use_generic_ptys(xcat_t) +userdom_use_user_terminals(xcat_t) + +# makehosts, makedns and makedhcp write the configuration of the services they +# drive, and packimage reads the whole image tree it packs. +files_read_etc_files(xcat_t) +files_manage_etc_files(xcat_t) +files_manage_generic_tmp_files(xcat_t) +files_manage_generic_tmp_dirs(xcat_t) +files_manage_generic_locks(xcat_t) +# The postscript and prescript plugins write a script under /tmp and run it. +can_exec(xcat_t, tmp_t) +files_read_all_files(xcat_t) +files_list_all(xcat_t) +files_getattr_all_dirs(xcat_t) +sysnet_read_config(xcat_t) +sysnet_manage_config(xcat_t) +miscfiles_read_localization(xcat_t) +logging_send_syslog_msg(xcat_t) +logging_read_syslog_config(xcat_t) +seutil_read_config(xcat_t) +seutil_read_file_contexts(xcat_t) + +# xdcp and "updatenode -F" copy /etc/shadow to the nodes. +auth_read_shadow(xcat_t) + +# Both domains resolve users and groups through nsswitch, which reaches +# systemd-userdbd over its runtime socket. +auth_use_nsswitch(xcat_t) +auth_use_nsswitch(xcat_image_t) + +# ps in a user namespace needs the namespaced capability as well. +allow xcat_t self:cap_userns sys_ptrace; +allow xcat_image_t self:cap_userns sys_ptrace; + +# nodeset and copycds write the rpm database of the image they prepare. +optional_policy(` + rpm_manage_db(xcat_t) + rpm_manage_db(xcat_image_t) + rpm_manage_cache(xcat_t) +') + +# xcatd rotates and stamps its own log directory. +logging_manage_generic_logs(xcat_t) +# logging_manage_generic_logs does not carry setattr on the directory itself. +allow xcat_t var_log_t:dir setattr; + +# goconserver and the other services xCAT starts itself run unconfined, and +# xcatd talks to them over their sockets. +optional_policy(` + unconfined_server_stream_connectto(xcat_t) +') + +# copycds loop-mounts the install DVD: the mount itself, the loop control +# device and the block device the loop driver then presents. +dev_rw_loop_control(xcat_t) +storage_raw_rw_fixed_disk(xcat_t) +fs_getattr_all_fs(xcat_t) +fs_mount_all_fs(xcat_t) +fs_unmount_all_fs(xcat_t) +files_mounton_all_mountpoints(xcat_t) + +# xcatd listens on site.xcatdport and reaches the services it configures. +corenet_tcp_bind_generic_node(xcat_t) +corenet_tcp_bind_ntop_port(xcat_t) +corenet_tcp_connect_ntop_port(xcat_t) +corenet_tcp_bind_generic_port(xcat_t) +corenet_tcp_connect_all_unreserved_ports(xcat_t) +corenet_tcp_connect_all_ports(xcat_t) +corenet_udp_bind_all_ports(xcat_t) +corenet_udp_bind_generic_node(xcat_t) + +# /install and /tftpboot are the trees xCAT owns. +manage_dirs_pattern(xcat_t, public_content_t, public_content_t) +manage_files_pattern(xcat_t, public_content_t, public_content_t) +manage_lnk_files_pattern(xcat_t, public_content_t, public_content_t) +can_exec(xcat_t, public_content_t) +# packimage runs cpio over the image tree, which creates the device nodes the +# image holds. packimage is a symlink to xcatclientnnr, so the work runs here +# and not in xcat_image_t. +manage_chr_files_pattern(xcat_t, public_content_t, public_content_t) +manage_blk_files_pattern(xcat_t, public_content_t, public_content_t) +manage_sock_files_pattern(xcat_t, public_content_t, public_content_t) +manage_fifo_files_pattern(xcat_t, public_content_t, public_content_t) +allow xcat_t public_content_t:chr_file create; +allow xcat_t public_content_t:blk_file create; +allow xcat_t self:capability mknod; + +# packimage and liteimg are symlinks to xcatclientnnr, so the xcatd plugin +# does their work in this domain: it writes and relabels the image tree, whose +# files keep the labels of the node operating system. The authority can only +# move to xcat_image_t when the plugin execs a helper instead. +files_manage_non_security_files(xcat_t) +files_manage_non_security_dirs(xcat_t) +files_relabel_non_security_files(xcat_t) + +# mount writes its own state, and the clients read the enforcing mode. +files_manage_mounttab(xcat_t) +optional_policy(` + mount_manage_pid_files(xcat_t) +') +selinux_get_enforce_mode(xcat_t) +storage_getattr_removable_dev(xcat_t) +manage_dirs_pattern(xcat_t, tftpdir_t, tftpdir_t) +manage_files_pattern(xcat_t, tftpdir_t, tftpdir_t) +manage_lnk_files_pattern(xcat_t, tftpdir_t, tftpdir_t) + +# makedns writes the zones and restarts named. There is no stock interface for +# the service class of a named unit, so the two rules are explicit. +manage_dirs_pattern(xcat_t, named_zone_t, named_zone_t) +manage_files_pattern(xcat_t, named_zone_t, named_zone_t) +# systemctl daemon-reload and systemctl stop act on the init domain itself, +# and no stock interface grants the system class. +allow xcat_t init_t:system { reload status start stop }; + +# setupntp sets the hardware clock and drives chronyd. +dev_rw_realtime_clock(xcat_t) +optional_policy(` + systemd_dbus_chat_timedated(xcat_t) +') +optional_policy(` + chronyd_manage_pid_files(xcat_t) + chronyd_manage_pid(xcat_t) + chronyd_systemctl(xcat_t) + chronyd_domtrans(xcat_t) + # setupntp execs chronyd, and the exec hands the child these three. + gen_require(` type chronyd_t; ') + allow xcat_t chronyd_t:process { noatsecure rlimitinh siginh }; +') + +allow xcat_t named_unit_file_t:service { start status stop reload enable disable }; +# makedhcp enables the kea units, so the set includes enable and disable. No +# denial was recorded for either: the audit window was empty while makedhcp +# still reported "Failed to enable kea-dhcp-ddns". +allow xcat_t systemd_unit_file_t:service { start status stop reload enable disable }; + +# xcatd keeps its credentials under /etc/xcat and its socket under /run/xcat. +manage_dirs_pattern(xcat_t, cert_t, cert_t) +manage_files_pattern(xcat_t, cert_t, cert_t) +manage_dirs_pattern(xcat_t, krb5_keytab_t, krb5_keytab_t) +manage_files_pattern(xcat_t, krb5_keytab_t, krb5_keytab_t) +manage_dirs_pattern(xcat_t, var_run_t, var_run_t) +manage_files_pattern(xcat_t, var_run_t, var_run_t) +manage_sock_files_pattern(xcat_t, var_run_t, var_run_t) + +# the administrator's own files: xdsh reads /root/.ssh, and the clients write +# their reports under /root. +userdom_read_admin_home_files(xcat_t) +manage_files_pattern(xcat_t, admin_home_t, admin_home_t) +manage_dirs_pattern(xcat_t, admin_home_t, admin_home_t) + +######################################## +# +# xcat_image_t, the image build +# + +allow xcat_image_t self:capability { audit_write chown dac_override + dac_read_search fowner fsetid mknod net_admin setfcap setgid setuid + sys_admin sys_chroot sys_resource sys_ptrace }; +allow xcat_image_t self:process { setcap setfscreate setpgid setrlimit setsched signal_perms }; +allow xcat_image_t self:fifo_file rw_fifo_file_perms; +allow xcat_image_t self:tcp_socket { create_stream_socket_perms accept listen }; +allow xcat_image_t self:udp_socket create_socket_perms; +allow xcat_image_t self:unix_stream_socket { create_stream_socket_perms connectto }; +allow xcat_image_t self:unix_dgram_socket create_socket_perms; +allow xcat_image_t self:netlink_route_socket { create_netlink_socket_perms nlmsg_read nlmsg_write }; +allow xcat_image_t self:netlink_audit_socket { create_netlink_socket_perms nlmsg_read nlmsg_write nlmsg_relay }; +allow xcat_image_t self:alg_socket { create_socket_perms accept }; + +# It installs packages into a directory tree, so it creates every type that +# tree holds and relabels what the package manager puts there. +files_manage_non_security_files(xcat_image_t) +files_manage_non_security_dirs(xcat_image_t) +files_relabel_non_security_files(xcat_image_t) +corecmd_manage_all_executables(xcat_image_t) +corecmd_relabel_all_executables(xcat_image_t) +auth_manage_shadow(xcat_image_t) +auth_relabel_shadow(xcat_image_t) +seutil_manage_file_contexts(xcat_image_t) +seutil_domtrans_setfiles(xcat_image_t) + +# dnf in the chroot, and the rpm scriptlets it runs. +corecmd_exec_bin(xcat_image_t) +corecmd_exec_shell(xcat_image_t) +corecmd_exec_all_executables(xcat_image_t) +can_exec(xcat_image_t, public_content_t) +# dnf and cpio create the device nodes of the image under /install. +manage_chr_files_pattern(xcat_image_t, public_content_t, public_content_t) +manage_blk_files_pattern(xcat_image_t, public_content_t, public_content_t) +manage_sock_files_pattern(xcat_image_t, public_content_t, public_content_t) +manage_fifo_files_pattern(xcat_image_t, public_content_t, public_content_t) +allow xcat_image_t public_content_t:chr_file create; +allow xcat_image_t public_content_t:blk_file create; +files_manage_mounttab(xcat_image_t) +# ldd, ldconfig, dracut-install and modprobe inside the image. +libs_exec_ld_so(xcat_image_t) +files_read_kernel_modules(xcat_image_t) +files_map_kernel_modules(xcat_image_t) +files_map_etc_files(xcat_image_t) +# cpio walks the device nodes of the image, and mknod creates them. +storage_getattr_fixed_disk_dev(xcat_image_t) +storage_getattr_removable_dev(xcat_image_t) +dev_create_generic_chr_files(xcat_image_t) +manage_chr_files_pattern(xcat_image_t, tmp_t, tmp_t) +fs_getattr_nsfs_files(xcat_image_t) +# dnf installs packages that own files of every type, including the security +# types, and it relabels what it writes. The grant is per class over the +# file_type attribute rather than a list: the measured tail named +# selinux_config_t, auditd_etc_t, auditd_log_t, krb5_keytab_t, +# semanage_store_t and default_context_t, and the next image adds more. +# +# This is the authority that keeps the image build out of xcat_t. Here it +# reaches the tree the build creates; in the daemon it would reach the real +# /etc/selinux, the audit configuration and the keytabs of the management node. +# Manage as well as relabel: the build creates the tree, so it writes files of +# every type the packages own. The kernel cannot tell a path inside the image +# from the same type on the management node, so this authority is filesystem +# wide and that is the reason it lives in a domain of its own, entered only +# through genimage. REVIEW THIS GRANT FIRST. +allow xcat_image_t file_type:dir manage_dir_perms; +allow xcat_image_t file_type:file manage_file_perms; +allow xcat_image_t file_type:lnk_file manage_lnk_file_perms; +allow xcat_image_t file_type:dir relabel_dir_perms; +allow xcat_image_t file_type:file relabel_file_perms; +allow xcat_image_t file_type:lnk_file relabel_lnk_file_perms; +allow xcat_image_t file_type:file map; +allow xcat_image_t device_t:chr_file setattr; +allow xcat_image_t self:capability audit_control; +allow xcat_image_t self:netlink_audit_socket nlmsg_readpriv; +allow xcat_image_t ldconfig_cache_t:file map; +# restorecon runs in setfiles_t, and the exec hands it these three. +allow xcat_image_t setfiles_t:process { noatsecure rlimitinh siginh }; +optional_policy(` + mount_manage_pid_files(xcat_image_t) +') +selinux_get_enforce_mode(xcat_image_t) +optional_policy(` + rpm_manage_cache(xcat_image_t) +') + +# It mounts /proc and /sys inside the chroot and unmounts them afterwards. +fs_getattr_all_fs(xcat_image_t) +fs_mount_all_fs(xcat_image_t) +fs_unmount_all_fs(xcat_image_t) +files_mounton_all_mountpoints(xcat_image_t) + +domain_read_all_domains_state(xcat_image_t) +init_read_state(xcat_image_t) +kernel_read_system_state(xcat_image_t) +kernel_read_network_state(xcat_image_t) +dev_getattr_all_chr_files(xcat_image_t) +dev_read_sysfs(xcat_image_t) +dev_read_urand(xcat_image_t) +term_use_all_ttys(xcat_image_t) +term_use_generic_ptys(xcat_image_t) +userdom_use_user_terminals(xcat_image_t) +files_read_etc_files(xcat_image_t) +files_manage_etc_files(xcat_image_t) +files_manage_generic_tmp_files(xcat_image_t) +files_manage_generic_tmp_dirs(xcat_image_t) +sysnet_read_config(xcat_image_t) +miscfiles_read_localization(xcat_image_t) +logging_send_syslog_msg(xcat_image_t) +seutil_read_config(xcat_image_t) +seutil_read_file_contexts(xcat_image_t) + +# It downloads the packages it installs. +corenet_tcp_connect_all_ports(xcat_image_t) +corenet_tcp_bind_generic_node(xcat_image_t) + +# It reports progress back to xcatd. +allow xcat_image_t xcat_t:unix_stream_socket connectto; +allow xcat_image_t xcat_t:fd use; +allow xcat_image_t xcat_t:fifo_file rw_fifo_file_perms; +allow xcat_image_t xcat_t:process sigchld; + ######################################## # # Access for the services that read the xCAT trees diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 8077b17cad..dc10293ef8 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -207,7 +207,8 @@ is_deeply([ grep { /^kernel_t / } @rules ], [], like($te, qr/^type xcat_t;$/m, 'xcat.te declares one domain for xcatd and the clients'); like($te, qr/^permissive xcat_t;$/m, '... which is permissive while the CI collects the accesses it needs'); -unlike($te, qr/^permissive (?!xcat_t\b)/m, '... and no other domain is made permissive'); +is_deeply([ sort($te =~ /^permissive (\w+);$/mg) ], [ 'xcat_image_t', 'xcat_t' ], + '... and the two xCAT domains are the only permissive ones'); like($te, qr/^init_daemon_domain\(xcat_t, xcatd_exec_t\)$/m, 'systemd starts xcatd in xcat_t'); From ca04e2c8ae3aef6f763920f67b53a997e0f61e7c Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:16:26 -0300 Subject: [PATCH 30/91] fix(xcat-core): the image build cannot open the fifo dnf writes its progress to The last two enforced denials of the enforcing run were xcat_image_t tmp_t:fifo_file create. Neither provisioning case failed on them, because dnf falls back to its plain output, but the grant belongs with the rest of the /tmp set of that domain. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 048dade3c2..4193c2e234 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -313,6 +313,8 @@ storage_getattr_fixed_disk_dev(xcat_image_t) storage_getattr_removable_dev(xcat_image_t) dev_create_generic_chr_files(xcat_image_t) manage_chr_files_pattern(xcat_image_t, tmp_t, tmp_t) +# dnf opens a fifo under /tmp for its progress output. +manage_fifo_files_pattern(xcat_image_t, tmp_t, tmp_t) fs_getattr_nsfs_files(xcat_image_t) # dnf installs packages that own files of every type, including the security # types, and it relabels what it writes. The grant is per class over the @@ -335,6 +337,10 @@ allow xcat_image_t file_type:dir relabel_dir_perms; allow xcat_image_t file_type:file relabel_file_perms; allow xcat_image_t file_type:lnk_file relabel_lnk_file_perms; allow xcat_image_t file_type:file map; +# The image holds its own /dev. device_t is a device type, not a member of the +# file_type attribute, so the grant above does not reach it. +manage_chr_files_pattern(xcat_image_t, device_t, device_t) +manage_blk_files_pattern(xcat_image_t, device_t, device_t) allow xcat_image_t device_t:chr_file setattr; allow xcat_image_t self:capability audit_control; allow xcat_image_t self:netlink_audit_socket nlmsg_readpriv; From 6eb1d713176470ee50da984382deeff63e9119ca Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:37:57 -0300 Subject: [PATCH 31/91] feat(xcat-core): keep the TFTP server out of the xCAT domain AAsn.pm starts /usr/sbin/in.tftpd with system() and no systemd unit, so the daemon inherited xcat_t: a persistent listener on UDP 69, reachable from every node of the provisioning network, held the authority of the domain that also writes the image tree and reaches the database. xcat.te now transitions from xcat_t to the stock tftpd_t on tftpd_exec_t. tftp.if carries no tftp_domtrans, so the pattern and the three inherited process permissions are written out. Measured on xcat163-mn-tmp-286 with both xCAT domains enforcing and dontaudit disabled: in.tftpd runs as system_u:system_r:tftpd_t:s0 and still owns port 69, a TFTP fetch of /tftpboot/xcat/xnba.kpxe returns the file, and both flat provisioning cases pass -- diskless 1177 s, which netboots the compute node over that server, and diskful 654 s. Zero denials in xcat_t, xcat_image_t and tftpd_t. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 4193c2e234..235738f79f 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -53,6 +53,18 @@ role system_r types xcat_image_t; permissive xcat_t; permissive xcat_image_t; +# xCAT starts in.tftpd itself, with no systemd unit, so without this the daemon +# inherits xcat_t and serves UDP 69 with this domain's authority. tftp.if ships +# no tftp_domtrans, so the transition is written here. +optional_policy(` + gen_require(` + type tftpd_t, tftpd_exec_t; + ') + + domtrans_pattern(xcat_t, tftpd_exec_t, tftpd_t) + allow xcat_t tftpd_t:process { noatsecure rlimitinh siginh }; +') + optional_policy(` gen_require(` type unconfined_t; From e2bae62e61f584b39b5a861132f1002a427787d1 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:06:01 -0300 Subject: [PATCH 32/91] test(xcat-core): capture the probe directory no package owns /opt/xcat/probe/subcmds/bin is created by the %post of xCAT-probe, so no package owns it. A directory a scriptlet creates takes the context of its parent, usr_t, and not the bin_t that the policy gives /opt/.*/bin, and nothing relabels it afterwards. Measured on xcat163-mn-tmp-286: restorecon -n -v -R /opt/xcat Would relabel /opt/xcat/probe/subcmds/bin from unconfined_u:object_r:usr_t:s0 to unconfined_u:object_r:bin_t:s0 It is the only path under /opt/xcat whose label does not match the policy. The directory is in use: xcatprobe:263 drops a switchprobe symlink in it, and xCAT-probe/debian/dirs already packages it on Debian. xcat_probe_package_payload.t asserts that %install creates it, that %post does not, and that the Debian package keeps it. 2 of its 4 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_probe_package_payload.t | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/xCAT-test/unit/xcat_probe_package_payload.t b/xCAT-test/unit/xcat_probe_package_payload.t index bac1f371bd..3483e3c2e5 100644 --- a/xCAT-test/unit/xcat_probe_package_payload.t +++ b/xCAT-test/unit/xcat_probe_package_payload.t @@ -11,4 +11,19 @@ my ($probe) = $control =~ /^Package: xcat-probe\n(.*?)(?:\n\n|\z)/ms; like($probe // '', qr/^Depends:.*\biproute2\s*\|\s*net-tools\b/m, 'Debian probe keeps the socket-tool alternatives'); +# The rpm created subcmds/bin in %post, so the directory belonged to no package +# and took the context of its parent, usr_t, instead of the bin_t the policy +# gives /opt/.*/bin. Nothing relabels it afterwards, and xcatprobe drops a +# switchprobe symlink in it at run time. The Debian package already owns the +# directory through debian/dirs. +my $spec = slurp_repo_file('xCAT-probe/xCAT-probe.spec'); +my ($install) = $spec =~ /^%install\n(.*?)^%\w+/ms; +like($install // '', qr{^mkdir -p \$RPM_BUILD_ROOT/%\{prefix\}/probe/subcmds/bin\b}m, + '%install creates subcmds/bin, so rpm owns it and labels it from the policy'); +my ($post) = $spec =~ /^%post\n(.*?)(?:^%\w+|\z)/ms; +unlike($post // '', qr{mkdir -p .*probe/subcmds/bin}, + '... and %post no longer creates it behind rpm'); +my $dirs = slurp_repo_file('xCAT-probe/debian/dirs'); +like($dirs, qr{^opt/xcat/probe/subcmds/bin$}m, 'the Debian package still owns it too'); + done_testing(); From db07a23349e1cc7d7d04df96fc50ac3aec2eb4f9 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:06:01 -0300 Subject: [PATCH 33/91] fix(xcat-core): rpm does not own the probe subcmds/bin directory The %post of xCAT-probe created /opt/xcat/probe/subcmds/bin, so the directory belonged to no package and carried usr_t from its parent rather than the bin_t the policy gives /opt/.*/bin. It was the only path under /opt/xcat that restorecon reported as pending, on every management node. %install now creates the directory, so rpm owns it and labels it from the policy at install, as the Debian package already does through debian/dirs. The %post keeps removing the obsolete switchprobe file it finds there. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-probe/xCAT-probe.spec | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/xCAT-probe/xCAT-probe.spec b/xCAT-probe/xCAT-probe.spec index 53bbb589cd..6466e94585 100644 --- a/xCAT-probe/xCAT-probe.spec +++ b/xCAT-probe/xCAT-probe.spec @@ -52,6 +52,10 @@ rm -rf $RPM_BUILD_ROOT mkdir -p $RPM_BUILD_ROOT/%{prefix}/bin mkdir -p $RPM_BUILD_ROOT/%{prefix}/probe/ +# xcatprobe drops a switchprobe symlink in here at run time. rpm must own the +# directory, or it takes the context of its parent instead of the one the +# policy gives /opt/.*/bin, and nothing relabels it afterwards. +mkdir -p $RPM_BUILD_ROOT/%{prefix}/probe/subcmds/bin cp xcatprobe $RPM_BUILD_ROOT/%{prefix}/bin cp -r subcmds $RPM_BUILD_ROOT/%{prefix}/probe/ @@ -77,8 +81,6 @@ rm -rf $RPM_BUILD_ROOT %post if [ -e %{prefix}/probe/subcmds/bin/switchprobe ]; then rm -rf %{prefix}/probe/subcmds/bin/switchprobe -else - mkdir -p %{prefix}/probe/subcmds/bin/ fi %preun From 4b891e59d3b53c5b09422827df092e6b6c8479df Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:15:38 -0300 Subject: [PATCH 34/91] test(xcat-core): capture the drift the policy package does not repair %posttrans relabels /install and nothing else, so a path under /opt/xcat whose label was wrong before an upgrade stays wrong: rpm does not relabel a directory that already exists. Measured on xcat163-mn-tmp-286, where /opt/xcat/probe/subcmds/bin kept usr_t through the upgrade that fixed its packaging, and only took bin_t once rpm created it. xcat_selinux_package.t now asserts that %posttrans relabels /opt/xcat as well. 1 of its 75 checks fails on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index dc10293ef8..766cd9e8e1 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -107,6 +107,11 @@ my $posttrans = join("\n", @{ $spec->{posttrans} || [] }); like($posttrans, qr/^%selinux_relabel_post -s targeted$/m, '%posttrans relabels the files whose context changed'); like($posttrans, qr{\brestorecon -R /install\b}, '... and relabels /install'); +# An upgrade does not relabel a directory that already exists, so a path whose +# label was wrong before the fix stays wrong. /opt/xcat/probe/subcmds/bin was +# that path on every management node. Relabelling the product tree here repairs +# it, and any later drift, without a separate step. +like($posttrans, qr{\brestorecon -R /opt/xcat\b}, '... and the product tree too'); foreach my $section (qw(pre preun post postun posttrans)) { unlike(join("\n", @{ $spec->{$section} || [] }), qr/\bsetenforce\b|\/etc\/selinux\/config/, "%$section does not change the SELinux mode"); From 4e35eebfbdae3ee8a5bb718a5b88e291334f820f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:15:39 -0300 Subject: [PATCH 35/91] fix(xcat-core): the policy package does not repair a stale label %posttrans relabelled /install only. A path under /opt/xcat whose context was wrong before the package arrived kept it, because rpm does not relabel a directory that already exists and nothing else ran restorecon there. %posttrans now relabels /opt/xcat too, so installing or updating the policy brings the product tree to the contexts the module declares. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xCAT-selinux.spec | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xCAT-selinux/xCAT-selinux.spec b/xCAT-selinux/xCAT-selinux.spec index 9751811c2d..9db0e8287b 100644 --- a/xCAT-selinux/xCAT-selinux.spec +++ b/xCAT-selinux/xCAT-selinux.spec @@ -65,3 +65,8 @@ fi if selinuxenabled && [ -d /install ]; then restorecon -R /install || : fi +# An upgrade does not relabel a directory that already exists, so a path whose +# label predates its packaging keeps it. Relabel the product tree as well. +if selinuxenabled && [ -d /opt/xcat ]; then + restorecon -R /opt/xcat || : +fi From dccc5ad2022775e18ad56e14c4e6828ebbebd8d7 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:33:39 -0300 Subject: [PATCH 36/91] fix(xcat-test): the check on the image domain's authority cannot fail The check that holds the whole security property of the split matched `^allow (\w+) file_type:\w+ \w+;$` -- one unbraced permission and nothing else. Every braced rule and every interface call passed it, so a grant of filesystem-wide authority to xcat_t would not have been caught. The pattern now reads both forms, and the named interfaces that grant the same thing are asserted per domain: files_manage_all_files, files_relabel_all_files, auth_manage_shadow, auth_relabel_shadow and seutil_manage_file_contexts belong to xcat_image_t and not to xcat_t. One check records what xcat_t does keep, and why. Verified against the policy: a braced `allow xcat_t file_type:file { write relabelto };` fails 1 check, and `files_relabel_all_files(xcat_t)` fails 2. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 766cd9e8e1..40249befa7 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -271,11 +271,29 @@ is_deeply([ grep { fc_type($_) eq 'xcat_image_exec_t' } sort keys %fc ], # THE SECURITY PROPERTY OF THE SPLIT. The image build writes and relabels files # of every type, because it creates an operating system tree. The daemon that # listens on the network must not hold that authority. -my @wide = $te =~ /^allow (\w+) file_type:\w+ \w+;$/mg; +# The first form of this check matched only `allow X file_type:class perm;` +# with a single unbraced permission, so every braced rule and every interface +# call passed it. It is the whole security property of the split, so it now +# reads both forms and names the interfaces that would grant the same thing. +my @wide = $te =~ /^allow (\w+) file_type:\w+ [{\w]/mg; is_deeply([ sort(List::Util::uniq(@wide)) ], [ 'xcat_image_t' ], - 'only the image domain may manage and relabel every file type'); -unlike($te, qr/^files_(manage|relabel)_all_files\(xcat_t\)$/m, - 'the daemon domain gets no filesystem-wide grant by interface either'); + 'only the image domain may reach every file type directly'); + +# The daemon domain may not relabel a security type, and may not manage one at +# all. Those two are what keeps /etc/selinux, the keytabs and the audit +# configuration of the management node out of reach of the network daemon. +foreach my $iface (qw(files_manage_all_files files_relabel_all_files + auth_manage_shadow auth_relabel_shadow seutil_manage_file_contexts)) { + unlike($te, qr/^\Q$iface\E\(xcat_t\)$/m, "$iface is not given to xcat_t"); + like($te, qr/^\Q$iface\E\(xcat_image_t\)$/m, "... and $iface is the image domain's") + if $te =~ /^\Q$iface\E\(/m; +} + +# What xcat_t does keep, and why, so the next reader does not take the split for +# more than it is: packimage and liteimg are symlinks to xcatclientnnr, so their +# tree work runs in the daemon. +like($te, qr/^files_manage_non_security_files\(xcat_t\)$/m, + 'xcat_t still manages non-security files, for packimage'); # A management node or a service node with the targeted policy installs the module. foreach my $pkg (qw(xCAT-server xCATsn)) { From ef70cc4e790d75180a3d3de1efe39d811f576a33 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:33:40 -0300 Subject: [PATCH 37/91] fix(xcat-core): the setfiles transition costs denials and buys nothing seutil_domtrans_setfiles(xcat_image_t) put restorecon in the stock setfiles_t domain during an image build. That domain is enforcing, and it cannot append to the pipe it inherits from its caller: every enforcing run carried 20 denials in setfiles_t, 13 of them `etc_t:file map`, 4 `xcat_t:fifo_file append` and 3 `public_content_t:chr_file write`. The runs passed, because restorecon only loses its output, and the denials were invisible to a count filtered on the xCAT domains. The transition also removed no authority: xcat_image_t already relabels every type, so the relabel is the same work in a different domain. The line is gone and the comment records why. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index 235738f79f..d83fdc8dc6 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -300,7 +300,10 @@ corecmd_relabel_all_executables(xcat_image_t) auth_manage_shadow(xcat_image_t) auth_relabel_shadow(xcat_image_t) seutil_manage_file_contexts(xcat_image_t) -seutil_domtrans_setfiles(xcat_image_t) +# No transition to setfiles_t. The image domain already relabels every type, so +# the transition removes no authority, and it put restorecon in an enforcing +# stock domain that cannot append to the pipe it inherits: 20 enforced denials +# per run, 4 of them setfiles_t xcat_t:fifo_file append. # dnf in the chroot, and the rpm scriptlets it runs. corecmd_exec_bin(xcat_image_t) From c4934af9265f10d80cb8f4e092b43be01a8a153d Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:35:08 -0300 Subject: [PATCH 38/91] fix(xcat-core): xCAT cannot stop the TFTP server it started setup_tftpd kills a stray in.tftpd before it starts its own (AAsn.pm:1382). With the server now in tftpd_t the signal crossed a domain boundary and was refused: xcat_t tftpd_t:process { signal signull }, found by the enforcing check after the transition landed. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index d83fdc8dc6..c555187053 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -63,6 +63,9 @@ optional_policy(` domtrans_pattern(xcat_t, tftpd_exec_t, tftpd_t) allow xcat_t tftpd_t:process { noatsecure rlimitinh siginh }; + + # setup_tftpd kills a stray server before it starts its own. + allow xcat_t tftpd_t:process { signal signull }; ') optional_policy(` From 2bb5d83d2862ebbdcd857f7f1a9574eab0e2d8ee Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:23:26 -0300 Subject: [PATCH 39/91] test(xcat-core): capture three paths the file contexts get wrong xcat.fc labels /opt/xcat/bin/genimage as the image entrypoint, although the wrapper only writes a request to the socket; in --interactive mode it runs the per-OS program through a shell (xCAT-client/bin/genimage:453), and that exec transitions on its own from either caller domain. A dispatching client therefore held the authority of the image build. It also misses two paths. netboot/fedora12/geninitrd is a real 41 KB program, and the genimage glob never matches a name spelled geninitrd. And /opt/xcat/bin/xcatDBcmds is a third dispatcher, reached by 12 spec symlinks including lsdef, chdef, mkdef and rmdef, which therefore run in the caller's domain while rpower runs in xcat_t. 3 of the 85 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcat_selinux_package.t | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 40249befa7..d1a9904f76 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -264,9 +264,25 @@ like($te, qr/^role system_r types xcat_image_t;$/m, 'system_r is authorized for like($te, qr/^\s*role unconfined_r types xcat_image_t;$/m, '... and so is unconfined_r, for an administrator who runs genimage'); +# The per-OS programs are the entrypoint, and the geninitrd name needs its own +# pattern: most are symlinks to their sibling genimage, but +# netboot/fedora12/geninitrd is a real program the genimage glob never matches. +# +# /opt/xcat/bin/genimage is NOT one of them. It writes a request to the socket, +# and in --interactive mode it runs the per-OS program through a shell +# (xCAT-client/bin/genimage:453), which transitions on its own. Labelling the +# wrapper gave a dispatching client the authority of the image domain. is_deeply([ grep { fc_type($_) eq 'xcat_image_exec_t' } sort keys %fc ], - [ '/opt/xcat/bin/genimage', '/opt/xcat/share/xcat/netboot/[^/]+/genimage' ], - 'the two genimage programs carry the entrypoint, and nothing else does'); + [ '/opt/xcat/share/xcat/netboot/[^/]+/geninitrd', + '/opt/xcat/share/xcat/netboot/[^/]+/genimage' ], + 'only the per-OS build programs carry the image entrypoint'); +is(fc_type('/opt/xcat/bin/genimage'), 'xcat_client_exec_t', + 'the genimage wrapper is a client, like every other dispatching command'); + +# xcatDBcmds is the third dispatcher: 12 spec symlinks reach it, among them +# lsdef, chdef, mkdef and rmdef, and it does nothing but submit_request. +is(fc_type('/opt/xcat/bin/xcatDBcmds'), 'xcat_client_exec_t', + 'the definition commands enter the domain too'); # THE SECURITY PROPERTY OF THE SPLIT. The image build writes and relabels files # of every type, because it creates an operating system tree. The daemon that From 73323090409fcbca7358ede6ada4fe2c8e026fcc Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:23:54 -0300 Subject: [PATCH 40/91] fix(xcat-core): three paths the file contexts get wrong The wrapper /opt/xcat/bin/genimage carried the image entrypoint, so a command that writes a request to the socket ran with the authority to relabel every type. It is now a client. The build still reaches xcat_image_t: the plugin, and the --interactive mode of the wrapper, run the per-OS program through a shell, and that exec transitions from either caller domain. The per-OS geninitrd gets its own line, because most of those names are symlinks to their sibling genimage but netboot/fedora12/geninitrd is a real program, and the genimage glob never matches it. /opt/xcat/bin/xcatDBcmds is labelled as a client. It is the third dispatcher, reached by 12 symlinks including lsdef, chdef, mkdef and rmdef, and without this they ran in the caller's domain while rpower ran in xcat_t. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 11 +++++++---- xCAT-test/unit/xcat_selinux_package.t | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 26ed9b766a..d69e58c9a5 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -3,12 +3,15 @@ /opt/xcat/sbin/xcatd -- gen_context(system_u:object_r:xcatd_exec_t,s0) /opt/xcat/bin/xcatclient -- gen_context(system_u:object_r:xcat_client_exec_t,s0) /opt/xcat/bin/xcatclientnnr -- gen_context(system_u:object_r:xcat_client_exec_t,s0) +/opt/xcat/bin/xcatDBcmds -- gen_context(system_u:object_r:xcat_client_exec_t,s0) +/opt/xcat/bin/genimage -- gen_context(system_u:object_r:xcat_client_exec_t,s0) -# The entrypoints of the image build. The wrapper and the per-OS program are -# both real files; packimage and liteimg are symlinks to xcatclientnnr, so the -# work they ask for runs in xcat_t. -/opt/xcat/bin/genimage -- gen_context(system_u:object_r:xcat_image_exec_t,s0) +# The entrypoints of the image build are the per-OS programs. The geninitrd +# name needs its own line: most are symlinks to their sibling genimage, but +# netboot/fedora12/geninitrd is a real program. packimage and liteimg are +# symlinks to xcatclientnnr, so the work they ask for runs in xcat_t. /opt/xcat/share/xcat/netboot/[^/]+/genimage -- gen_context(system_u:object_r:xcat_image_exec_t,s0) +/opt/xcat/share/xcat/netboot/[^/]+/geninitrd -- gen_context(system_u:object_r:xcat_image_exec_t,s0) /install(/.*)? gen_context(system_u:object_r:public_content_t,s0) diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index d1a9904f76..8758b2e045 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -273,8 +273,8 @@ like($te, qr/^\s*role unconfined_r types xcat_image_t;$/m, # (xCAT-client/bin/genimage:453), which transitions on its own. Labelling the # wrapper gave a dispatching client the authority of the image domain. is_deeply([ grep { fc_type($_) eq 'xcat_image_exec_t' } sort keys %fc ], - [ '/opt/xcat/share/xcat/netboot/[^/]+/geninitrd', - '/opt/xcat/share/xcat/netboot/[^/]+/genimage' ], + [ '/opt/xcat/share/xcat/netboot/[^/]+/genimage', + '/opt/xcat/share/xcat/netboot/[^/]+/geninitrd' ], 'only the per-OS build programs carry the image entrypoint'); is(fc_type('/opt/xcat/bin/genimage'), 'xcat_client_exec_t', 'the genimage wrapper is a client, like every other dispatching command'); From 11c91fd5124a9cb9cf69a75e2b09184f2e86c049 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:24:15 -0300 Subject: [PATCH 41/91] docs(selinux): the page describes one domain, and there are two The page was written for a single domain and three entrypoints. It now names both domains, the five client entrypoints including xcatDBcmds and the genimage wrapper, and the two per-OS build programs. It also states what each domain holds, so a reader does not take the split for more than it is: xcat_image_t may relabel every type including the security ones, and xcat_t keeps manage and relabel of non-security files because packimage and liteimg run inside xcatd. And it records that a permissive declaration does not cover a transition into a stock domain. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 66 ++++++++++++++++++++------ 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 1a9ef99818..5dd7abadc8 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -10,19 +10,53 @@ Scope This version covers the management node. A service node and a compute node are out of scope: no run measures them, and xCAT does not select their mode. -The xcat_t domain ------------------ +The two domains +--------------- -``xcatd`` and the xCAT client commands run in one domain, ``xcat_t``. The -``xCAT-selinux`` package labels the three files the domain is entered through: +``xcatd`` and the xCAT client commands run in ``xcat_t``. The image build runs +in ``xcat_image_t``, because it creates a complete operating system tree and +therefore writes and relabels files of every type. The ``xCAT-selinux`` package +labels the files each domain is entered through: -============================== ======================= -File Type -============================== ======================= -/opt/xcat/sbin/xcatd ``xcatd_exec_t`` -/opt/xcat/bin/xcatclient ``xcat_client_exec_t`` -/opt/xcat/bin/xcatclientnnr ``xcat_client_exec_t`` -============================== ======================= +=========================================== ======================= +File Type +=========================================== ======================= +/opt/xcat/sbin/xcatd ``xcatd_exec_t`` +/opt/xcat/bin/xcatclient ``xcat_client_exec_t`` +/opt/xcat/bin/xcatclientnnr ``xcat_client_exec_t`` +/opt/xcat/bin/xcatDBcmds ``xcat_client_exec_t`` +/opt/xcat/bin/genimage ``xcat_client_exec_t`` +/opt/xcat/share/xcat/netboot//genimage ``xcat_image_exec_t`` +/opt/xcat/share/xcat/netboot//geninitrd ``xcat_image_exec_t`` +=========================================== ======================= + +``xcatd`` runs the per-OS ``genimage`` through a shell, so the build enters +``xcat_image_t`` from ``xcat_t``. An administrator who runs ``genimage`` +directly enters it the same way. + +What each domain holds +---------------------- + +``xcat_image_t`` may create, write and relabel a file of any type, including the +security types a package installs inside the image: ``/etc/selinux``, the audit +configuration and the keytabs of the image. The kernel cannot tell a path inside +the image from the same type on the management node, so this is the broadest +grant in the module and the reason the build has a domain of its own. + +``xcat_t`` keeps what the daemon needs: its sockets and the ``xcatd`` port, +``/install``, ``/tftpboot``, the configuration of the services it drives, the +credentials under ``/etc/xcat``, and the ``service`` class for the units it +restarts. It also manages and relabels non-security files, because ``packimage`` +and ``liteimg`` are symlinks to ``xcatclientnnr`` and their work runs inside +``xcatd``. What it never gets is the security types. + +Services xCAT starts itself +--------------------------- + +xCAT starts ``in.tftpd`` without a systemd unit. The module transitions it to +the stock ``tftpd_t``, so the TFTP server does not serve UDP 69 with the +authority of the management domain. ``chronyd``, which ``setupntp`` runs, reaches +``chronyd_t`` the same way. systemd enters ``xcat_t`` on the ``xcatd`` script, so the ``ExecStart`` of the unit must name ``xcatd`` and not a shell. 115 command names are symlinks to @@ -35,10 +69,11 @@ Read the domain of the running daemon with:: ps -o label= -p "$(cat /run/xcatd.pid)" ps -eo label,args | grep '[x]catd:' -The domain is permissive ------------------------- +The domains are permissive +-------------------------- -The policy source declares ``permissive xcat_t;``. The host policy stays +The policy source declares ``permissive xcat_t;`` and +``permissive xcat_image_t;``. The host policy stays enforcing, and the kernel records each access that ``xcat_t`` makes outside the rules rather than refusing it. The CI collects those records, and each rule the module gains comes from one of them. A later release removes the declaration @@ -49,6 +84,9 @@ List the permissive domains of the loaded policy with:: semodule -l | grep -x xcat seinfo --permissive +A transition to another domain is not covered by a permissive declaration. +``tftpd_t``, ``chronyd_t`` and the stock domains enforce their own rules. + A denial that the kernel enforced carries ``permissive=0``. On a management node of this version, only such a record reports a refused access:: From 905c63e47c8d9e1bc4bb6449ed2402ad28652395 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:16:55 -0300 Subject: [PATCH 42/91] test(xcat-core): capture the image roots that restorecon relabels xcat.fc excludes a rootimg from the /install relabel only at the default depth, /install/netboot////rootimg. An osimage with rootimgdir=/install/netboot/custom-image resolves rootimg/etc/shadow to public_content_t, so the restorecon -R /install in %posttrans overwrites the labels of the guest operating system. The new native test builds xcat.pp, installs it into a private copy of the targeted store, and asks matchpathcon for the label of each path. Then it labels a copy of /install, relabels it with setfiles after the install and after a reinstall of the module, and reads the labels back. The test fails for the custom roots. The unit test no longer compares the fc lines as text. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .github/workflows/xcat_test.yml | 19 ++- xCAT-test/native/README.md | 15 +++ xCAT-test/native/selinux_file_contexts.t | 150 +++++++++++++++++++++++ xCAT-test/unit/xcat_selinux_package.t | 8 +- 4 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 xCAT-test/native/selinux_file_contexts.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index fc30f70a84..38d67809ab 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -71,8 +71,25 @@ jobs: - name: Install lifecycle test dependencies run: | dnf install -y epel-release - dnf --enablerepo=${{ matrix.repository }} install -y perl perl-Capture-Tiny perl-File-Slurper perl-Test-Simple rpm-build bubblewrap systemd chkconfig initscripts tar gzip which diffutils httpd curl procps-ng + dnf --enablerepo=${{ matrix.repository }} install -y perl perl-Capture-Tiny perl-File-Slurper perl-Test-Simple perl-Test-Harness rpm-build bubblewrap systemd chkconfig initscripts tar gzip which diffutils httpd curl procps-ng - name: Enable lifecycle test namespaces run: sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - name: Test RPM package lifecycle run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/xcatd_rpm_lifecycle.t xCAT-test/native/apache_rpm_configuration.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t' + selinux_policy_test: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + container: + image: almalinux:10 + options: --privileged + steps: + - uses: actions/checkout@v6 + - name: Install policy test dependencies + run: | + dnf install -y epel-release + dnf --enablerepo=crb install -y make selinux-policy-devel selinux-policy-targeted libselinux-utils policycoreutils attr perl perl-Capture-Tiny perl-Test-Simple perl-Test-Harness + - name: Look up and relabel the xCAT file contexts + run: | + mkdir -p /mnt/labels + mount -t tmpfs -o size=1g tmpfs /mnt/labels + TMPDIR=/mnt/labels prove -v xCAT-test/native/selinux_file_contexts.t diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 58d3240c4f..ece2a64e3c 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -111,6 +111,21 @@ an ordinary user with `XCAT_TEST_PG_BINDIR` set to the directory containing XCAT_TEST_PG_BINDIR=/usr/bin prove xCAT-test/native/pgsqlsetup_native_schema.t ``` +The SELinux policy case runs as root in a disposable EL10 container. It needs +`make`, `selinux-policy-devel`, `selinux-policy-targeted`, `libselinux-utils`, +`policycoreutils`, `attr` and Capture::Tiny. It installs the xCAT module into a +private copy of the targeted store, so the host policy does not change. Set +`TMPDIR` to a file system that stores `security.selinux` attributes, such as a +tmpfs: + +``` +TMPDIR=/mnt/labels prove xCAT-test/native/selinux_file_contexts.t +``` + +The case looks up labels in the compiled `file_contexts` and relabels a copy of +`/install` with `setfiles`. It does not need an enforcing kernel, and it does not +run the rpm scriptlets. + Check the TAP output for skipped prerequisites. A successful `prove` exit with skipped cases does not qualify those cases. diff --git a/xCAT-test/native/selinux_file_contexts.t b/xCAT-test/native/selinux_file_contexts.t new file mode 100644 index 0000000000..c0e15681b0 --- /dev/null +++ b/xCAT-test/native/selinux_file_contexts.t @@ -0,0 +1,150 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Capture::Tiny qw(capture); +use File::Path qw(make_path); +use File::Temp qw(tempdir); +use FindBin; +use Test::More; + +# semodule writes a private copy of the targeted policy store, and setfiles +# writes security.selinux attributes. Both need root, not an enforcing kernel. +die "run as root\n" unless $> == 0; +die "requires the targeted policy store\n" unless -d '/var/lib/selinux/targeted'; + +my $work = tempdir(CLEANUP => 1); + +#--- + +=head3 run + + Descriptions: Run a command and die with its output when it fails. + Arguments: The command and its arguments. + Returns: The standard output of the command. + +=cut + +#--- +sub run { + my (@command) = @_; + my ($out, $err, $rc) = capture { system(@command) }; + die "@command: rc=$rc\n$out$err" if $rc != 0; + return $out; +} + +my $build = "$work/build"; +make_path($build); +run('cp', glob("$FindBin::Bin/../../xCAT-selinux/xcat.*"), $build); +run('make', '-C', $build, '-f', '/usr/share/selinux/devel/Makefile', 'xcat.pp'); + +# The policy root is a copy of the host store, so the host policy is unchanged. +my $root = "$work/root"; +make_path("$root/etc/selinux", "$root/var/lib/selinux"); +run('cp', '-a', '/etc/selinux/config', '/etc/selinux/targeted', "$root/etc/selinux/"); +run('cp', '-a', '/var/lib/selinux/targeted', "$root/var/lib/selinux/"); +my $fc = "$root/etc/selinux/targeted/contexts/files/file_contexts"; + +#--- + +=head3 install_module + + Descriptions: Install xcat.pp into the private store, as %post does. + Arguments: None. + Returns: Nothing. + +=cut + +#--- +sub install_module { + run('semodule', '-p', $root, '-i', "$build/xcat.pp"); +} + +#--- + +=head3 lookup + + Descriptions: Ask libselinux for the default label of a path. + Arguments: The path on the management node. + Returns: The type, or <> when restorecon leaves the path alone. + +=cut + +#--- +sub lookup { + my ($path) = @_; + my $out = run('matchpathcon', '-f', $fc, $path); + return $1 if $out =~ /^\S+\s+[^:\s]+:[^:\s]+:(\w+):/; + return '<>' if $out =~ /^\S+\s+<>$/; + die "matchpathcon $path: unexpected output: $out"; +} + +install_module(); + +my @images = ( + '/install/netboot/rhels9/x86_64/compute', + '/install/netboot/custom-image', + '/install/custom/images/rhels9-compute', +); +my @guest = map { ("$_/rootimg/etc/shadow", "$_/rootimg-statelite/etc/shadow") } @images; +my @published = map { + my $dir = $_; + map { "$dir/$_" } qw(kernel initrd-stateless.gz initrd-statelite.gz rootimg.cpio.gz + rootimg.cpio.gz.sha256 rootimg.cpio.gz.metainfo rootimg.tar.xz rootimg.sfs + rootimg-statelite.gz) +} @images; + +foreach my $path (@guest) { + is(lookup($path), '<>', "restorecon leaves $path alone"); +} +foreach my $path (@published, '/install', '/install/postscripts/xcatdsklspost') { + is(lookup($path), 'public_content_t', "$path is public_content_t"); +} + +# A management node: each guest file keeps the label of its own operating +# system, and each published file starts with the label it had before the +# package was installed. +my $mn = "$work/mn"; +my %before; +$before{$_} = 'shadow_t' foreach @guest; +$before{$_} = 'default_t' foreach @published; +foreach my $path (sort keys %before) { + my $file = "$mn$path"; + (my $dir = $file) =~ s{/[^/]+$}{}; + make_path($dir); + open(my $fh, '>', $file) or die "$file: $!"; + close($fh); + run('setfattr', '-n', 'security.selinux', '-v', "system_u:object_r:$before{$path}:s0", $file); +} + +#--- + +=head3 label_of + + Descriptions: Read the security.selinux attribute of a file. + Arguments: The path on the management node. + Returns: The type in the attribute. + +=cut + +#--- +sub label_of { + my ($path) = @_; + my $value = run('getfattr', '--only-values', '-n', 'security.selinux', "$mn$path"); + return $value =~ /^[^:]+:[^:]+:(\w+):/ ? $1 : $value; +} + +# %posttrans runs restorecon -R /install. setfiles -F applies the same +# file_contexts to the copy and also resets the user and role fields. +foreach my $step ('install', 'upgrade') { + install_module() if $step eq 'upgrade'; + run('setfiles', '-F', '-r', $mn, $fc, "$mn/install"); + foreach my $path (@guest) { + is(label_of($path), $before{$path}, "after the $step relabel $path keeps $before{$path}"); + } + foreach my $path (@published) { + is(label_of($path), 'public_content_t', "after the $step relabel $path is public_content_t"); + } +} + +done_testing(); diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t index 8758b2e045..e501ef7d55 100644 --- a/xCAT-test/unit/xcat_selinux_package.t +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -119,12 +119,8 @@ foreach my $section (qw(pre preun post postun posttrans)) { my @fc = grep { !/^\s*(?:#|$)/ } lines_of("$root/xCAT-selinux/xcat.fc"); my %fc = map { (split /\s+/, $_, 2) } @fc; -is($fc{'/install(/.*)?'}, 'gen_context(system_u:object_r:public_content_t,s0)', - '/install is public_content_t'); -is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg(/.*)?'}, '<>', - '... and restorecon leaves a rootimg alone'); -is($fc{'/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)?'}, '<>', - '... and a statelite rootimg too'); +# The labels of /install and of the image trees are looked up in the compiled +# policy by xCAT-test/native/selinux_file_contexts.t. ok(!(grep { m{^/tftpboot} } keys %fc), '/tftpboot keeps the stock tftpdir_t'); # The type of an fc entry, dropping the file-type flag that executables carry. From 66e4cb6a6e13e1d03632cb447edbcddd0d7b6c98 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:18:31 -0300 Subject: [PATCH 43/91] fix(xcat-core): restorecon relabels a rootimg outside the default path xcat.fc excluded a rootimg from the /install relabel only at /install/netboot////rootimg. An osimage whose rootimgdir has another depth got public_content_t on every guest file, so installing or upgrading xCAT-selinux overwrote the labels of the guest operating system. genimage, packimage and statelite put the tree at /rootimg. The two <> entries now match a rootimg or rootimg-statelite path component at any depth under /install. The published files beside the tree, such as kernel, the initrds and rootimg.cpio.gz, keep public_content_t. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index d69e58c9a5..9b24c4bdb3 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -16,5 +16,7 @@ /install(/.*)? gen_context(system_u:object_r:public_content_t,s0) # A rootimg keeps the labels of its own OS, so restorecon must not change them. -/install/netboot/[^/]+/[^/]+/[^/]+/rootimg(/.*)? <> -/install/netboot/[^/]+/[^/]+/[^/]+/rootimg-statelite(/.*)? <> +# genimage puts the tree at /rootimg, and rootimgdir can be at any +# depth under /install. +/install(/.*)?/rootimg(/.*)? <> +/install(/.*)?/rootimg-statelite(/.*)? <> From c922dbcf521f40840f0895d66f2679cafc3ea2bf Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:36:19 -0300 Subject: [PATCH 44/91] test(xcat-core): capture the missing SELinux mode attributes xCAT has no attribute that selects the SELinux mode of a node. The site table help does not describe a selinux key, and noderes has no selinux column, so neither the admin nor the provisioning code can set a mode per site, group or node. selinux_schema.t loads xCAT::Schema and checks the noderes.selinux column, its description, the node and group object attribute, and the site.selinux help. 18 of its 19 checks fail on this commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/selinux_schema.t | 51 +++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 xCAT-test/unit/selinux_schema.t diff --git a/xCAT-test/unit/selinux_schema.t b/xCAT-test/unit/selinux_schema.t new file mode 100644 index 0000000000..255d6d09ff --- /dev/null +++ b/xCAT-test/unit/selinux_schema.t @@ -0,0 +1,51 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use Test::More; + +use xCAT::Schema; + +like($INC{'xCAT/Schema.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::Schema comes from this checkout, not from /opt/xcat'); + +# noderes keys on a node or a group name, so one column gives the node and the +# group settings. +my $noderes = $xCAT::Schema::tabspec{noderes}; +ok((grep { $_ eq 'selinux' } @{ $noderes->{cols} }), + 'noderes has a selinux column'); +my $coldoc = $noderes->{descriptions}{selinux}; +ok(defined $coldoc, '... and the column has a description'); +like($coldoc // '', qr/\benforcing\b/, '... that names enforcing'); +like($coldoc // '', qr/\bpermissive\b/, '... and permissive'); +like($coldoc // '', qr/\bdisabled\b/, '... and disabled'); +like($coldoc // '', qr/site\.selinux/, '... and says site.selinux is the fallback'); + +foreach my $type (qw(node group)) { + my @attrs = grep { $_->{attr_name} eq 'selinux' } + @{ $xCAT::Schema::defspec{$type}{attrs} }; + is(scalar(@attrs), 1, "a $type object has one selinux attribute"); + is($attrs[0] && $attrs[0]{tabentry}, 'noderes.selinux', + "... and the $type attribute is stored in noderes.selinux"); + is($attrs[0] && $attrs[0]{access_tabentry}, 'noderes.node=attr:node', + "... and the $type row is found by the node column"); +} + +my $sitedoc = $xCAT::Schema::tabspec{site}{descriptions}{key}; +my ($selinux_help) = $sitedoc =~ /^( selinux:.*?)(?:\n\n|\z)/ms; +ok(defined $selinux_help, 'the site table help describes the selinux key'); +like($selinux_help // '', qr/\benforcing\b/, '... with the enforcing value'); +like($selinux_help // '', qr/\bpermissive\b/, '... the permissive value'); +like($selinux_help // '', qr/\bdisabled\b/, '... and the disabled value'); +like($selinux_help // '', qr/not set.*\bdisabled\b/s, + '... and says an unset key means disabled'); +like($selinux_help // '', qr/noderes\.selinux/, + '... and names the node and group override'); + +done_testing(); From e0c12830fd1ed249e4fd3c6b556f4b165502675f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:36:38 -0300 Subject: [PATCH 45/91] feat(xcat-core): add site.selinux and noderes.selinux xCAT had no attribute that selects the SELinux mode of a node. site.selinux holds the default mode for the cluster. The values are enforcing, permissive and disabled, and an unset key means disabled. The new noderes.selinux column overrides it for a node or a group, and chdef and lsdef show it as the selinux attribute of node and group objects. Nothing reads the attributes yet. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/Schema.pm | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/perl-xCAT/xCAT/Schema.pm b/perl-xCAT/xCAT/Schema.pm index e03cf2ffab..5d532d63cf 100644 --- a/perl-xCAT/xCAT/Schema.pm +++ b/perl-xCAT/xCAT/Schema.pm @@ -660,7 +660,7 @@ passed as argument rather than by table value', }, }, noderes => { - cols => [qw(node servicenode netboot tftpserver tftpdir nfsserver monserver nfsdir installnic primarynic discoverynics cmdinterface xcatmaster current_osimage next_osimage nimserver routenames nameservers proxydhcp syslog comments disable)], + cols => [qw(node servicenode netboot tftpserver tftpdir nfsserver monserver nfsdir installnic primarynic discoverynics cmdinterface xcatmaster current_osimage next_osimage nimserver routenames nameservers proxydhcp syslog selinux comments disable)], keys => [qw(node)], tablespace => 'XCATTBS16K', table_desc => 'Resources and settings to use when installing nodes.', @@ -696,6 +696,7 @@ passed as argument rather than by table value', nameservers => 'An optional node/group specific override for name server list. Most people want to stick to site or network defined nameserver configuration.', proxydhcp => 'To specify whether the node supports proxydhcp protocol. Valid values: yes or 1, no or 0. Default value is yes.', syslog => "To configure how to configure syslog for compute node. Valid values:blank(not set), ignore. blank - run postscript syslog; ignore - do NOT run postscript syslog", + selinux => 'The SELinux mode of the node after it is provisioned. Valid values: enforcing, permissive, disabled. A node row takes precedence over a group row. If not set, site.selinux is used. Nodes whose OS does not support the xCAT SELinux policy, and statelite nodes, are provisioned with SELinux disabled.', comments => 'Any user-written notes.', disable => "Set to 'yes' or '1' to comment out this row.", }, @@ -1248,6 +1249,11 @@ passed as argument rather than by table value', " If no, it will not generate the mypostscript file in the tftpdir.\n\n" . " secureroot: If set to 1, xCAT will use secure mode to transfer root password hash\n" . " during the installation. Default is 0.\n\n" . +" selinux: The default SELinux mode of the nodes. Valid values are enforcing,\n" . +" permissive and disabled. If not set, the mode is disabled.\n" . +" noderes.selinux overrides this value for a node or a group.\n" . +" xcatconfig sets enforcing at the first install when the management\n" . +" node is enforcing, and disabled otherwise.\n\n" . " setinstallnic: Set the network configuration for installnic to be static.\n\n" . " sharedtftp: Set to 0 or no, xCAT should not assume the directory\n" . " in tftpdir is mounted on all on Service Nodes. Default is 1/yes.\n" . @@ -2078,6 +2084,10 @@ my @nodeattrs = ( tabentry => 'noderes.syslog', access_tabentry => 'noderes.node=attr:node', }, + { attr_name => 'selinux', + tabentry => 'noderes.selinux', + access_tabentry => 'noderes.node=attr:node', + }, { attr_name => 'kernel', tabentry => 'bootparams.kernel', From 7e495f118aeec1d323212a4e14502cbcead62494 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:37:39 -0300 Subject: [PATCH 46/91] test(xcat-core): capture how the SELinux mode of a node is resolved No code resolves the SELinux mode of a node from noderes.selinux and site.selinux. Each provisioning path would need to repeat the precedence and the platform rules. selinux_node_modes.t drives xCAT::SELinux->node_modes with Perl stubs for the noderes, nodetype and osimage tables and for site.selinux. It covers the node row, the group row, the site value, an absent site value, a node that enables SELinux under a disabled site, an invalid value, the SLES and Ubuntu clamp, the osimage OS and the statelite clamp. The test dies on this commit because node_modes does not exist. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/selinux_node_modes.t | 240 ++++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 xCAT-test/unit/selinux_node_modes.t diff --git a/xCAT-test/unit/selinux_node_modes.t b/xCAT-test/unit/selinux_node_modes.t new file mode 100644 index 0000000000..d2c63a81c1 --- /dev/null +++ b/xCAT-test/unit/selinux_node_modes.t @@ -0,0 +1,240 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use Test::More; + +use xCAT::Table; +use xCAT::TableUtils; +use xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +# A table with node rows and group rows. getNodesAttribs gives a node row +# before a group row, as xCAT::Table does. +package FakeTable; + +sub new { + my ($class, %args) = @_; + return bless {%args}, $class; +} + +sub getNodesAttribs { + my ($self, $nodes, $attrs) = @_; + my %result; + foreach my $node (@{$nodes}) { + my @keys = ($node, @{ $self->{groups}{$node} || [] }); + my %row; + foreach my $attr (@{$attrs}) { + foreach my $key (@keys) { + my $value = $self->{rows}{$key}{$attr}; + next unless defined $value && $value ne ''; + $row{$attr} = $value; + last; + } + } + $result{$node} = [ \%row ]; + } + return \%result; +} + +sub getAttribs { + my ($self, $keys, @attrs) = @_; + my $row = $self->{rows}{ $keys->{imagename} } or return undef; + return { map { $_ => $row->{$_} } @attrs }; +} + +sub close { } + +package main; + +# Runs node_modes with the given table contents. +sub modes_for { + my (%args) = @_; + + my %groups = %{ $args{groups} || {} }; + my %tables = ( + noderes => FakeTable->new(rows => $args{noderes} || {}, groups => \%groups), + nodetype => FakeTable->new(rows => $args{nodetype} || {}, groups => \%groups), + osimage => FakeTable->new(rows => $args{osimage} || {}), + ); + my @opened; + + no warnings 'redefine'; + local *xCAT::Table::new = sub { + my ($class, $name) = @_; + push @opened, $name; + return $tables{$name}; + }; + local *xCAT::TableUtils::get_site_attribute = sub { + my ($class, $attr) = @_; + return $attr eq 'selinux' ? $args{site} : undef; + }; + + my %reasons; + my $modes = xCAT::SELinux->node_modes($args{nodes}, \%reasons); + return ($modes, \%reasons, \@opened); +} + +my %EL9 = (os => 'rhels9.4', provmethod => 'install'); + +# The node row wins over the group row and over the site. +{ + my ($modes) = modes_for( + nodes => ['cn1'], + groups => { cn1 => ['compute'] }, + noderes => { cn1 => { selinux => 'permissive' }, compute => { selinux => 'disabled' } }, + nodetype => { cn1 => {%EL9} }, + site => 'enforcing', + ); + is_deeply($modes, { cn1 => 'permissive' }, 'a node row wins over its group row and the site'); +} + +# A group row applies to every member without a node row. +{ + my ($modes) = modes_for( + nodes => [qw(cn1 cn2)], + groups => { cn1 => ['compute'], cn2 => ['compute'] }, + noderes => { compute => { selinux => 'permissive' } }, + nodetype => { compute => {%EL9} }, + site => 'enforcing', + ); + is_deeply($modes, { cn1 => 'permissive', cn2 => 'permissive' }, + 'a group row wins over the site for every member'); +} + +# With no noderes value the site value applies. +{ + my ($modes) = modes_for( + nodes => ['cn1'], + nodetype => { cn1 => {%EL9} }, + site => 'enforcing', + ); + is_deeply($modes, { cn1 => 'enforcing' }, 'the site value applies when noderes has none'); +} + +# Values are case insensitive. +{ + my ($modes) = modes_for( + nodes => ['cn1'], + nodetype => { cn1 => {%EL9} }, + site => ' Enforcing ', + ); + is_deeply($modes, { cn1 => 'enforcing' }, 'the site value is trimmed and lower cased'); +} + +# No noderes value and no site key means disabled. +{ + my ($modes) = modes_for( + nodes => ['cn1'], + nodetype => { cn1 => {%EL9} }, + site => undef, + ); + is_deeply($modes, { cn1 => 'disabled' }, 'an absent site.selinux resolves to disabled'); +} + +# site.selinux=disabled is a default, not a ceiling. +{ + my ($modes) = modes_for( + nodes => [qw(cn1 cn2)], + noderes => { cn1 => { selinux => 'enforcing' } }, + nodetype => { cn1 => {%EL9}, cn2 => {%EL9} }, + site => 'disabled', + ); + is_deeply($modes, { cn1 => 'enforcing', cn2 => 'disabled' }, + 'a node row enables SELinux while the site says disabled'); +} + +# A value that is not a mode does not enable SELinux. +{ + my ($modes, $reasons) = modes_for( + nodes => ['cn1'], + noderes => { cn1 => { selinux => 'yes' } }, + nodetype => { cn1 => {%EL9} }, + site => 'enforcing', + ); + is_deeply($modes, { cn1 => 'disabled' }, 'an invalid noderes value resolves to disabled'); + like($reasons->{cn1}, qr/\byes\b/, '... and the reason names the invalid value'); +} + +# SLES and Ubuntu have no xCAT SELinux policy. +{ + my ($modes, $reasons) = modes_for( + nodes => [qw(sles ubu el)], + nodetype => { + sles => { os => 'sles15.5', provmethod => 'install' }, + ubu => { os => 'ubuntu22.04', provmethod => 'netboot' }, + el => { os => 'alma10.0', provmethod => 'netboot' }, + }, + site => 'enforcing', + ); + is_deeply($modes, { sles => 'disabled', ubu => 'disabled', el => 'enforcing' }, + 'SLES and Ubuntu nodes resolve to disabled, an EL node keeps the site mode'); + like($reasons->{sles}, qr/sles15\.5/, '... and the SLES reason names the OS'); + like($reasons->{ubu}, qr/ubuntu22\.04/, '... and the Ubuntu reason names the OS'); + ok(!exists $reasons->{el}, '... and the EL node has no reason'); +} + +# The OS of an osimage-provisioned node comes from the osimage row. +{ + my ($modes) = modes_for( + nodes => [qw(a b)], + nodetype => { + a => { os => 'rhels9.4', provmethod => 'sles15.5-x86_64-install-compute' }, + b => { provmethod => 'rocky9.4-x86_64-netboot-compute' }, + }, + osimage => { + 'sles15.5-x86_64-install-compute' => + { osvers => 'sles15.5', provmethod => 'install' }, + 'rocky9.4-x86_64-netboot-compute' => + { osvers => 'rocky9.4', provmethod => 'netboot' }, + }, + site => 'enforcing', + ); + is_deeply($modes, { a => 'disabled', b => 'enforcing' }, + 'the osimage osvers decides the platform, not a stale nodetype.os'); +} + +# A node with no known OS cannot be matched to a policy. +{ + my ($modes) = modes_for( + nodes => ['cn1'], + site => 'enforcing', + ); + is_deeply($modes, { cn1 => 'disabled' }, 'a node with no OS resolves to disabled'); +} + +# Statelite resolves to disabled in this version. +{ + my ($modes, $reasons) = modes_for( + nodes => [qw(lite1 lite2)], + noderes => { lite1 => { selinux => 'enforcing' } }, + nodetype => { + lite1 => { os => 'rhels9.4', provmethod => 'statelite' }, + lite2 => { provmethod => 'rhels9.4-x86_64-statelite-compute' }, + }, + osimage => { + 'rhels9.4-x86_64-statelite-compute' => + { osvers => 'rhels9.4', provmethod => 'statelite' }, + }, + site => 'enforcing', + ); + is_deeply($modes, { lite1 => 'disabled', lite2 => 'disabled' }, + 'statelite nodes resolve to disabled, by nodetype or by osimage provmethod'); + like($reasons->{lite1}, qr/statelite/, '... and the reason names statelite'); +} + +# An empty list gives an empty answer. +{ + my ($modes) = modes_for(nodes => [], site => 'enforcing'); + is_deeply($modes, {}, 'no nodes give an empty answer'); +} + +done_testing(); From 9923aadb11f5263b12d2d51726830de169affdb6 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:38:14 -0300 Subject: [PATCH 47/91] feat(xcat-core): resolve the SELinux mode of each node No code resolved the SELinux mode of a node, so each provisioning path would have to repeat the precedence and the platform rules. xCAT::SELinux->node_modes returns the mode for each node. The noderes row of the node comes first, then the noderes rows of its groups, then site.selinux, then disabled. A node or group row can enable SELinux when site.selinux is disabled. A node resolves to disabled when its OS is not in the Red Hat, Fedora or openEuler families, when its OS is not known, and when the node or its osimage is statelite. The OS and the provisioning method come from the osimage row when nodetype.provmethod names one. An optional hash reference receives the reason for each such clamp. With the clamp removed, 7 checks of selinux_node_modes.t fail. With the site value read before noderes, 5 checks fail. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 116 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm index 64c3c1fb7e..e3e34c62b7 100644 --- a/perl-xCAT/xCAT/SELinux.pm +++ b/perl-xCAT/xCAT/SELinux.pm @@ -8,6 +8,11 @@ use warnings; our @ENFORCE_FILES = ('/sys/fs/selinux/enforce', '/selinux/enforce'); our $CONFIG_FILE = '/etc/selinux/config'; +our @MODES = qw(enforcing permissive disabled); + +# The OS families that ship SELinux and get the xCAT policy. SLES 15 and Ubuntu use AppArmor. +our $POLICY_OS = qr/^(?:rhel|rhes|rhels|centos|alma|rocky|ol|fedora|openeuler|sl\d)/i; + #----------------------------------------------------------------------------- =head3 runtime_mode @@ -116,6 +121,117 @@ sub xcatconfig_action { return \%answer; } +#----------------------------------------------------------------------------- + +=head3 node_modes + + Descriptions: + Resolves the SELinux mode each node gets when it is provisioned. + The order is the noderes row of the node, the noderes rows of its + groups, site.selinux, then disabled. A node row can enable SELinux + when site.selinux is disabled. A node resolves to disabled when its + OS has no xCAT SELinux policy, when its OS is not known, and when it + is statelite. + Arguments: + nodes - a reference to a list of node names + reasons - optional hash reference. For each node that resolves to + disabled against its configured mode, the sub sets a message. + Returns: + A hash reference: node name => enforcing, permissive or disabled. + Example: + my $modes = xCAT::SELinux->node_modes(\@nodes, \%why); + +=cut + +#----------------------------------------------------------------------------- +sub node_modes { + my ($class, $nodes, $reasons) = @_; + $reasons = {} unless ref($reasons) eq 'HASH'; + + my %modes; + return \%modes unless $nodes && @{$nodes}; + + require xCAT::Table; + require xCAT::TableUtils; + + my $site = xCAT::TableUtils->get_site_attribute('selinux'); + + my $noderes = _nodes_attribs('noderes', $nodes, ['selinux']); + my $nodetype = _nodes_attribs('nodetype', $nodes, [ 'os', 'provmethod' ]); + my %images; + + foreach my $node (@{$nodes}) { + my $value = $noderes->{$node}{selinux}; + $value = $site unless defined $value && $value =~ /\S/; + my $mode = _normalize_mode($value); + if (!defined $mode) { + $reasons->{$node} = "selinux value '$value' is not one of @MODES"; + $modes{$node} = 'disabled'; + next; + } + + my ($os, $provmethod) = @{ $nodetype->{$node} }{qw(os provmethod)}; + if (defined $provmethod && $provmethod !~ /^(?:install|netboot|statelite)$/) { + $images{$provmethod} ||= _image_attribs($provmethod); + my $image = $images{$provmethod}; + $os = $image->{osvers} if $image->{osvers}; + $provmethod = $image->{provmethod}; + } + + if ($mode ne 'disabled') { + if (!defined $os || $os eq '') { + $reasons->{$node} = "SELinux $mode needs a known OS"; + $mode = 'disabled'; + } elsif ($os !~ $POLICY_OS) { + $reasons->{$node} = "$os has no xCAT SELinux policy"; + $mode = 'disabled'; + } elsif (defined $provmethod && $provmethod eq 'statelite') { + $reasons->{$node} = "statelite does not support SELinux $mode"; + $mode = 'disabled'; + } + } + + $modes{$node} = $mode; + } + + return \%modes; +} + +sub _normalize_mode { + my ($value) = @_; + + return 'disabled' unless defined $value; + $value = lc($value); + $value =~ s/^\s+|\s+$//g; + return 'disabled' if $value eq ''; + return (grep { $_ eq $value } @MODES) ? $value : undef; +} + +sub _nodes_attribs { + my ($table, $nodes, $attrs) = @_; + + my %rows; + my $tab = xCAT::Table->new($table) or return \%rows; + my $all = $tab->getNodesAttribs($nodes, $attrs) || {}; + $tab->close(); + foreach my $node (keys %{$all}) { + my $row = ref($all->{$node}) eq 'ARRAY' ? $all->{$node}[0] : undef; + $rows{$node} = $row if ref($row) eq 'HASH'; + } + + return \%rows; +} + +sub _image_attribs { + my ($imagename) = @_; + + my $tab = xCAT::Table->new('osimage') or return {}; + my $row = $tab->getAttribs({ imagename => $imagename }, 'osvers', 'provmethod'); + $tab->close(); + + return $row || {}; +} + sub _first_line { my ($path) = @_; From 057fe98ccf9b726adcfaa651ea6547a29c3d2081 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:38:29 -0300 Subject: [PATCH 48/91] test(xcat-core): capture the site.selinux default of a first install xcatconfig records no SELinux mode at the first install. A management node that is enforcing therefore leaves site.selinux unset, and its nodes are provisioned with SELinux disabled. xcatconfig_selinux_policy.t now drives xCAT::SELinux->install_default for each runtime mode with no value, an empty value and each existing value. Only an enforcing node records enforcing, and an existing value is kept. The test dies on this commit because install_default does not exist. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcatconfig_selinux_policy.t | 33 ++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/xCAT-test/unit/xcatconfig_selinux_policy.t b/xCAT-test/unit/xcatconfig_selinux_policy.t index 8964bc6ceb..74e5e95ec7 100644 --- a/xCAT-test/unit/xcatconfig_selinux_policy.t +++ b/xCAT-test/unit/xcatconfig_selinux_policy.t @@ -157,4 +157,37 @@ my $CONFIG = "SELINUX=enforcing\nSELINUXTYPE=targeted\n"; 'a commented SELINUX line is ignored'); } +# At the first install, site.selinux records enforcing only for an enforcing +# management node. An existing value is never replaced. +{ + my %expected = ( + enforcing => 'enforcing', + permissive => 'disabled', + disabled => 'disabled', + enabled => 'disabled', + ); + foreach my $mode (sort keys %expected) { + is(xCAT::SELinux->install_default($mode, undef), $expected{$mode}, + "a $mode management node with no site.selinux records $expected{$mode}"); + is(xCAT::SELinux->install_default($mode, ''), $expected{$mode}, + "a $mode management node with an empty site.selinux records $expected{$mode}"); + foreach my $existing (qw(enforcing permissive disabled)) { + is(xCAT::SELinux->install_default($mode, $existing), undef, + "a $mode management node keeps site.selinux=$existing"); + } + } +} + +# install_default only decides. It writes nothing under the root it reads. +{ + my $root = selinux_root(enforce => "1\n", config => $CONFIG); + my $before = tree_contents($root); + my $mode = xCAT::SELinux->runtime_mode(root => $root); + + is(xCAT::SELinux->install_default($mode, undef), 'enforcing', + 'the runtime mode of an enforcing root gives enforcing'); + is_deeply(tree_contents($root), $before, + '... and the enforce file and /etc/selinux/config are not rewritten'); +} + done_testing(); From 9b469b68d5252e09a28ebea3a3f52708d0675824 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:39:24 -0300 Subject: [PATCH 49/91] feat(xcat-core): record the SELinux default at the first install xcatconfig recorded no SELinux mode at the first install, so an enforcing management node left site.selinux unset and its nodes were provisioned with SELinux disabled. At the first install, xcatconfig now sets site.selinux to enforcing when the management node is enforcing, and to disabled when it is permissive or disabled. xCAT::SELinux->install_default makes the decision. An existing site.selinux value stays, and an upgrade does not set it. xcatconfig does not change the SELinux mode of the management node. With the existing value ignored, 12 checks of xcatconfig_selinux_policy.t fail. With a permissive mode recorded as permissive, 4 checks fail. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 26 ++++++++++++++++++++++++++ xCAT-server/sbin/xcatconfig | 31 +++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm index e3e34c62b7..7ad7ca3e34 100644 --- a/perl-xCAT/xCAT/SELinux.pm +++ b/perl-xCAT/xCAT/SELinux.pm @@ -123,6 +123,32 @@ sub xcatconfig_action { #----------------------------------------------------------------------------- +=head3 install_default + + Descriptions: + Decides the site.selinux value that the first install records. + Only an enforcing management node gives enforcing. An existing + value belongs to the admin and stays. + Arguments: + mode - the value runtime_mode returns + existing - the current site.selinux value, or undef + Returns: + 'enforcing' or 'disabled' to write, or undef to write nothing. + Example: + my $value = xCAT::SELinux->install_default($mode, $existing); + +=cut + +#----------------------------------------------------------------------------- +sub install_default { + my ($class, $mode, $existing) = @_; + + return undef if defined $existing && $existing =~ /\S/; + return (defined $mode && $mode eq 'enforcing') ? 'enforcing' : 'disabled'; +} + +#----------------------------------------------------------------------------- + =head3 node_modes Descriptions: diff --git a/xCAT-server/sbin/xcatconfig b/xCAT-server/sbin/xcatconfig index bfde0d055d..43bb5bd9ef 100755 --- a/xCAT-server/sbin/xcatconfig +++ b/xCAT-server/sbin/xcatconfig @@ -32,6 +32,7 @@ use xCAT::SELinux; use Getopt::Long; use xCAT::MsgUtils; use xCAT::Table; +use xCAT::TableUtils; use Socket; #----------------------------------------------------------------------------- @@ -416,6 +417,11 @@ if ($::INITIALINSTALL || $::UPDATEINSTALL || $::FORCE || $::initDB) &initDB; } +if ($::INITIALINSTALL) +{ + &recordselinuxdefault; +} + # # set up syslog # @@ -1080,6 +1086,31 @@ sub is_redhat6sp4 +#----------------------------------------------------------------------------- + +=head3 recordselinuxdefault + + Records site.selinux from the SELinux mode of the management node, when + site.selinux is not set. The mode of the management node does not change. + +=cut + +#----------------------------------------------------------------------------- +sub recordselinuxdefault +{ + my $existing = xCAT::TableUtils->get_site_attribute('selinux'); + my $value = xCAT::SELinux->install_default(xCAT::SELinux->runtime_mode(), $existing); + return unless defined $value; + + xCAT::Utils->runcmd("$::XCATROOT/sbin/chtab key=selinux site.value=$value", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not set site.selinux to $value."); + return; + } + xCAT::MsgUtils->message('I', "Set site.selinux to $value."); +} + #----------------------------------------------------------------------------- =head3 initDB From fabfaedc8953389a4a96130cee5b2a75165e8d62 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:36:53 -0300 Subject: [PATCH 50/91] feat(xcat-core): provision compute and service nodes with SELinux enabled Every compute and service node was provisioned with SELinux disabled. mknetboot added selinux=0, the kickstart templates said selinux --disable, and the genimage postinstall and the dracut hooks wrote SELINUX=disabled into the image. noderes.selinux and site.selinux had no consumer on the node side. The mode that xCAT::SELinux->node_modes resolves now reaches the node: - Kernel command line: mknetboot appends kcmdline_selinux(): selinux=0 for disabled, enforcing=0 for permissive, nothing for enforcing. An image built without the relabel hook (EL7 and older), and a squashfs image without labels, boot with selinux=0 and nodeset says why. Test: selinux_netboot_kcmdline.t. - Kickstart: #SELINUXMODE# and #SELINUXRELABEL# in xCAT::Template. The rh el8/9/10, riscv64 and openEuler templates use them; the %post ends with restorecon -RF over the paths the xCAT scripts write. mkinstall warns when a template cannot express the mode of the node. Test: selinux_kickstart_template.t. - genimage: the el8-10 postinstalls no longer write SELINUX=disabled, and the stateless xcatroot no longer writes /etc/sysconfig/selinux. genimage sets SELINUX=enforcing in the image, adds dracut 98selinux, and installs a pre-pivot hook that runs setfiles with the image file_contexts unless selinux=0 is set. Tests: selinux_image_config.t, selinux_relabel_hook.bats. - packimage -m squashfs stores the labels of the image policy through mksquashfs pseudo xattr definitions (squashfs-tools 4.6 or later), and writes rootimg.sfs.selinux beside the image. Test: selinux_squashfs_labels.t. - Service nodes mount /install and /tftpboot from the management node with context=public_content_t and tftpdir_t when SELinux is on. Test: selinux_sn_mount_options.t. - makedns no longer warns about SELinux. xcatprobe xcatmn checks the xcat module and the labels of installdir and tftpdir instead of failing on enforcing. Test: probe_utils_selinux_policy.t. The selinux/cases1 xcattest cases provision a diskful, a stateless and a squashfs node enforcing, and a stateless node with site.selinux=disabled. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 365 ++++++++++++++++++ xCAT-probe/lib/perl/probe_utils.pm | 41 ++ xCAT-probe/subcmds/xcatmn | 45 ++- xCAT-server/lib/perl/xCAT/Template.pm | 7 + xCAT-server/lib/xcat/plugins/AAsn.pm | 25 +- xCAT-server/lib/xcat/plugins/anaconda.pm | 27 +- xCAT-server/lib/xcat/plugins/ddns.pm | 7 - xCAT-server/lib/xcat/plugins/packimage.pm | 22 ++ .../install/openeuler/compute.openeuler.tmpl | 3 +- .../install/rh/compute.rhels10.riscv64.tmpl | 3 +- .../xcat/install/rh/compute.rhels10.tmpl | 3 +- .../share/xcat/install/rh/compute.rhels8.tmpl | 3 +- .../share/xcat/install/rh/compute.rhels9.tmpl | 3 +- .../rocky/service.rocky10.riscv64.tmpl | 3 +- .../rh/compute.rhels10.ppc64le.postinstall | 7 - .../rh/compute.rhels10.x86_64.postinstall | 7 - .../rh/compute.rhels8.ppc64le.postinstall | 7 - .../rh/compute.rhels8.x86_64.postinstall | 7 - .../rh/compute.rhels9.ppc64le.postinstall | 7 - .../rh/compute.rhels9.x86_64.postinstall | 7 - .../netboot/rh/dracut_047/install.netboot | 1 + .../rh/dracut_047/xcat-selinux-relabel.sh | 35 ++ .../share/xcat/netboot/rh/dracut_047/xcatroot | 4 - .../rh/dracut_105/stateless/module-setup.sh | 3 + .../stateless/xcat-selinux-relabel.sh | 1 + .../netboot/rh/dracut_105/stateless/xcatroot | 4 - xCAT-server/share/xcat/netboot/rh/genimage | 22 ++ .../rocky/compute.rocky10.riscv64.postinstall | 7 - xCAT-test/autotest/testcase/selinux/cases1 | 168 ++++++++ xCAT-test/bats/selinux_relabel_hook.bats | 126 ++++++ xCAT-test/native/netboot_profile_riscv64.t | 6 +- xCAT-test/unit/probe_utils_selinux_policy.t | 58 +++ xCAT-test/unit/selinux_image_config.t | 51 +++ xCAT-test/unit/selinux_kickstart_template.t | 118 ++++++ xCAT-test/unit/selinux_netboot_kcmdline.t | 48 +++ xCAT-test/unit/selinux_sn_mount_options.t | 38 ++ xCAT-test/unit/selinux_squashfs_labels.t | 116 ++++++ 37 files changed, 1298 insertions(+), 107 deletions(-) create mode 100755 xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh create mode 120000 xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh create mode 100644 xCAT-test/autotest/testcase/selinux/cases1 create mode 100644 xCAT-test/bats/selinux_relabel_hook.bats create mode 100644 xCAT-test/unit/probe_utils_selinux_policy.t create mode 100644 xCAT-test/unit/selinux_image_config.t create mode 100644 xCAT-test/unit/selinux_kickstart_template.t create mode 100644 xCAT-test/unit/selinux_netboot_kcmdline.t create mode 100644 xCAT-test/unit/selinux_sn_mount_options.t create mode 100644 xCAT-test/unit/selinux_squashfs_labels.t diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm index 7ad7ca3e34..37f04dc1d5 100644 --- a/perl-xCAT/xCAT/SELinux.pm +++ b/perl-xCAT/xCAT/SELinux.pm @@ -10,6 +10,9 @@ our $CONFIG_FILE = '/etc/selinux/config'; our @MODES = qw(enforcing permissive disabled); +# packimage writes this file beside rootimg.sfs when the squashfs carries the image labels. +our $SQUASHFS_LABELS = 'rootimg.sfs.selinux'; + # The OS families that ship SELinux and get the xCAT policy. SLES 15 and Ubuntu use AppArmor. our $POLICY_OS = qr/^(?:rhel|rhes|rhels|centos|alma|rocky|ol|fedora|openeuler|sl\d)/i; @@ -223,6 +226,368 @@ sub node_modes { return \%modes; } +#----------------------------------------------------------------------------- + +=head3 netboot_supported + + Descriptions: + Reports whether a stateless image of this OS can boot with SELinux on. + genimage builds these images from the dracut_047 or dracut_105 module, + which carries the pre-pivot hook that labels the RAM root. + Arguments: + osver - the OS of the image, for example rhels9.6 or openeuler24.03sp3 + Returns: + 1 when it can, 0 otherwise. + Example: + my $ok = xCAT::SELinux->netboot_supported($osver); + +=cut + +#----------------------------------------------------------------------------- +sub netboot_supported { + my ($class, $osver) = @_; + + return 0 unless defined $osver; + return 1 if $osver =~ /^openeuler/i; + if ($osver =~ /^(?:rhels|rhel|alma|rocky|ol|centos-stream|centos)(\d+)/i) { + return $1 >= 8 ? 1 : 0; + } + + return 0; +} + +#----------------------------------------------------------------------------- + +=head3 kcmdline_selinux + + Descriptions: + Gives the kernel arguments that select the SELinux mode of a + stateless node. One image serves every mode. + Arguments: + mode - the mode node_modes resolved for the node + osver - the OS of the image + Returns: + 'selinux=0' for disabled and for an image that cannot label its root, + 'enforcing=0' for permissive, and the empty string for enforcing. + Example: + $kcmdline .= ' ' . xCAT::SELinux->kcmdline_selinux($mode, $osver); + +=cut + +#----------------------------------------------------------------------------- +sub kcmdline_selinux { + my ($class, $mode, $osver) = @_; + + return 'selinux=0' unless defined $mode && $class->netboot_supported($osver); + return '' if $mode eq 'enforcing'; + return 'enforcing=0' if $mode eq 'permissive'; + return 'selinux=0'; +} + +#----------------------------------------------------------------------------- + +=head3 kickstart_relabel + + Descriptions: + Gives the %post command that relabels the files the xCAT post + scripts wrote. rpm labels what it installs; scripts that write in the + installer chroot can leave the label of the parent directory. + Arguments: + mode - the mode of the node + Returns: + The command, or the empty string when the mode is disabled. + +=cut + +#----------------------------------------------------------------------------- +sub kickstart_relabel { + my ($class, $mode) = @_; + + return '' unless defined $mode && ($mode eq 'enforcing' || $mode eq 'permissive'); + return '/usr/sbin/restorecon -RF /xcatpost /opt/xcat /etc /root /var/log' + . ' || echo "restorecon returned $?"'; +} + +#----------------------------------------------------------------------------- + +=head3 kickstart_mode + + Descriptions: + Reads the SELinux mode a rendered kickstart asks anaconda for. + Arguments: + text - the kickstart + Returns: + enforcing, permissive or disabled. A kickstart with no selinux line + gets the anaconda default, enforcing. + +=cut + +#----------------------------------------------------------------------------- +sub kickstart_mode { + my ($class, $text) = @_; + + my $mode = 'enforcing'; + foreach my $line (split /\n/, (defined $text ? $text : '')) { + next unless $line =~ /^\s*selinux\s+--(\w+)/; + my $word = lc($1); + $mode = $word eq 'disable' ? 'disabled' : $word; + } + + return $mode; +} + +#----------------------------------------------------------------------------- + +=head3 kickstart_mismatch + + Descriptions: + Compares the mode of a node with the mode its kickstart asks for. + A template that hard-codes the selinux line cannot follow the node. + Arguments: + mode - the mode node_modes resolved for the node + text - the rendered kickstart + Returns: + A warning, or undef when both agree. + +=cut + +#----------------------------------------------------------------------------- +sub kickstart_mismatch { + my ($class, $mode, $text) = @_; + + my $asked = $class->kickstart_mode($text); + return undef if !defined $mode || $mode eq $asked; + return "SELinux mode is $mode, but the install template sets $asked. " + . "Use selinux --#SELINUXMODE# in the template."; +} + +#----------------------------------------------------------------------------- + +=head3 write_image_config + + Descriptions: + Sets SELINUX=enforcing in /etc/selinux/config of a rootimg. The + kernel command line that mknetboot writes then selects the mode of + each node. + Arguments: + root - the rootimg directory + Returns: + 1 when the file was written, 0 when the image has no SELinux policy. + +=cut + +#----------------------------------------------------------------------------- +sub write_image_config { + my ($class, %args) = @_; + my $path = "$args{root}$CONFIG_FILE"; + + open(my $in, '<', $path) or return 0; + my @lines = <$in>; + close($in); + + my $found = 0; + foreach my $line (@lines) { + next if $line =~ /^\s*#/; + $found = 1 if $line =~ s/^(\s*SELINUX\s*=\s*)\S*/${1}enforcing/; + } + push @lines, "SELINUX=enforcing\n" unless $found; + + open(my $out, '>', $path) or return 0; + print $out @lines; + close($out); + + return 1; +} + +#----------------------------------------------------------------------------- + +=head3 image_file_contexts + + Descriptions: + Finds the file_contexts of the policy that an image boots with. + Arguments: + root - the image root directory + Returns: + The path of the file under root, or undef when there is none. + +=cut + +#----------------------------------------------------------------------------- +sub image_file_contexts { + my ($class, $root) = @_; + + my $type = 'targeted'; + if (open(my $fh, '<', "$root$CONFIG_FILE")) { + while (my $line = <$fh>) { + $type = $1 if $line =~ /^\s*SELINUXTYPE\s*=\s*(\S+)/; + } + close($fh); + } + my $path = "$root/etc/selinux/$type/contexts/files/file_contexts"; + + return -r $path ? $path : undef; +} + +#----------------------------------------------------------------------------- + +=head3 mksquashfs_supports_pseudo_xattr + + Descriptions: + Reports whether mksquashfs takes xattr pseudo definitions, which + squashfs-tools 4.6 added. + Arguments: + version - the output of mksquashfs -version + Returns: + 1 or 0. + +=cut + +#----------------------------------------------------------------------------- +sub mksquashfs_supports_pseudo_xattr { + my ($class, $version) = @_; + + return 0 unless defined $version && $version =~ /version\s+(\d+)\.(\d+)/; + return ($1 > 4 || ($1 == 4 && $2 >= 6)) ? 1 : 0; +} + +#----------------------------------------------------------------------------- + +=head3 label_paths + + Descriptions: + Looks up the default context of node paths in the file_contexts of + an image. matchpathcon reads the file and does not ask the policy of + this host, so an image type that this host does not know is fine. + Arguments: + file_contexts - the file_contexts of the image + type - file, dir, lnk_file, chr_file, blk_file, sock_file + or fifo_file + paths - a reference to a list of absolute paths on the node + Returns: + A hash reference: path => context. A path with no context is absent. + +=cut + +#----------------------------------------------------------------------------- +sub label_paths { + my ($class, $file_contexts, $type, $paths) = @_; + + my %contexts; + my @todo = @{$paths}; + while (my @batch = splice(@todo, 0, 1000)) { + open(my $fh, '-|', 'matchpathcon', '-m', $type, '-f', $file_contexts, @batch) + or return \%contexts; + while (my $line = <$fh>) { + chomp($line); + $contexts{$1} = $2 if $line =~ /^(.*)\t(\S+)$/ && $2 ne '<>'; + } + close($fh); + } + + return \%contexts; +} + +#----------------------------------------------------------------------------- + +=head3 squashfs_label_args + + Descriptions: + Prepares mksquashfs to store the labels of the image policy. It + writes a pseudo file with one security.selinux definition for each + path, and drops the labels that the temporary copy got on this host. + Arguments: + root - the temporary copy of the rootimg that mksquashfs reads + pseudo - the pseudo file to write + version - the output of mksquashfs -version + Returns: + (\@args) with the mksquashfs arguments, or (undef, $warning) when + the image cannot be labelled. + +=cut + +#----------------------------------------------------------------------------- +sub squashfs_label_args { + my ($class, %args) = @_; + my ($root, $pseudo) = @args{qw(root pseudo)}; + + return (undef, 'squashfs-tools 4.6 or later is needed to store SELinux labels in a squashfs image') + unless $class->mksquashfs_supports_pseudo_xattr($args{version}); + my $fc = $class->image_file_contexts($root); + return (undef, 'the image has no SELinux file_contexts') unless $fc; + + my %by_type; + require File::Find; + File::Find::find({ + no_chdir => 1, + wanted => sub { + my $path = $File::Find::name; + my $rel = substr($path, length($root)); + return if $rel =~ /\n/; + $rel = '/' if $rel eq ''; + push @{ $by_type{ _file_type($path) } }, $rel; + }, + }, $root); + + open(my $out, '>', $pseudo) or return (undef, "cannot write $pseudo: $!"); + foreach my $type (sort keys %by_type) { + my $contexts = $class->label_paths($fc, $type, $by_type{$type}); + foreach my $path (@{ $by_type{$type} }) { + next unless defined $contexts->{$path}; + print $out _pseudo_name($path), " x security.selinux=$contexts->{$path}\n"; + } + } + close($out); + + return ([ '-xattrs-exclude', '^security\.selinux$', '-pf', $pseudo ]); +} + +sub _file_type { + my ($path) = @_; + + return 'lnk_file' if -l $path; + return 'dir' if -d _; + return 'chr_file' if -c _; + return 'blk_file' if -b _; + return 'sock_file' if -S _; + return 'fifo_file' if -p _; + return 'file'; +} + +# mksquashfs reads a quoted pseudo name with backslash escapes, relative to the image root. +sub _pseudo_name { + my ($path) = @_; + + return '"/"' if $path eq '/'; + (my $name = substr($path, 1)) =~ s/(["\\])/\\$1/g; + return "\"$name\""; +} + +#----------------------------------------------------------------------------- + +=head3 nfs_mount_options + + Descriptions: + Gives the mount options for a tree that a service node mounts from + the management node. NFSv3 and NFSv4 without security_label carry no + per-file label, so the mount gets one type for every file. + Arguments: + base - the options without a context + type - the SELinux type of the tree, for example public_content_t + mode - the runtime mode of the service node + Returns: + The options. The kernel refuses context= when SELinux is off, so a + disabled node gets base unchanged. + +=cut + +#----------------------------------------------------------------------------- +sub nfs_mount_options { + my ($class, $base, $type, $mode) = @_; + + return $base if !defined $mode || $mode eq 'disabled'; + return "$base,context=system_u:object_r:$type:s0"; +} + sub _normalize_mode { my ($value) = @_; diff --git a/xCAT-probe/lib/perl/probe_utils.pm b/xCAT-probe/lib/perl/probe_utils.pm index 51f5573eb7..668170e26f 100644 --- a/xCAT-probe/lib/perl/probe_utils.pm +++ b/xCAT-probe/lib/perl/probe_utils.pm @@ -481,6 +481,47 @@ sub is_selinux_enforcing { #------------------------------------------ +=head3 + Description: + Decide the xcatmn verdict on SELinux. xCAT runs with SELinux on when + the xcat policy module is loaded and the xCAT trees carry their types. + Arguments: + mode: enforcing, permissive or disabled + modules: the output of semodule -l + labels: a reference to a list of [path, expected type, context of the path] + Returns: + (level, message) + level is "o" for ok, "w" for warning and "f" for failed +=cut + +#------------------------------------------ +sub selinux_policy_verdict { + my ($mode, $modules, $labels) = @_; + $mode = 'disabled' unless defined $mode; + + return ("o", "SELinux is disabled on current server") if ($mode eq 'disabled'); + + my @problems; + $modules = '' unless defined $modules; + unless (grep { /^xcat(?:\s|$)/ } split(/\n/, $modules)) { + push @problems, "The xcat SELinux module is not loaded. Install xCAT-selinux."; + } + foreach my $label (@{ $labels || [] }) { + my ($path, $expected, $context) = @{$label}; + my $type = (defined $context && $context =~ /^[^:]*:[^:]*:([^:]+)/) ? $1 : undef; + if (!defined $type) { + push @problems, "$path has no SELinux label, expected $expected. Run restorecon -R $path."; + } elsif ($type ne $expected) { + push @problems, "$path has type $type, expected $expected. Run restorecon -R $path."; + } + } + + return ("o", "SELinux is $mode on current server, and the xcat policy is in place") unless (@problems); + return (($mode eq 'enforcing' ? "f" : "w"), join("\n", @problems)); +} + +#------------------------------------------ + =head3 Description: Test if firewall is opened in current operating system diff --git a/xCAT-probe/subcmds/xcatmn b/xCAT-probe/subcmds/xcatmn index 8b5e1b9502..5da5fe83fb 100755 --- a/xCAT-probe/subcmds/xcatmn +++ b/xCAT-probe/subcmds/xcatmn @@ -92,8 +92,8 @@ sub do_main_job { $rst = 0 if ($flag eq "w"); $rc |= $rst; - #check if SElinux is disabled - ($rst, $flag) = check_selinux(\$checkpoint, \@error); + #check the SELinux mode and the xcat policy + ($rst, $flag) = check_selinux(\%sitetable, \$checkpoint, \@error); print_check_result($checkpoint, $flag, $rst, \@error); $rst = 0 if ($flag eq "w"); $rc |= $rst; @@ -683,29 +683,36 @@ sub check_disk { } sub check_selinux { - my $checkpoint_ref = shift; - my $error_ref = shift; - my $rst = 0; - my $flag = "w"; - my $msg = ""; + my $sitetable_ref = shift; + my $checkpoint_ref = shift; + my $error_ref = shift; - $$checkpoint_ref = "Checking SELinux is disabled..."; + $$checkpoint_ref = "Checking SELinux policy for xCAT..."; @$error_ref = (); + my $mode = "disabled"; if (probe_utils->is_selinux_enable()) { - $msg = "SELinux is enabled on current server"; - $rst = 1; - $flag = "w"; + $mode = probe_utils->is_selinux_enforcing() ? "enforcing" : "permissive"; } - if (probe_utils->is_selinux_enforcing()) { - $msg = "SELinux is enforcing on current server"; - $rst = 1; - $flag = "f"; + + my $modules = ""; + my @labels; + if ($mode ne "disabled") { + $modules = `semodule -l 2>/dev/null`; + my $installdir = $sitetable_ref->{installdir} || "/install"; + my $tftpdir = $sitetable_ref->{tftpdir} || "/tftpboot"; + foreach my $dir ([ $installdir, "public_content_t" ], [ $tftpdir, "tftpdir_t" ]) { + my $context = `stat -c %C $dir->[0] 2>/dev/null`; + chomp($context); + push @labels, [ @$dir, ($? == 0 ? $context : undef) ]; + } } - if ($rst) { - push @error_ref, "$msg"; - } - return ($rst, $flag); + + my ($flag, $msg) = probe_utils::selinux_policy_verdict($mode, $modules, \@labels); + return (0, $flag) if ($flag eq "o"); + + push @$error_ref, split(/\n/, $msg); + return (1, $flag); } sub check_firewall { diff --git a/xCAT-server/lib/perl/xCAT/Template.pm b/xCAT-server/lib/perl/xCAT/Template.pm index cf2bfef8ad..747ba01e04 100644 --- a/xCAT-server/lib/perl/xCAT/Template.pm +++ b/xCAT-server/lib/perl/xCAT/Template.pm @@ -18,6 +18,7 @@ use xCAT::TableUtils; use xCAT::NetworkUtils; use xCAT::PasswordUtils; use xCAT::MsgUtils; +use xCAT::SELinux; use XML::Simple; BEGIN @@ -393,6 +394,12 @@ sub subvars { $inc =~ s/#CRYPTORLOCKED:([^:]+):([^:]+):([^#]+)#/crydb_or_locked($1,$2,$3)/eg; $inc =~ s/#COMMAND:([^#]+)#/command($1)/eg; $inc =~ s/#KICKSTARTNET#/kickstartnetwork($platform)/eg; + if ($inc =~ /#SELINUX(?:MODE|RELABEL)#/) { + my $selinux = xCAT::SELinux->node_modes([$node])->{$node}; + $inc =~ s/#SELINUXMODE#/$selinux/g; + my $relabel = xCAT::SELinux->kickstart_relabel($selinux); + $inc =~ s/#SELINUXRELABEL#/$relabel/g; + } $inc =~ s/#MIRRORSPEC#/mirrorspec()/eg; $inc =~ s/#YAST2NET#/yast2network()/eg; $inc =~ s/#KICKSTARTBOOTLOADER#/kickstartbootloader()/eg; diff --git a/xCAT-server/lib/xcat/plugins/AAsn.pm b/xCAT-server/lib/xcat/plugins/AAsn.pm index 543967e3ac..09c97170ae 100644 --- a/xCAT-server/lib/xcat/plugins/AAsn.pm +++ b/xCAT-server/lib/xcat/plugins/AAsn.pm @@ -16,6 +16,7 @@ use xCAT::SvrUtils; use xCAT::TableUtils; use xCAT::NetworkUtils; use xCAT::DHCP::Backend; +use xCAT::SELinux; use xCAT::MsgUtils; use xCAT_plugin::dhcp; @@ -346,15 +347,15 @@ sub setupInstallloc # need to mount the directory my $cmd; + my $options = "rw,nolock"; my @nfsv4 = xCAT::TableUtils->get_site_attribute("useNFSv4onAIX"); if ($nfsv4[0] && ($nfsv4[0] =~ /1|Yes|yes|YES|Y|y/)) { - $cmd = "mount -o vers=4,rw,nolock $master:$installloc $installdir"; - } - else - { - $cmd = "mount -o rw,nolock $master:$installloc $installdir"; + $options = "vers=4,rw,nolock"; } + $options = xCAT::SELinux->nfs_mount_options($options, 'public_content_t', + xCAT::SELinux->runtime_mode()); + $cmd = "mount -o $options $master:$installloc $installdir"; system $cmd; if ($? > 0) { # error @@ -451,7 +452,9 @@ sub setupInstallloc { if ($nomount == 0) # then add the entry { -`echo "$master:$installloc $installdir nfs timeo=14,intr 1 2" >>/etc/fstab`; + my $options = xCAT::SELinux->nfs_mount_options('timeo=14,intr', 'public_content_t', + xCAT::SELinux->runtime_mode()); +`echo "$master:$installloc $installdir nfs $options 1 2" >>/etc/fstab`; } } @@ -1225,15 +1228,15 @@ sub setup_TFTP # need to mount the directory my $cmd; + my $options = "rw,nolock"; my @nfsv4 = xCAT::TableUtils->get_site_attribute("useNFSv4onAIX"); if ($nfsv4[0] && ($nfsv4[0] =~ /1|Yes|yes|YES|Y|y/)) { - $cmd = " mount -o vers=4,rw,nolock $tftphost:$tftpdir $tftpdir"; - } - else - { - $cmd = " mount -o rw,nolock $tftphost:$tftpdir $tftpdir"; + $options = "vers=4,rw,nolock"; } + $options = xCAT::SELinux->nfs_mount_options($options, 'tftpdir_t', + xCAT::SELinux->runtime_mode()); + $cmd = " mount -o $options $tftphost:$tftpdir $tftpdir"; system $cmd; if ($? > 0) { # error diff --git a/xCAT-server/lib/xcat/plugins/anaconda.pm b/xCAT-server/lib/xcat/plugins/anaconda.pm index a06a9fe5f7..4b20bd6a04 100644 --- a/xCAT-server/lib/xcat/plugins/anaconda.pm +++ b/xCAT-server/lib/xcat/plugins/anaconda.pm @@ -18,6 +18,7 @@ use xCAT::NetworkUtils; use xCAT::MsgUtils; use xCAT::SvrUtils; use xCAT::Yum; +use xCAT::SELinux; use Getopt::Long; Getopt::Long::Configure("bundling"); @@ -389,6 +390,9 @@ sub mknetboot $stateHash = $statetab->getNodesAttribs(\@nodes, ['statemnt']); } + my %selinux_why; + my $selinux_modes = xCAT::SELinux->node_modes(\@nodes, \%selinux_why); + foreach my $node (@nodes) { my $osver; @@ -952,10 +956,21 @@ sub mknetboot } } - # turn off the selinux - if ($osver =~ m/(fedora12|fedora13|(?:rhels|ol|alma|rocky)(?:[7-9]|10))/) { - $kcmdline .= " selinux=0 "; + my $selinux = $selinux_modes->{$node} || 'disabled'; + if ($selinux ne 'disabled') { + if (!xCAT::SELinux->netboot_supported($osver)) { + $selinux_why{$node} = "the $osver stateless image cannot label its root"; + $selinux = 'disabled'; + } elsif (defined($compressedrootimg) and $compressedrootimg eq 'rootimg.sfs' + and !-e "$rootimgdir/$xCAT::SELinux::SQUASHFS_LABELS") { + $selinux_why{$node} = "rootimg.sfs has no SELinux labels, run packimage with squashfs-tools 4.6 or later"; + $selinux = 'disabled'; + } } + if ($selinux_why{$node}) { + $callback->({ warning => ["$node: SELinux is disabled: $selinux_why{$node}"] }); + } + $kcmdline .= " " . xCAT::SELinux->kcmdline_selinux($selinux, $osver) . " "; # if kdump service is enbaled, add "crashkernel=" and "kdtarget=" if ($dump) { @@ -1090,6 +1105,7 @@ sub mkinstall my %hents = %{ $hmtab->getNodesAttribs(\@nodes, [ 'serialport', 'serialspeed', 'serialflow' ]) }; my %macents = %{ $mactab->getNodesAttribs(\@nodes, ['mac']) }; + my $selinux_modes = xCAT::SELinux->node_modes(\@nodes); require xCAT::Template; @@ -1388,6 +1404,11 @@ sub mkinstall xCAT::MsgUtils->report_node_error($callback, $node, $tmperr); next; } + if ($os =~ $xCAT::SELinux::POLICY_OS and open(my $ksfh, '<', "/$installroot/autoinst/$node")) { + my $mismatch = xCAT::SELinux->kickstart_mismatch($selinux_modes->{$node}, join('', <$ksfh>)); + close($ksfh); + $callback->({ warning => ["$node: $mismatch"] }) if $mismatch; + } #To support multiple paths for osimage.pkgdir. We require the first value of osimage.pkgdir # should be the os base pkgdir. diff --git a/xCAT-server/lib/xcat/plugins/ddns.pm b/xCAT-server/lib/xcat/plugins/ddns.pm index dc2cb5caa7..4db955585a 100644 --- a/xCAT-server/lib/xcat/plugins/ddns.pm +++ b/xCAT-server/lib/xcat/plugins/ddns.pm @@ -432,13 +432,6 @@ sub process_request { } } - # check for selinux disabled - my $rc = xCAT::Utils->isSELINUX(); - if ($rc == 0) - { - xCAT::SvrUtils::sendmsg([ 0, "Warning:SELINUX is not disabled. The makedns command will not be able to generate a complete DNS setup. Disable SELINUX and run the command again." ], $callback); - - } my @entries = xCAT::TableUtils->get_site_attribute("nameservers"); my $sitens = $entries[0]; unless (defined($site_entry)) { diff --git a/xCAT-server/lib/xcat/plugins/packimage.pm b/xCAT-server/lib/xcat/plugins/packimage.pm index 54293761b5..d89e951713 100644 --- a/xCAT-server/lib/xcat/plugins/packimage.pm +++ b/xCAT-server/lib/xcat/plugins/packimage.pm @@ -37,6 +37,7 @@ use File::Path; use xCAT::Utils; use xCAT::TableUtils; use xCAT::SvrUtils; +use xCAT::SELinux; use xCAT::PasswordUtils; use Digest::MD5 qw(md5_hex); @@ -642,6 +643,7 @@ sub process_request { } $oldmask = umask 0077; } elsif ($method =~ /squashfs/) { + unlink("$destdir/$xCAT::SELinux::SQUASHFS_LABELS"); $temppath = eval { mkdtemp("/tmp/packimage.$$.XXXXXXXX") } or return $native_failure->("Cannot create a staging directory: $@"); chmod 0755, $temppath; @@ -672,9 +674,26 @@ sub process_request { } return $native_failure->("mksquashfs not found, squashfs-tools rpm should be installed on the management node"); } + # The temporary copy has the labels of this host. Store the labels of the image policy. + my $selinux_pseudo; + if ($osver =~ $xCAT::SELinux::POLICY_OS) { + my ($label_args, $label_warning) = xCAT::SELinux->squashfs_label_args( + root => $temppath, + pseudo => "$temppath.selinux", + version => scalar(`mksquashfs -version 2>&1`), + ); + if ($label_args) { + $selinux_pseudo = "$temppath.selinux"; + $flags .= join('', map { " '$_'" } @{$label_args}); + } else { + $callback->({ warning => ["$label_warning. Nodes that boot the squashfs image get SELinux disabled."] }); + } + } + my $mksquashfs_command = "mksquashfs $temppath $archive_output $flags"; xCAT::Utils->runcmd($mksquashfs_command, 0, 1); my $rc = $::RUNCMD_RC; + unlink($selinux_pseudo) if $selinux_pseudo; if ($rc) { return $native_failure->("Command \"$mksquashfs_command\" failed"); } @@ -682,6 +701,9 @@ sub process_request { if ($rc) { return $native_failure->("Failed to clean up temp space"); } + if ($selinux_pseudo and open(my $marker, '>', "$destdir/$xCAT::SELinux::SQUASHFS_LABELS")) { + close($marker); + } } if (my $error = xCAT::SvrUtils->write_rootimg_checksum("$stage/$image_file")) { diff --git a/xCAT-server/share/xcat/install/openeuler/compute.openeuler.tmpl b/xCAT-server/share/xcat/install/openeuler/compute.openeuler.tmpl index 7ff6f5fdc6..77dda6d86e 100644 --- a/xCAT-server/share/xcat/install/openeuler/compute.openeuler.tmpl +++ b/xCAT-server/share/xcat/install/openeuler/compute.openeuler.tmpl @@ -13,7 +13,7 @@ clearpart --all --initlabel %include /tmp/partitionfile #XCAT_PARTITION_END# firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot %packages @@ -34,5 +34,6 @@ cat /tmp/pre-install.log >>/var/log/xcat/xcat.log echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.ng# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels8# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/install/rh/compute.rhels10.riscv64.tmpl b/xCAT-server/share/xcat/install/rh/compute.rhels10.riscv64.tmpl index dbf34f13c7..63e697b6bb 100644 --- a/xCAT-server/share/xcat/install/rh/compute.rhels10.riscv64.tmpl +++ b/xCAT-server/share/xcat/install/rh/compute.rhels10.riscv64.tmpl @@ -28,7 +28,7 @@ clearpart --all --initlabel # Do not configure any iptables rules firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot # riscv64: EL10 has no default crash kernel reservation for this architecture @@ -63,6 +63,7 @@ echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.rhels10# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels10.riscv64# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels10# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/install/rh/compute.rhels10.tmpl b/xCAT-server/share/xcat/install/rh/compute.rhels10.tmpl index 90b60aea85..3c90ba493d 100644 --- a/xCAT-server/share/xcat/install/rh/compute.rhels10.tmpl +++ b/xCAT-server/share/xcat/install/rh/compute.rhels10.tmpl @@ -28,7 +28,7 @@ clearpart --all --initlabel # Do not configure any iptables rules firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot %packages @@ -49,5 +49,6 @@ cat /tmp/pre-install.log >>/var/log/xcat/xcat.log echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.rhels10# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels10# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/install/rh/compute.rhels8.tmpl b/xCAT-server/share/xcat/install/rh/compute.rhels8.tmpl index ddbec300db..64daf4a34f 100644 --- a/xCAT-server/share/xcat/install/rh/compute.rhels8.tmpl +++ b/xCAT-server/share/xcat/install/rh/compute.rhels8.tmpl @@ -28,7 +28,7 @@ clearpart --all --initlabel # Do not configure any iptables rules firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot %packages @@ -54,5 +54,6 @@ cat /tmp/pre-install.log >>/var/log/xcat/xcat.log echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.ng# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels8# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/install/rh/compute.rhels9.tmpl b/xCAT-server/share/xcat/install/rh/compute.rhels9.tmpl index 747703edb9..6cb3a98883 100644 --- a/xCAT-server/share/xcat/install/rh/compute.rhels9.tmpl +++ b/xCAT-server/share/xcat/install/rh/compute.rhels9.tmpl @@ -28,7 +28,7 @@ clearpart --all --initlabel # Do not configure any iptables rules firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot %packages @@ -49,5 +49,6 @@ cat /tmp/pre-install.log >>/var/log/xcat/xcat.log echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.ng# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels8# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/install/rocky/service.rocky10.riscv64.tmpl b/xCAT-server/share/xcat/install/rocky/service.rocky10.riscv64.tmpl index b7c6dc41e5..bc1cc270bd 100644 --- a/xCAT-server/share/xcat/install/rocky/service.rocky10.riscv64.tmpl +++ b/xCAT-server/share/xcat/install/rocky/service.rocky10.riscv64.tmpl @@ -28,7 +28,7 @@ clearpart --all --initlabel # Do not configure any iptables rules firewall --disable -selinux --disable +selinux --#SELINUXMODE# reboot # riscv64: EL10 has no default crash kernel reservation for this architecture @@ -63,6 +63,7 @@ echo "Running Kickstart Post-installation script..." #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.xcat.ng# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels10.riscv64# #INCLUDE:#ENV:XCATROOT#/share/xcat/install/scripts/post.rhels8# +#SELINUXRELABEL# } &>>/var/log/xcat/xcat.log %end diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall index dd2576c8f7..e29e51aeec 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall @@ -32,13 +32,6 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall index 2ad53bb406..8f99e37345 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall @@ -32,13 +32,6 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall index dd2576c8f7..e29e51aeec 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall @@ -32,13 +32,6 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall index 2ad53bb406..8f99e37345 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall @@ -32,13 +32,6 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall index dd2576c8f7..e29e51aeec 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall @@ -32,13 +32,6 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall index 2ad53bb406..8f99e37345 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall @@ -32,13 +32,6 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot b/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot index 0be90b3ec5..d9160f1cc0 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot @@ -8,6 +8,7 @@ dracut_install ethtool inst "$moddir/xcat-updateflag" "/tmp/updateflag" inst "$moddir/xcatroot" "/sbin/xcatroot" inst_hook cmdline 10 "$moddir/xcat-cmdline.sh" +inst_hook pre-pivot 60 "$moddir/xcat-selinux-relabel.sh" for file in /etc/udev/rules.d/*;do grep -qi xcat $file && inst $file $file done diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh new file mode 100755 index 0000000000..d5cbd581f6 --- /dev/null +++ b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Label the stateless root with the policy of the image. dracut 98selinux loads that +# policy at pre-pivot 50, and systemd cannot start from an unlabelled tmpfs root. + +xcat_selinux_relabel() +{ + getarg selinux=0 >/dev/null && return 0 + + # A squashfs root carries its labels, and a relabel would copy every file to the overlay. + [ -e "${xcat_sfs_image:-/rootimg.sfs}" ] && return 0 + + local config="$NEWROOT/etc/selinux/config" mode type fc setfiles rc + [ -r "$config" ] || return 0 + mode=$(sed -n 's/^[[:space:]]*SELINUX[[:space:]]*=[[:space:]]*//p' "$config" | tail -n 1) + [ "$mode" = disabled ] && return 0 + type=$(sed -n 's/^[[:space:]]*SELINUXTYPE[[:space:]]*=[[:space:]]*//p' "$config" | tail -n 1) + fc="/etc/selinux/${type:-targeted}/contexts/files/file_contexts" + if [ ! -r "$NEWROOT$fc" ]; then + warn "xCAT: $fc is not in the image, the root is not labelled" + return 0 + fi + + setfiles=/usr/sbin/setfiles + [ -x "$NEWROOT$setfiles" ] || setfiles=/sbin/setfiles + + mount -t proc proc "$NEWROOT/proc" + mount --bind /sys "$NEWROOT/sys" + chroot "$NEWROOT" "$setfiles" -F -e /proc -e /sys -e /dev "$fc" / + rc=$? + umount "$NEWROOT/sys" + umount "$NEWROOT/proc" + [ "$rc" -eq 0 ] || warn "xCAT: setfiles returned $rc" +} + +xcat_selinux_relabel diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot index 99b7b23317..0e6b683039 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot @@ -412,10 +412,6 @@ fi [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "Saving $NEWROOT/etc/resolv.conf" cp /etc/resolv.conf "$NEWROOT/etc/" -if [ -d "$NEWROOT/etc/sysconfig" -a ! -e "$NEWROOT/etc/sysconfig/selinux" ]; then - [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "disable selinux ..." - echo "SELINUX=disabled" >> "$NEWROOT/etc/sysconfig/selinux" -fi logger $SYSLOGHOST -t $log_label -p local4.info "Exiting xcatroot..." # inject new exit_if_exists diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh index b150bd42c4..28bc073a65 100644 --- a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh +++ b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh @@ -28,6 +28,9 @@ install() { # cmdline hook inst_hook cmdline 10 "$moddir/xcat-cmdline.sh" + # After 98selinux loads the policy of the image at pre-pivot 50. + inst_hook pre-pivot 60 "$moddir/xcat-selinux-relabel.sh" + # udev rules with "xcat" for file in /etc/udev/rules.d/*; do if grep -qi xcat "$file"; then diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh new file mode 120000 index 0000000000..51972524cd --- /dev/null +++ b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh @@ -0,0 +1 @@ +../../dracut_047/xcat-selinux-relabel.sh \ No newline at end of file diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot index 99b7b23317..0e6b683039 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot @@ -412,10 +412,6 @@ fi [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "Saving $NEWROOT/etc/resolv.conf" cp /etc/resolv.conf "$NEWROOT/etc/" -if [ -d "$NEWROOT/etc/sysconfig" -a ! -e "$NEWROOT/etc/sysconfig/selinux" ]; then - [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "disable selinux ..." - echo "SELINUX=disabled" >> "$NEWROOT/etc/sysconfig/selinux" -fi logger $SYSLOGHOST -t $log_label -p local4.info "Exiting xcatroot..." # inject new exit_if_exists diff --git a/xCAT-server/share/xcat/netboot/rh/genimage b/xCAT-server/share/xcat/netboot/rh/genimage index e6c2543ae3..231ffcb8ca 100755 --- a/xCAT-server/share/xcat/netboot/rh/genimage +++ b/xCAT-server/share/xcat/netboot/rh/genimage @@ -20,6 +20,7 @@ use FindBin; use lib "$FindBin::Bin/../imgutils"; use imgutils; use xCAT::Utils; +use xCAT::SELinux; use Digest::MD5 qw(md5_hex); #use strict; @@ -822,6 +823,9 @@ xdie("Error: failed to generate the initial ramdisk: native image has no dracut imgutils::disable_vendor_repositories($rootimg_dir); +# The kernel command line that mknetboot writes selects the SELinux mode of each node. +xCAT::SELinux->write_image_config(root => $rootimg_dir); + #-- run postinstall script unless ($imagename) { $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); @@ -1092,6 +1096,7 @@ sub mkinitrd_dracut { 'installkernel', 'module-setup.sh', 'xcat-cmdline.sh', + 'xcat-selinux-relabel.sh', 'xcatroot', 'xcat-updateflag', ], @@ -1167,6 +1172,12 @@ sub mkinitrd_dracut { } } + # 98selinux loads the policy of the image before the xCAT relabel hook runs. + my @selinux_module = glob($dracutmoduledir . "[0-9]*selinux"); + if (-r "$dracutmpath/xcat-selinux-relabel.sh" and @selinux_module) { + $dracutmodulelist .= " selinux"; + } + # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); print $DRACUTCONF qq{dracutmodules+=" $dracutmodulelist "\n}; @@ -1245,6 +1256,11 @@ sub mkinitrd_dracut { $perm = (stat("$fullpath/$dracutdir/installkernel"))[2]; chmod($perm & 07777, "$dracutmpath/installkernel"); + if (-r "$fullpath/$dracutdir/xcat-selinux-relabel.sh") { + cp("$fullpath/$dracutdir/xcat-selinux-relabel.sh", "$dracutmpath/"); + chmod(0755, "$dracutmpath/xcat-selinux-relabel.sh"); + } + my $dracutmodulelist = "xcat nfs base network kernel-modules syslog"; if (defined(imgutils::openeuler_release_version($osver)) ? scalar(glob($dracutmoduledir . '[0-9]*network-manager')) @@ -1259,6 +1275,12 @@ sub mkinitrd_dracut { } } + # 98selinux loads the policy of the image before the xCAT relabel hook runs. + my @selinux_module = glob($dracutmoduledir . "[0-9]*selinux"); + if (-r "$dracutmpath/xcat-selinux-relabel.sh" and @selinux_module) { + $dracutmodulelist .= " selinux"; + } + # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); print $DRACUTCONF qq{dracutmodules+=" $dracutmodulelist "\n}; diff --git a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall index 015cfec0f9..0cc5674cdc 100755 --- a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall +++ b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall @@ -32,13 +32,6 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab -#-- Disable SELinux in the rootimg -#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default -#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" -if [ -f "$installroot/etc/selinux/config" ] -then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config -fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 new file mode 100644 index 0000000000..e73a1f1e32 --- /dev/null +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -0,0 +1,168 @@ +start:selinux_cn_diskful_enforcing +description:on an enforcing management node, a diskful compute node with noderes.selinux=enforcing boots enforcing, with correct labels and no denial +label:selinux,provision +os:Linux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_diskful.start' +check:rc==0 +cmd:chdef -t node -o $$CN selinux=enforcing +check:rc==0 +cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-install-compute +check:rc==0 +check:output=~Provision node\(s\)\: $$CN +cmd:xdsh $$CN getenforce +check:rc==0 +check:output=~Enforcing +cmd:xdsh $$CN cat /proc/cmdline +check:rc==0 +check:output!~selinux=0 +cmd:xdsh $$CN "ls -dZ /root/.ssh /etc/ssh/sshd_config /opt/xcat /xcatpost" +check:rc==0 +check:output=~ssh_home_t +check:output!~default_t +check:output!~unlabeled_t +cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /var/log/xcat" +check:rc==0 +check:output!~Would relabel +cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +check:output=~ +check:output!~type=AVC +cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskful.start)' +check:rc==1 +check:output=~ +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +cmd:rm -f /tmp/selinux_cn_diskful.start +end + +start:selinux_cn_diskless_enforcing +description:on an enforcing management node, a stateless (cpio) compute node with noderes.selinux=enforcing labels its RAM root at boot and runs enforcing with no denial +label:selinux,provision +os:Linux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_diskless.start' +check:rc==0 +cmd:chdef -t node -o $$CN selinux=enforcing +check:rc==0 +cmd:genimage __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +cmd:packimage -m cpio __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +check:output=~Provision node\(s\)\: $$CN +cmd:xdsh $$CN mount +check:rc==0 +check:output=~on / type tmpfs +cmd:xdsh $$CN getenforce +check:rc==0 +check:output=~Enforcing +cmd:xdsh $$CN cat /proc/cmdline +check:rc==0 +check:output!~selinux=0 +cmd:xdsh $$CN "ls -dZ / /usr/bin/bash /root/.ssh /etc/ssh/sshd_config /opt/xcat /xcatpost" +check:rc==0 +check:output=~bin_t +check:output=~ssh_home_t +check:output!~tmpfs_t +check:output!~default_t +check:output!~unlabeled_t +cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /usr/sbin" +check:rc==0 +check:output!~Would relabel +cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +check:output=~ +check:output!~type=AVC +cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskless.start)' +check:rc==1 +check:output=~ +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +cmd:rm -f /tmp/selinux_cn_diskless.start +end + +start:selinux_cn_diskless_squashfs_enforcing +description:on an enforcing management node with squashfs-tools 4.6 or later, a stateless squashfs compute node with noderes.selinux=enforcing boots from labels stored in the image and runs enforcing with no denial +label:selinux,provision +os:Linux +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_squashfs.start' +check:rc==0 +cmd:chdef -t node -o $$CN selinux=enforcing +check:rc==0 +cmd:sh -c 'rpm -q squashfs-tools || dnf install -y squashfs-tools' +check:rc==0 +cmd:genimage __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +cmd:packimage -m squashfs __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +check:output=~archive method:squashfs +check:output!~Nodes that boot +cmd:sh -c 'ls "$(lsdef -t osimage -o __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute -i rootimgdir -c | cut -d= -f2)/rootimg.sfs.selinux"' +check:rc==0 +cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +check:output=~Provision node\(s\)\: $$CN +cmd:xdsh $$CN mount +check:rc==0 +check:output=~on / type overlay +cmd:xdsh $$CN getenforce +check:rc==0 +check:output=~Enforcing +cmd:xdsh $$CN "ls -dZ / /usr/bin/bash /etc/ssh/sshd_config /opt/xcat /xcatpost" +check:rc==0 +check:output=~bin_t +check:output!~tmp_t +check:output!~default_t +check:output!~unlabeled_t +cmd:xdsh $$CN "restorecon -RnvF /usr/bin /usr/sbin /etc/ssh /xcatpost /opt/xcat" +check:rc==0 +check:output!~Would relabel +cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +check:output=~ +check:output!~type=AVC +cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_squashfs.start)' +check:rc==1 +check:output=~ +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +cmd:rm -f /tmp/selinux_cn_squashfs.start +end + +start:selinux_cn_diskless_site_disabled +description:with site.selinux=disabled and no noderes.selinux value, a stateless compute node boots with SELinux disabled, as before +label:selinux,provision +os:Linux +cmd:sh -c 'lsdef -t site -i selinux -c | cut -d= -f2 > /tmp/selinux_site.orig' +check:rc==0 +cmd:chtab key=selinux site.value=disabled +check:rc==0 +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +cmd:lsdef -t node -o $$CN -i selinux +check:rc==0 +check:output!~selinux=enforcing +check:output!~selinux=permissive +cmd:genimage __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +cmd:packimage -m cpio __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +check:output=~Provision node\(s\)\: $$CN +cmd:xdsh $$CN cat /proc/cmdline +check:rc==0 +check:output=~selinux=0 +cmd:xdsh $$CN getenforce +check:rc==0 +check:output=~Disabled +cmd:sh -c 'chtab key=selinux site.value="$(cat /tmp/selinux_site.orig)"' +check:rc==0 +cmd:rm -f /tmp/selinux_site.orig +end diff --git a/xCAT-test/bats/selinux_relabel_hook.bats b/xCAT-test/bats/selinux_relabel_hook.bats new file mode 100644 index 0000000000..3b794b9bac --- /dev/null +++ b/xCAT-test/bats/selinux_relabel_hook.bats @@ -0,0 +1,126 @@ +#!/usr/bin/env bats +# +# Source the pre-pivot hook that labels a stateless root, as dracut does. getarg, warn, +# mount, umount and chroot are dracut and initramfs commands, so shadow them with functions. + +load 'helpers/shell_source' + +HOOKS=( + 'xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh' + 'xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh' +) + +setup() +{ + NEWROOT="${BATS_TEST_TMPDIR}/sysroot" + CALLS="${BATS_TEST_TMPDIR}/calls" + CMDLINE='' + xcat_sfs_image="${BATS_TEST_TMPDIR}/rootimg.sfs" + mkdir -p "$NEWROOT/etc/selinux/targeted/contexts/files" "$NEWROOT/usr/sbin" "$NEWROOT/proc" "$NEWROOT/sys" + : >"$NEWROOT/etc/selinux/targeted/contexts/files/file_contexts" + : >"$NEWROOT/usr/sbin/setfiles" + chmod 0755 "$NEWROOT/usr/sbin/setfiles" + write_config enforcing targeted + : >"$CALLS" +} + +write_config() +{ + printf 'SELINUX=%s\nSELINUXTYPE=%s\n' "$1" "$2" >"$NEWROOT/etc/selinux/config" +} + +getarg() +{ + local arg + for arg in $CMDLINE; do + [ "$arg" = "$1" ] && return 0 + done + return 1 +} + +warn() { echo "warn: $*" >>"$CALLS"; } +mount() { :; } +umount() { :; } +chroot() { echo "chroot $*" >>"$CALLS"; } + +source_hook() +{ + # dracut sources every hook into its own shell. + . "$(repo_path "$1")" +} + +@test "selinux=0 on the kernel command line runs no setfiles" { + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + CMDLINE='root=1 selinux=0 quiet' + source_hook "$hook" + run cat "$CALLS" + [ -z "$output" ] + done +} + +@test "an enforcing node runs setfiles once with the file_contexts of the image" { + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + CMDLINE='root=1 quiet' + source_hook "$hook" + run grep -c '^chroot ' "$CALLS" + [ "$output" = 1 ] + run cat "$CALLS" + [ "$output" = "chroot $NEWROOT /usr/sbin/setfiles -F -e /proc -e /sys -e /dev /etc/selinux/targeted/contexts/files/file_contexts /" ] + done +} + +@test "a permissive node also runs setfiles" { + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + CMDLINE='root=1 enforcing=0' + source_hook "$hook" + run grep -c '^chroot .*/usr/sbin/setfiles' "$CALLS" + [ "$output" = 1 ] + done +} + +@test "the file_contexts follows SELINUXTYPE of the image" { + mkdir -p "$NEWROOT/etc/selinux/mls/contexts/files" + : >"$NEWROOT/etc/selinux/mls/contexts/files/file_contexts" + write_config enforcing mls + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + source_hook "$hook" + run cat "$CALLS" + [[ "$output" == *" /etc/selinux/mls/contexts/files/file_contexts /" ]] + done +} + +@test "a squashfs root keeps the labels of the image" { + : >"$xcat_sfs_image" + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + source_hook "$hook" + run cat "$CALLS" + [ -z "$output" ] + done +} + +@test "an image configured with SELINUX=disabled runs no setfiles" { + write_config disabled targeted + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + source_hook "$hook" + run grep -c '^chroot ' "$CALLS" + [ "$output" = 0 ] + done +} + +@test "an image without file_contexts warns and runs no setfiles" { + rm -f "$NEWROOT/etc/selinux/targeted/contexts/files/file_contexts" + for hook in "${HOOKS[@]}"; do + : >"$CALLS" + source_hook "$hook" + run grep -c '^chroot ' "$CALLS" + [ "$output" = 0 ] + run grep -c '^warn: .*file_contexts' "$CALLS" + [ "$output" = 1 ] + done +} diff --git a/xCAT-test/native/netboot_profile_riscv64.t b/xCAT-test/native/netboot_profile_riscv64.t index be5109d4c9..20f4e9152f 100644 --- a/xCAT-test/native/netboot_profile_riscv64.t +++ b/xCAT-test/native/netboot_profile_riscv64.t @@ -88,10 +88,8 @@ for my $family (@families) { if ($mode eq 'absent') { ok(!-e "$image/etc/selinux/config", "pass $pass leaves absent SELinux configuration absent"); } else { - local $TODO = 'The existing postinstall duplicates SELINUX= for permissive mode' - if $mode eq 'permissive'; - is(read_text("$image/etc/selinux/config"), "SELINUX=disabled\nSELINUXTYPE=targeted\n", - "pass $pass disables SELinux without changing the policy type"); + is(read_text("$image/etc/selinux/config"), "SELINUX=$mode\nSELINUXTYPE=targeted\n", + "pass $pass keeps the SELinux mode the image was built with"); } my @mounts = map { [split /\s+/] } grep { /\S/ } split /\n/, read_text("$image/etc/fstab"); is_deeply(\@mounts, [ diff --git a/xCAT-test/unit/probe_utils_selinux_policy.t b/xCAT-test/unit/probe_utils_selinux_policy.t new file mode 100644 index 0000000000..e134e951f1 --- /dev/null +++ b/xCAT-test/unit/probe_utils_selinux_policy.t @@ -0,0 +1,58 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-probe/lib/perl"; + +use Test::More; + +require probe_utils; + +like($INC{'probe_utils.pm'}, qr/\Q$FindBin::Bin\E/, 'probe_utils comes from this checkout'); + +# semodule -l prints one module per line; EL8 adds a version column. +my $loaded_el9 = "abrt\nxcat\nzosremote\n"; +my $loaded_el8 = "abrt\t1.4.1\nxcat\t1.0.0\n"; +my $not_loaded = "abrt\nxcatlike\nzosremote\n"; +my @good_labels = ( + [ '/install', 'public_content_t', 'system_u:object_r:public_content_t:s0' ], + [ '/tftpboot', 'tftpdir_t', 'system_u:object_r:tftpdir_t:s0' ], +); + +my ($flag, $msg) = probe_utils::selinux_policy_verdict('disabled', '', []); +is($flag, 'o', 'SELinux disabled is ok, whatever the module'); +like($msg, qr/disabled/, 'the message names the disabled mode'); + +foreach my $modules ($loaded_el9, $loaded_el8) { + ($flag, $msg) = probe_utils::selinux_policy_verdict('enforcing', $modules, \@good_labels); + is($flag, 'o', 'enforcing with the xcat module and the expected labels is ok'); +} + +($flag, $msg) = probe_utils::selinux_policy_verdict('enforcing', $not_loaded, \@good_labels); +is($flag, 'f', 'enforcing without the xcat module fails'); +like($msg, qr/xcat SELinux module is not loaded/, 'the failure names the missing module'); +unlike($msg, qr{/install}, 'the failure does not blame a label that is correct'); + +my @bad_labels = ( + [ '/install', 'public_content_t', 'system_u:object_r:default_t:s0' ], + [ '/tftpboot', 'tftpdir_t', undef ], +); +($flag, $msg) = probe_utils::selinux_policy_verdict('enforcing', $loaded_el9, \@bad_labels); +is($flag, 'f', 'enforcing with a wrong label fails'); +like($msg, qr{/install has type default_t, expected public_content_t}, 'the failure names the path, its type and the expected type'); +like($msg, qr{/tftpboot has no SELinux label, expected tftpdir_t}, 'a path with no label is a failure'); +unlike($msg, qr/module/, 'the failure does not blame a module that is loaded'); + +($flag, $msg) = probe_utils::selinux_policy_verdict('permissive', $not_loaded, \@bad_labels); +is($flag, 'w', 'permissive turns the same findings into a warning'); +like($msg, qr/module.*default_t/s, 'the warning lists every finding'); + +($flag, $msg) = probe_utils::selinux_policy_verdict('permissive', $loaded_el9, \@good_labels); +is($flag, 'o', 'permissive with the module and the labels is ok'); + +done_testing(); diff --git a/xCAT-test/unit/selinux_image_config.t b/xCAT-test/unit/selinux_image_config.t new file mode 100644 index 0000000000..ecd83b5c00 --- /dev/null +++ b/xCAT-test/unit/selinux_image_config.t @@ -0,0 +1,51 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use File::Temp qw(tempdir); +use Test::More; + +use xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +my $root = tempdir(CLEANUP => 1); +make_path("$root/etc/selinux"); +my $config = "$root/etc/selinux/config"; + +# The config an old genimage postinstall left behind. +write_text($config, "# comment SELINUX=keep\nSELINUX=disabled\nSELINUXTYPE=targeted\n"); +ok(xCAT::SELinux->write_image_config(root => $root), 'write_image_config changes a disabled image'); +is(read_text($config), "# comment SELINUX=keep\nSELINUX=enforcing\nSELINUXTYPE=targeted\n", + 'the image boots enforcing unless the kernel command line says otherwise'); +is(xCAT::SELinux->config_mode(root => $root), 'enforcing', 'config_mode of the image reads enforcing'); + +write_text($config, "SELINUX=permissive\nSELINUXTYPE=mls\n"); +xCAT::SELinux->write_image_config(root => $root); +is(read_text($config), "SELINUX=enforcing\nSELINUXTYPE=mls\n", 'a permissive image becomes enforcing; the policy type stays'); + +write_text($config, "SELINUXTYPE=targeted\n"); +xCAT::SELinux->write_image_config(root => $root); +is(read_text($config), "SELINUXTYPE=targeted\nSELINUX=enforcing\n", 'a config with no SELINUX line gets one'); + +my $bare = tempdir(CLEANUP => 1); +ok(!xCAT::SELinux->write_image_config(root => $bare), 'an image without an SELinux policy is left alone'); +ok(!-e "$bare/etc/selinux/config", 'no config is created in an image without an SELinux policy'); + +is(xCAT::SELinux->image_file_contexts($bare), undef, 'an image without a policy has no file_contexts'); +make_path("$root/etc/selinux/mls/contexts/files"); +write_text($config, "SELINUX=enforcing\nSELINUXTYPE=mls\n"); +write_text("$root/etc/selinux/mls/contexts/files/file_contexts", "/.* system_u:object_r:default_t:s0\n"); +is(xCAT::SELinux->image_file_contexts($root), "$root/etc/selinux/mls/contexts/files/file_contexts", + 'image_file_contexts follows SELINUXTYPE of the image'); + +done_testing(); diff --git a/xCAT-test/unit/selinux_kickstart_template.t b/xCAT-test/unit/selinux_kickstart_template.t new file mode 100644 index 0000000000..3ca8a8d8dd --- /dev/null +++ b/xCAT-test/unit/selinux_kickstart_template.t @@ -0,0 +1,118 @@ +#!/usr/bin/env perl +use strict; +use warnings; +no warnings 'once'; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use File::Path qw(make_path); +use File::Slurper qw(read_text); +use File::Temp qw(tempdir); +use Test::More; +use XCAT::Test::File qw(repo_path); + +my $dir = tempdir(CLEANUP => 1); +make_path("$dir/db", "$dir/install"); +symlink(repo_path('xCAT/postscripts'), "$dir/install/postscripts") or die "postscripts link: $!"; +$ENV{XCATROOT} = repo_path('xCAT-server'); +$ENV{XCATCFG} = "SQLite:$dir/db"; +require xCAT::Table; +require xCAT::Template; +require xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +my %site_values = ( + installdir => "$dir/install", tftpdir => "$dir/tftpboot", master => '192.0.2.1', + timezone => 'UTC', xcatiport => 3002, xcatdport => 3001, httpport => 80, + xcatdebugmode => 0, nodestatus => 1, +); +my $site = xCAT::Table->new('site', -create => 1); +for my $key (keys %site_values) { + $site->setAttribs({ key => $key }, { value => $site_values{$key} }); +} +$site->close(); +%::XCATSITEVALS = (%site_values, secureroot => 1, managedaddressmode => 'dhcp'); + +# The maintained kickstart templates, each with an OS that uses it. +my @templates = ( + [ 'rh/compute.rhels10.tmpl', 'rhels10.0', 'rh' ], + [ 'rh/compute.rhels9.tmpl', 'alma9.6', 'rh' ], + [ 'rh/compute.rhels8.tmpl', 'rocky8.10', 'rh' ], + [ 'rh/compute.rhels10.riscv64.tmpl', 'rhels10.0', 'rh' ], + [ 'openeuler/compute.openeuler.tmpl', 'openeuler24.03sp3', 'openeuler' ], +); + +my $relabel = qr{^/usr/sbin/restorecon -RF /xcatpost /opt/xcat /etc /root /var/log\b}m; + +sub set_node { + my ($os, $mode) = @_; + for my $entry ( + [ 'nodelist', { groups => 'all' } ], + [ 'nodetype', { os => $os, arch => 'x86_64', provmethod => 'install' } ], + [ 'noderes', { xcatmaster => '192.0.2.1', nfsserver => '192.0.2.2', installnic => 'mac', selinux => $mode } ], + [ 'mac', { mac => '52:54:00:12:34:56' } ], + ) { + my ($name, $values) = @$entry; + my $tab = xCAT::Table->new($name, -create => 1); + $tab->setAttribs({ node => 'cn1' }, $values); + $tab->close(); + } +} + +# The text of the first %post section: where the xCAT post scripts run. +sub main_post { + my ($ks) = @_; + my ($post) = $ks =~ /^(%post --interpreter=\/bin\/bash.*?^%end)$/ms; + return $post; +} + +foreach my $case (@templates) { + my ($template, $os, $platform) = @$case; + my $path = "$ENV{XCATROOT}/share/xcat/install/$template"; + (my $pkglist = $path) =~ s/\.tmpl$/.pkglist/; + $pkglist = '' unless -r $pkglist; + + foreach my $mode (qw(enforcing permissive disabled)) { + set_node($os, $mode); + my $out = "$dir/ks.$mode"; + my $error = xCAT::Template->subvars($path, $out, 'cn1', $pkglist, + '/install/media', $platform, undef, { xcatmaster => '192.0.2.1' }); + ok(!$error, "$template renders for $mode") or diag($error); + my $ks = read_text($out); + + my @lines = $ks =~ /^(selinux\s.*)$/mg; + is_deeply(\@lines, ["selinux --$mode"], "$template sets selinux --$mode for a $mode node"); + is(xCAT::SELinux->kickstart_mode($ks), $mode, "the $template kickstart asks anaconda for $mode"); + unlike($ks, qr/#SELINUX[A-Z]*#/, "$template leaves no SELinux directive unresolved"); + + my $post = main_post($ks); + ok(defined $post, "$template has a main %post section"); + if ($mode eq 'disabled') { + unlike($ks, $relabel, "$template does not relabel a $mode node"); + } else { + like($post, $relabel, "$template relabels the xCAT files in %post for a $mode node"); + like($post, qr/$relabel.*\n\}\s*&>>\/var\/log\/xcat\/xcat\.log\s*\n%end\z/s, + "$template relabels after the xCAT post scripts ran"); + } + } +} + +# A custom template that keeps the old line cannot express the mode of the node. +is(xCAT::SELinux->kickstart_mode("text\nselinux --disable\nreboot\n"), 'disabled', + 'selinux --disable asks for disabled'); +is(xCAT::SELinux->kickstart_mode("text\nselinux --enforcing\n"), 'enforcing', + 'selinux --enforcing asks for enforcing'); +is(xCAT::SELinux->kickstart_mode("text\nreboot\n"), 'enforcing', + 'a kickstart with no selinux line gets the anaconda default, enforcing'); + +like(xCAT::SELinux->kickstart_mismatch('enforcing', "selinux --disabled\n"), qr/enforcing.*disabled/, + 'an enforcing node with a template that says --disabled gets a warning'); +like(xCAT::SELinux->kickstart_mismatch('disabled', "reboot\n"), qr/disabled.*enforcing/, + 'a disabled node with a template that has no selinux line gets a warning'); +is(xCAT::SELinux->kickstart_mismatch('permissive', "selinux --permissive\n"), undef, + 'a template that matches the mode of the node gets no warning'); + +done_testing(); diff --git a/xCAT-test/unit/selinux_netboot_kcmdline.t b/xCAT-test/unit/selinux_netboot_kcmdline.t new file mode 100644 index 0000000000..5fb4415e67 --- /dev/null +++ b/xCAT-test/unit/selinux_netboot_kcmdline.t @@ -0,0 +1,48 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use Test::More; + +use xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +# The stateless images whose initramfs carries the xCAT relabel hook. +my @supported = qw(rhels8.10 rhels9.6 rhels10.0 alma9.4 alma10.0 rocky8.10 rocky10.0 + ol9.5 centos-stream9 openeuler22.03sp4 openeuler24.03sp3); + +# Images built from the older dracut module, which has no relabel hook. +my @unsupported = qw(rhels7.9 rhels6.10 centos7 ol7.9 fedora13 sles15.6 ubuntu24.04); + +foreach my $osver (@supported) { + is(xCAT::SELinux->kcmdline_selinux('enforcing', $osver), '', + "$osver enforcing adds nothing to the kernel command line"); + is(xCAT::SELinux->kcmdline_selinux('permissive', $osver), 'enforcing=0', + "$osver permissive boots with enforcing=0"); + is(xCAT::SELinux->kcmdline_selinux('disabled', $osver), 'selinux=0', + "$osver disabled boots with selinux=0"); + ok(xCAT::SELinux->netboot_supported($osver), "$osver supports SELinux on a stateless node"); +} + +foreach my $osver (@unsupported) { + foreach my $mode (qw(enforcing permissive disabled)) { + is(xCAT::SELinux->kcmdline_selinux($mode, $osver), 'selinux=0', + "$osver $mode boots with selinux=0, because its initramfs cannot label the root"); + } + ok(!xCAT::SELinux->netboot_supported($osver), "$osver does not support SELinux on a stateless node"); +} + +is(xCAT::SELinux->kcmdline_selinux(undef, 'rhels9.6'), 'selinux=0', + 'an unresolved mode boots with selinux=0'); +is(xCAT::SELinux->kcmdline_selinux('enforcing', undef), 'selinux=0', + 'an unknown OS boots with selinux=0'); + +done_testing(); diff --git a/xCAT-test/unit/selinux_sn_mount_options.t b/xCAT-test/unit/selinux_sn_mount_options.t new file mode 100644 index 0000000000..e2435a667a --- /dev/null +++ b/xCAT-test/unit/selinux_sn_mount_options.t @@ -0,0 +1,38 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use Test::More; + +use xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +foreach my $mode (qw(enforcing permissive enabled)) { + is(xCAT::SELinux->nfs_mount_options('rw,nolock', 'public_content_t', $mode), + 'rw,nolock,context=system_u:object_r:public_content_t:s0', + "a $mode service node mounts /install as public_content_t"); + is(xCAT::SELinux->nfs_mount_options('vers=4,rw,nolock', 'tftpdir_t', $mode), + 'vers=4,rw,nolock,context=system_u:object_r:tftpdir_t:s0', + "a $mode service node mounts /tftpboot as tftpdir_t"); +} + +# The kernel refuses context= when SELinux is off, so the mount must not carry it. +foreach my $mode ('disabled', undef) { + my $name = defined $mode ? $mode : 'undef'; + is(xCAT::SELinux->nfs_mount_options('rw,nolock', 'public_content_t', $mode), 'rw,nolock', + "a service node in mode $name mounts /install as before"); +} + +is(xCAT::SELinux->nfs_mount_options('timeo=14,intr', 'public_content_t', 'enforcing'), + 'timeo=14,intr,context=system_u:object_r:public_content_t:s0', + 'the fstab options get the same context'); + +done_testing(); diff --git a/xCAT-test/unit/selinux_squashfs_labels.t b/xCAT-test/unit/selinux_squashfs_labels.t new file mode 100644 index 0000000000..cbb4a573ed --- /dev/null +++ b/xCAT-test/unit/selinux_squashfs_labels.t @@ -0,0 +1,116 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use File::Path qw(make_path); +use File::Slurper qw(read_lines write_text); +use File::Temp qw(tempdir); +use Test::More; + +use xCAT::SELinux; + +like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, + 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); + +ok(xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.6.1 (2023/03/25)'), + 'squashfs-tools 4.6.1 (EL10, openEuler 24.03) takes pseudo xattr definitions'); +ok(xCAT::SELinux->mksquashfs_supports_pseudo_xattr("mksquashfs version 4.10 (2030/01/01)\ncopyright"), + 'a later minor version takes them too'); +ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.5 (2021/07/22)'), + 'squashfs-tools 4.5 (openEuler 22.03) does not'); +ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.4-git.1 (2020/02/17)'), + 'squashfs-tools 4.4 (EL9) does not'); +ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.3-git (2014/06/09)'), + 'squashfs-tools 4.3 (EL8) does not'); +ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr(undef), 'no version output means no support'); + +# A temporary copy of a rootimg, as packimage makes it before mksquashfs. +my $tmp = tempdir(CLEANUP => 1); +my $root = "$tmp/copy"; +make_path("$root/usr/bin", "$root/etc/selinux/targeted/contexts/files", "$root/a dir"); +my $fc = "$root/etc/selinux/targeted/contexts/files/file_contexts"; +write_text("$root/etc/selinux/config", "SELINUX=enforcing\nSELINUXTYPE=targeted\n"); +write_text($fc, "/.* system_u:object_r:default_t:s0\n"); +write_text("$root/usr/bin/ls", "ELF\n"); +write_text("$root/a dir/say \"hi\"\\now", "x\n"); +write_text("$root/etc/bad\nname", "x\n"); +symlink('ls', "$root/usr/bin/dir") or die "symlink: $!"; + +# label_paths runs matchpathcon against the image policy. Answer by file type instead. +my @lookups; +my %context = (dir => 'root_t', file => 'bin_t', lnk_file => 'lnk_t'); +sub run_args { + my (%args) = @_; + @lookups = (); + no warnings 'redefine'; + local *xCAT::SELinux::label_paths = sub { + my ($class, $file_contexts, $type, $paths) = @_; + push @lookups, [ $file_contexts, $type, [ sort @{$paths} ] ]; + my %answer; + foreach my $path (@{$paths}) { + next if $path eq '/etc/selinux/config'; + $answer{$path} = "system_u:object_r:$context{$type}:s0"; + } + return \%answer; + }; + return xCAT::SELinux->squashfs_label_args(%args); +} + +my $pseudo = "$tmp/pseudo"; +my ($args, $warning) = run_args(root => $root, pseudo => $pseudo, + version => 'mksquashfs version 4.6.1 (2023/03/25)'); +is($warning, undef, 'squashfs-tools 4.6.1 gives no warning'); +is_deeply($args, [ '-xattrs-exclude', '^security\.selinux$', '-pf', $pseudo ], + 'mksquashfs drops the labels of the copy and takes the labels of the image from the pseudo file'); + +is_deeply([ sort map { $_->[1] } @lookups ], [qw(dir file lnk_file)], 'one lookup for each file type'); +is_deeply([ map { $_->[0] } @lookups ], [ ($fc) x 3 ], 'every lookup uses the file_contexts of the image'); +my %paths = map { $_->[1] => $_->[2] } @lookups; +is_deeply($paths{dir}, [ '/', '/a dir', '/etc', '/etc/selinux', '/etc/selinux/targeted', + '/etc/selinux/targeted/contexts', '/etc/selinux/targeted/contexts/files', '/usr', '/usr/bin' ], + 'directories are looked up at their path on the node'); +is_deeply($paths{file}, [ "/a dir/say \"hi\"\\now", '/etc/selinux/config', + '/etc/selinux/targeted/contexts/files/file_contexts', '/usr/bin/ls' ], + 'files are looked up, and a name with a newline is skipped'); +is_deeply($paths{lnk_file}, ['/usr/bin/dir'], 'symbolic links are looked up as lnk_file'); + +my @lines = sort(read_lines($pseudo)); +is_deeply(\@lines, [ sort( + '"/" x security.selinux=system_u:object_r:root_t:s0', + '"a dir" x security.selinux=system_u:object_r:root_t:s0', + '"a dir/say \"hi\"\\\\now" x security.selinux=system_u:object_r:bin_t:s0', + '"etc" x security.selinux=system_u:object_r:root_t:s0', + '"etc/selinux" x security.selinux=system_u:object_r:root_t:s0', + '"etc/selinux/targeted" x security.selinux=system_u:object_r:root_t:s0', + '"etc/selinux/targeted/contexts" x security.selinux=system_u:object_r:root_t:s0', + '"etc/selinux/targeted/contexts/files" x security.selinux=system_u:object_r:root_t:s0', + '"etc/selinux/targeted/contexts/files/file_contexts" x security.selinux=system_u:object_r:bin_t:s0', + '"usr" x security.selinux=system_u:object_r:root_t:s0', + '"usr/bin" x security.selinux=system_u:object_r:root_t:s0', + '"usr/bin/dir" x security.selinux=system_u:object_r:lnk_t:s0', + '"usr/bin/ls" x security.selinux=system_u:object_r:bin_t:s0', + ) ], + 'the pseudo file quotes each name and skips a path the policy gives no context'); + +unlink($pseudo); +($args, $warning) = run_args(root => $root, pseudo => $pseudo, + version => 'mksquashfs version 4.4-git.1 (2020/02/17)'); +is($args, undef, 'squashfs-tools 4.4 gives no label arguments'); +like($warning, qr/4\.6/, 'the warning names the squashfs-tools version that labels the image'); +is(scalar(@lookups), 0, 'squashfs-tools 4.4 looks up no label'); +ok(!-e $pseudo, 'squashfs-tools 4.4 writes no pseudo file'); + +my $bare = "$tmp/bare"; +make_path("$bare/usr"); +($args, $warning) = run_args(root => $bare, pseudo => $pseudo, + version => 'mksquashfs version 4.6.1 (2023/03/25)'); +is($args, undef, 'an image without an SELinux policy gives no label arguments'); +like($warning, qr/file_contexts/, 'the warning says the image has no file_contexts'); + +done_testing(); From d9924c41aea91b83f50ae4c776fb0068a9829e16 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:49:18 -0300 Subject: [PATCH 51/91] fix(xcat-core): every AVC check in the selinux cases reports clean cases0 and cases1 call ausearch eight times to assert that a step produced no AVC denial. On el10, audit 4.0.3 ships an ausearch that reads the journal, and the journal carries no audit records. Measured on an enforcing management node: "ausearch -ts today" returns 0 records while "ausearch --input-logs -ts today" returns 11261, and the raw log holds 1032 denials. So each of the eight checks reports no denials whatever the node does, and the suite cannot fail. Add --input-logs to all eight. The option makes ausearch read /var/log/audit/audit.log, which is where auditd writes. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases1 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index e73a1f1e32..81d5168b16 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -26,10 +26,10 @@ check:output!~unlabeled_t cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /var/log/xcat" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" check:output=~ check:output!~type=AVC -cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskful.start)' +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskful.start)' check:rc==1 check:output=~ cmd:chdef -t node -o $$CN selinux= @@ -74,10 +74,10 @@ check:output!~unlabeled_t cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /usr/sbin" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" check:output=~ check:output!~type=AVC -cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskless.start)' +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskless.start)' check:rc==1 check:output=~ cmd:chdef -t node -o $$CN selinux= @@ -124,10 +124,10 @@ check:output!~unlabeled_t cmd:xdsh $$CN "restorecon -RnvF /usr/bin /usr/sbin /etc/ssh /xcatpost /opt/xcat" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch -m AVC,USER_AVC -ts boot" +cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" check:output=~ check:output!~type=AVC -cmd:sh -c 'ausearch -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_squashfs.start)' +cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_squashfs.start)' check:rc==1 check:output=~ cmd:chdef -t node -o $$CN selinux= From 89dee4de1ec896736716ed46e899efb372399c13 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:42:14 -0300 Subject: [PATCH 52/91] fix(xcat-core): the SELinux AVC checks assert no denial of any kind Eight checks in the selinux testcases asserted ausearch output =~ "", which is zero denials of any kind in the window. A cluster denies things xCAT has nothing to do with. On an idle enforcing management node httpd asks the kernel for net_admin on itself every ten seconds, and the base policy carries no dontaudit rule for that shape. One node logged 1034 denials in a day, 817 of them that one shape. So the assertion cannot pass once ausearch is called correctly, and before --input-logs was added it could not fail. selinux_avc_check.sh keeps the denials whose subject program or object path belongs to xCAT and counts those. The cases assert XCAT_AVC=0. selinux_mn_labels now also plants a denial on purpose: it mislabels /install/postscripts/xcatdsklspost, shows httpd answering 403, and requires the check to report XCAT_AVC=[1-9] before restoring the label. A counting method with no positive control cannot be trusted to find anything. restorecon -RnvF reports a difference in the SELinux user as well as the type, and the files xCAT writes carry unconfined_u. On one node -RnvF printed 12 lines over /install where -Rnv printed 2. The checks use -Rnv, which is the type they assert. The six cases were in no bundle and in no pipeline conf, so none had ever run, which is why the dead checks were not noticed. selinux.bundle and selinux_mn.bundle name them, and selinux_bundle.t fails when a case is in no bundle. Tests: selinux_avc_check.bats drives the classifier with records measured on an enforcing management node. Replacing the filter with one that keeps every record fails 4 of its 8 checks; dropping the object-path branch fails 2. selinux_bundle.t fails when selinux.bundle is removed. selinux_kickstart_template.t asserted the relabel order with a regex that matched wherever the relabel sat; it now compares line positions, and moving #SELINUXRELABEL# above the xCAT post includes fails it. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/bundle/selinux.bundle | 6 ++ xCAT-test/autotest/bundle/selinux_mn.bundle | 3 + .../testcase/commoncmd/selinux_avc_check.sh | 58 ++++++++++++++ xCAT-test/autotest/testcase/selinux/cases0 | 29 ++++++- xCAT-test/autotest/testcase/selinux/cases1 | 54 ++++++++----- xCAT-test/bats/selinux_avc_check.bats | 78 +++++++++++++++++++ xCAT-test/unit/selinux_bundle.t | 37 +++++++++ xCAT-test/unit/selinux_kickstart_template.t | 14 +++- 8 files changed, 252 insertions(+), 27 deletions(-) create mode 100644 xCAT-test/autotest/bundle/selinux.bundle create mode 100644 xCAT-test/autotest/bundle/selinux_mn.bundle create mode 100755 xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh create mode 100644 xCAT-test/bats/selinux_avc_check.bats create mode 100644 xCAT-test/unit/selinux_bundle.t diff --git a/xCAT-test/autotest/bundle/selinux.bundle b/xCAT-test/autotest/bundle/selinux.bundle new file mode 100644 index 0000000000..c911b45964 --- /dev/null +++ b/xCAT-test/autotest/bundle/selinux.bundle @@ -0,0 +1,6 @@ +selinux_xcatd_domain +selinux_mn_labels +selinux_restapi_avc +selinux_cn_diskful_enforcing +selinux_cn_diskless_disabled_by_design +selinux_cn_diskless_site_disabled diff --git a/xCAT-test/autotest/bundle/selinux_mn.bundle b/xCAT-test/autotest/bundle/selinux_mn.bundle new file mode 100644 index 0000000000..bebb26dbce --- /dev/null +++ b/xCAT-test/autotest/bundle/selinux_mn.bundle @@ -0,0 +1,3 @@ +selinux_xcatd_domain +selinux_mn_labels +selinux_restapi_avc diff --git a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh new file mode 100755 index 0000000000..bc3bbd7809 --- /dev/null +++ b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# Report the SELinux denials that xCAT is answerable for, out of the audit records since +# a start time. +# +# A cluster denies things xCAT has nothing to do with. On an idle enforcing management +# node httpd asks the kernel for net_admin on itself every ten seconds, and the base +# policy carries no dontaudit rule for that shape, so a two hour window holds hundreds of +# denials that no change to xCAT can remove. 1034 denials were counted on one node in one +# day, of which 817 were that one shape. "The window holds no denial" is therefore not a +# test xCAT can pass. This script keeps the denials whose subject program or object path +# belongs to xCAT, and counts those. +# +# ausearch reads the journal unless it is told otherwise, and on el10 the journal carries +# no audit records, so --input-logs is not optional: without it the search returns 0 +# records and every answer is "clean". +# +# Usage: +# selinux_avc_check.sh search and report +# selinux_avc_check.sh --classify read raw records on stdin +# +# Prints: SEARCHED= AVC= XCAT_AVC= +# then the records it kept. +# Exits: 0 when it kept none, 1 when it kept any, 2 on a usage error. + +# Subjects: the programs xCAT runs. Objects: the directories xCAT owns. +XCAT_AVC_COMM='xcatd|genimage|packimage|nodeset|mknb|makedhcp|makedns|makehosts|makeknownhosts|copycds|liteimg|xdsh|xdcp|xcatprobe|xcatconfig' +XCAT_AVC_PATH='/opt/xcat|/xcatpost|/tftpboot|/install|/var/log/xcat|/etc/xcat|/var/lib/xcat' + +selinux_avc_classify() +{ + grep -E "(comm|exe)=\"[^\"]*(${XCAT_AVC_COMM})[^\"]*\"|(path|name)=\"[^\"]*(${XCAT_AVC_PATH})" +} + +selinux_avc_report() +{ + since=$1 + [ -n "$since" ] || return 2 + + searched=$(ausearch --input-logs -ts "$since" --raw 2>/dev/null | grep -c '^type=') + denials=$(ausearch --input-logs -m AVC,USER_AVC -ts "$since" --raw 2>/dev/null) + all=$(printf '%s\n' "$denials" | grep -c '^type=') + kept=$(printf '%s\n' "$denials" | selinux_avc_classify) + ours=$(printf '%s\n' "$kept" | grep -c '^type=') + + echo "SEARCHED=$searched AVC=$all XCAT_AVC=$ours" + [ "$ours" -eq 0 ] && return 0 + printf '%s\n' "$kept" + return 1 +} + +# Sourced by the bats test, which calls the functions directly. +if [ "$(basename "$0")" = selinux_avc_check.sh ]; then + case $1 in + --classify) selinux_avc_classify ;; + '') echo "usage: $0 " >&2; exit 2 ;; + *) selinux_avc_report "$1" ;; + esac +fi diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index 364ac84ab1..eef22eb219 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -58,7 +58,7 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; true' +cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; date "+%x %T" > /tmp/selinux_mn_labels.start; true' check:rc==0 cmd:rpm -q xCAT-selinux check:rc==0 @@ -96,7 +96,25 @@ check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_mn_labels.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:rm -f /tmp/selinux_mn_labels.ck /tmp/selinux_mn_labels.avc +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_mn_labels.start)"' +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:sh -c 'date "+%x %T" > /tmp/selinux_mn_control.start; sleep 1; chcon -t shadow_t /install/postscripts/xcatdsklspost' +check:rc==0 +cmd:sh -c 'curl -s -o /dev/null -w "%{http_code}" http://localhost/install/postscripts/xcatdsklspost' +check:rc==0 +check:output=~403 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_mn_control.start)"' +check:rc==1 +check:output=~XCAT_AVC=[1-9] +cmd:restorecon -F /install/postscripts/xcatdsklspost +check:rc==0 +cmd:ls -Z /install/postscripts/xcatdsklspost +check:rc==0 +check:output=~:public_content_t: +cmd:sh -c 'curl -s -f -o /dev/null http://localhost/install/postscripts/xcatdsklspost' +check:rc==0 +cmd:rm -f /tmp/selinux_mn_labels.start /tmp/selinux_mn_control.start /tmp/selinux_mn_labels.ck /tmp/selinux_mn_labels.avc end start:selinux_restapi_avc @@ -105,7 +123,7 @@ label:mn_only,selinux,restapi cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; true' +cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; date "+%x %T" > /tmp/selinux_restapi_avc.start; true' check:rc==0 cmd:sh -c 'rpm -q mod_ssl || dnf install -y mod_ssl' check:rc==0 @@ -121,5 +139,8 @@ check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_restapi_avc.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:rm -f /tmp/selinux_restapi_avc.ck /tmp/selinux_restapi_avc.avc +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_restapi_avc.start)"' +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:rm -f /tmp/selinux_restapi_avc.start /tmp/selinux_restapi_avc.ck /tmp/selinux_restapi_avc.avc end diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index 81d5168b16..932188687a 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -23,15 +23,19 @@ check:rc==0 check:output=~ssh_home_t check:output!~default_t check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /var/log/xcat" +cmd:xdsh $$CN "restorecon -Rnv /xcatpost /opt/xcat /root /etc/ssh /var/log/xcat" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" -check:output=~ -check:output!~type=AVC -cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskful.start)' -check:rc==1 -check:output=~ +cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ +check:rc==0 +cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" +check:rc==0 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_diskful.start)"' +check:rc==0 +check:output=~XCAT_AVC=0 cmd:chdef -t node -o $$CN selinux= check:rc==0 cmd:rm -f /tmp/selinux_cn_diskful.start @@ -71,15 +75,19 @@ check:output=~ssh_home_t check:output!~tmpfs_t check:output!~default_t check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -RnvF /xcatpost /opt/xcat /root /etc/ssh /usr/sbin" +cmd:xdsh $$CN "restorecon -Rnv /xcatpost /opt/xcat /root /etc/ssh /usr/sbin" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" -check:output=~ -check:output!~type=AVC -cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_diskless.start)' -check:rc==1 -check:output=~ +cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ +check:rc==0 +cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" +check:rc==0 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_diskless.start)"' +check:rc==0 +check:output=~XCAT_AVC=0 cmd:chdef -t node -o $$CN selinux= check:rc==0 cmd:rm -f /tmp/selinux_cn_diskless.start @@ -121,15 +129,19 @@ check:output=~bin_t check:output!~tmp_t check:output!~default_t check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -RnvF /usr/bin /usr/sbin /etc/ssh /xcatpost /opt/xcat" +cmd:xdsh $$CN "restorecon -Rnv /usr/bin /usr/sbin /etc/ssh /xcatpost /opt/xcat" check:rc==0 check:output!~Would relabel -cmd:xdsh $$CN "ausearch --input-logs -m AVC,USER_AVC -ts boot" -check:output=~ -check:output!~type=AVC -cmd:sh -c 'ausearch --input-logs -m AVC,USER_AVC -ts $(cat /tmp/selinux_cn_squashfs.start)' -check:rc==1 -check:output=~ +cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ +check:rc==0 +cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" +check:rc==0 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_squashfs.start)"' +check:rc==0 +check:output=~XCAT_AVC=0 cmd:chdef -t node -o $$CN selinux= check:rc==0 cmd:rm -f /tmp/selinux_cn_squashfs.start diff --git a/xCAT-test/bats/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats new file mode 100644 index 0000000000..8decd6a85e --- /dev/null +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -0,0 +1,78 @@ +#!/usr/bin/env bats +# +# The classifier that decides which SELinux denials xCAT is answerable for. The records +# below are real: they were captured on an enforcing AlmaLinux 10 management node while a +# compute node was provisioned. + +load 'helpers/shell_source' + +setup() +{ + . "$(repo_path 'xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh')" +} + +classify() +{ + printf '%s\n' "$@" | selinux_avc_classify +} + +count_kept() +{ + printf '%s\n' "$@" | selinux_avc_classify | grep -c '^type=' +} + +# httpd serving /tftpboot through the xcat.conf AliasMatch. This is the one the xcat +# policy module exists for, so a denial here is xCAT's. +XCAT_RECORD='type=AVC msg=audit(1759000000.111:222): avc: denied { getattr } for pid=1234 comm="httpd" path="/tftpboot/xcat/xnba.kpxe" dev="vda2" ino=55 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:shadow_t:s0 tclass=file permissive=0' + +# httpd asking for net_admin on itself, every ten seconds, on an idle node. 817 of 1034 +# denials on one node in one day were this shape. +TIMER_RECORD='type=AVC msg=audit(1759000001.222:333): avc: denied { net_admin } for pid=2345 comm="httpd" scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:httpd_t:s0 tclass=capability permissive=0' + +# An ordinary ssh login. cluster-test.pl makes one on every step. +SSH_RECORD='type=AVC msg=audit(1759000002.333:444): avc: denied { siginh } for pid=3456 comm="sshd" scontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tcontext=system_u:system_r:sshd_session_t:s0-s0:c0.c1023 tclass=process permissive=0' + +@test "a denial on an xCAT directory is kept" { + run classify "$XCAT_RECORD" + [ "$status" -eq 0 ] + [[ "$output" == *'/tftpboot/xcat/xnba.kpxe'* ]] +} + +@test "the httpd net_admin timer is not kept" { + run classify "$TIMER_RECORD" + [ -z "$output" ] +} + +@test "an ssh login denial is not kept" { + run classify "$SSH_RECORD" + [ -z "$output" ] +} + +@test "one xCAT denial among the noise is found and counted once" { + run count_kept "$TIMER_RECORD" "$XCAT_RECORD" "$SSH_RECORD" "$TIMER_RECORD" + [ "$status" -eq 0 ] + [ "$output" = "1" ] +} + +@test "a window of noise alone is kept empty" { + run classify "$TIMER_RECORD" "$SSH_RECORD" + [ -z "$output" ] +} + +@test "a denial by an xCAT program is kept whatever the path" { + local record='type=AVC msg=audit(1759000003.444:555): avc: denied { read } for pid=4567 comm="genimage" name="dracut.conf" scontext=system_u:system_r:unconfined_service_t:s0 tcontext=system_u:object_r:etc_t:s0 tclass=file permissive=0' + run classify "$record" + [ "$status" -eq 0 ] + [[ "$output" == *'comm="genimage"'* ]] +} + +@test "a program whose name merely contains a kept word is not matched by accident" { + local record='type=AVC msg=audit(1759000004.555:666): avc: denied { execute } for pid=5678 comm="systemd-udevd" scontext=system_u:system_r:udev_t:s0 tcontext=system_u:object_r:bin_t:s0 tclass=file permissive=0' + run classify "$record" + [ -z "$output" ] +} + +@test "the report refuses a call with no start time" { + run "$(repo_path 'xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh')" + [ "$status" -eq 2 ] +} diff --git a/xCAT-test/unit/selinux_bundle.t b/xCAT-test/unit/selinux_bundle.t new file mode 100644 index 0000000000..dc7a7e721c --- /dev/null +++ b/xCAT-test/unit/selinux_bundle.t @@ -0,0 +1,37 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use File::Slurper qw(read_lines); +use Test::More; + +# A case that no bundle names is a case no run selects. The six SELinux cases were in no +# bundle and in no pipeline conf, so none of them had ever run, and eight checks that +# could never pass went unnoticed for that reason. +my $root = "$FindBin::Bin/../.."; +my $dir = "$root/xCAT-test/autotest/testcase/selinux"; + +my @cases; +foreach my $file (sort glob("$dir/cases*")) { + push @cases, map { /^start:(\S+)/ ? $1 : () } read_lines($file); +} +ok(scalar(@cases) >= 6, "the selinux testcase files declare @{[scalar @cases]} cases"); + +my %bundled; +foreach my $bundle (sort glob("$root/xCAT-test/autotest/bundle/*.bundle")) { + $bundled{$_} = 1 for grep { /\S/ } read_lines($bundle); +} +ok(scalar(keys %bundled) > 100, "the bundles name @{[scalar keys %bundled]} cases in total"); + +my @orphans = grep { !$bundled{$_} } @cases; +is_deeply(\@orphans, [], 'every selinux case is named by a bundle'); + +my @mn = grep { /\S/ } read_lines("$root/xCAT-test/autotest/bundle/selinux_mn.bundle"); +my %mn = map { $_ => 1 } @mn; +foreach my $case (@cases) { + next unless $case =~ /_cn_/; + ok(!$mn{$case}, "$case needs a compute node, so the management node bundle leaves it out"); +} + +done_testing(); diff --git a/xCAT-test/unit/selinux_kickstart_template.t b/xCAT-test/unit/selinux_kickstart_template.t index 3ca8a8d8dd..0d7bd71b2b 100644 --- a/xCAT-test/unit/selinux_kickstart_template.t +++ b/xCAT-test/unit/selinux_kickstart_template.t @@ -94,8 +94,18 @@ foreach my $case (@templates) { unlike($ks, $relabel, "$template does not relabel a $mode node"); } else { like($post, $relabel, "$template relabels the xCAT files in %post for a $mode node"); - like($post, qr/$relabel.*\n\}\s*&>>\/var\/log\/xcat\/xcat\.log\s*\n%end\z/s, - "$template relabels after the xCAT post scripts ran"); + + # The relabel has to run after the xCAT post scripts wrote their files, so + # compare where each one lands. A regex that only spans from the relabel to + # the end of %post passes wherever the relabel sits. + my @post_lines = split(/\n/, $post); + my ($relabel_at) = grep { $post_lines[$_] =~ $relabel } 0 .. $#post_lines; + my @xcat_at = grep { + $_ != $relabel_at && $post_lines[$_] =~ /mypostscript|xcatdsklspost|updateflag/ + } 0 .. $#post_lines; + ok(scalar(@xcat_at) > 0, "$template runs the xCAT post scripts in %post"); + ok(defined $relabel_at && $relabel_at > $xcat_at[-1], + "$template relabels at line $relabel_at, after the last xCAT post script at line $xcat_at[-1]"); } } } From b3038a27410fa8b6c0fc4d13e8de169872a44482 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:42:21 -0300 Subject: [PATCH 53/91] test(xcat-core): capture the stateless SELinux claim that no node meets netboot_supported() answers 1 for rhels8 and later and for every openEuler, so mknetboot omits selinux=0 and a stateless node is told to run SELinux. No stateless node has been measured booting that way. This test asserts the opposite: every OS answers 0, every mode gets selinux=0, and no dracut module ships a relabel hook. It fails on this commit, which is the point. The walk of the netboot tree carries a positive control, so an empty hook list means the hooks are gone and not that the walk looked nowhere. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/selinux_netboot_kcmdline.t | 63 ++++++++++++++++------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/xCAT-test/unit/selinux_netboot_kcmdline.t b/xCAT-test/unit/selinux_netboot_kcmdline.t index 5fb4415e67..3850869660 100644 --- a/xCAT-test/unit/selinux_netboot_kcmdline.t +++ b/xCAT-test/unit/selinux_netboot_kcmdline.t @@ -8,6 +8,7 @@ BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } use FindBin; use lib "$FindBin::Bin/../../perl-xCAT"; +use File::Find (); use Test::More; use xCAT::SELinux; @@ -15,34 +16,58 @@ use xCAT::SELinux; like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); -# The stateless images whose initramfs carries the xCAT relabel hook. -my @supported = qw(rhels8.10 rhels9.6 rhels10.0 alma9.4 alma10.0 rocky8.10 rocky10.0 - ol9.5 centos-stream9 openeuler22.03sp4 openeuler24.03sp3); +# A stateless root is a cpio archive unpacked into tmpfs. It starts unlabelled, and no +# measured boot of a stateless node has reached enforcing. So every stateless node gets +# selinux=0, whatever its OS and whatever mode noderes.selinux and site.selinux resolve. +my @osvers = qw(rhels8.10 rhels9.6 rhels10.0 alma9.4 alma10.0 rocky8.10 rocky10.0 + ol9.5 centos-stream9 openeuler22.03sp4 openeuler24.03sp3 rhels7.9 fedora13 + sles15.6 ubuntu24.04); -# Images built from the older dracut module, which has no relabel hook. -my @unsupported = qw(rhels7.9 rhels6.10 centos7 ol7.9 fedora13 sles15.6 ubuntu24.04); - -foreach my $osver (@supported) { - is(xCAT::SELinux->kcmdline_selinux('enforcing', $osver), '', - "$osver enforcing adds nothing to the kernel command line"); - is(xCAT::SELinux->kcmdline_selinux('permissive', $osver), 'enforcing=0', - "$osver permissive boots with enforcing=0"); - is(xCAT::SELinux->kcmdline_selinux('disabled', $osver), 'selinux=0', - "$osver disabled boots with selinux=0"); - ok(xCAT::SELinux->netboot_supported($osver), "$osver supports SELinux on a stateless node"); -} - -foreach my $osver (@unsupported) { +foreach my $osver (@osvers) { + ok(!xCAT::SELinux->netboot_supported($osver), + "$osver does not support SELinux on a stateless node"); foreach my $mode (qw(enforcing permissive disabled)) { is(xCAT::SELinux->kcmdline_selinux($mode, $osver), 'selinux=0', - "$osver $mode boots with selinux=0, because its initramfs cannot label the root"); + "$osver $mode boots with selinux=0"); } - ok(!xCAT::SELinux->netboot_supported($osver), "$osver does not support SELinux on a stateless node"); } is(xCAT::SELinux->kcmdline_selinux(undef, 'rhels9.6'), 'selinux=0', 'an unresolved mode boots with selinux=0'); is(xCAT::SELinux->kcmdline_selinux('enforcing', undef), 'selinux=0', 'an unknown OS boots with selinux=0'); +ok(!xCAT::SELinux->netboot_supported(undef), 'an unknown OS is not supported either'); + +# kcmdline_selinux still answers for each mode, so the day a stateless node is measured +# booting enforcing only netboot_supported has to change. These three hold that contract. +{ + no warnings 'redefine'; + local *xCAT::SELinux::netboot_supported = sub { return 1; }; + is(xCAT::SELinux->kcmdline_selinux('enforcing', 'rhels10.0'), '', + 'an enforcing node adds nothing to the kernel command line'); + is(xCAT::SELinux->kcmdline_selinux('permissive', 'rhels10.0'), 'enforcing=0', + 'a permissive node boots with enforcing=0'); + is(xCAT::SELinux->kcmdline_selinux('disabled', 'rhels10.0'), 'selinux=0', + 'a disabled node boots with selinux=0'); +} + +# The product must carry no stateless relabel hook: a hook that loads the policy denies +# every later exec in the initramfs, and a hook that only labels the root leaves systemd +# unable to relabel /dev and /run after switch_root. Both were measured on AlmaLinux 10.1. +my $netboot = "$FindBin::Bin/../../xCAT-server/share/xcat/netboot"; +my (@hooks, @control); +File::Find::find({ + no_chdir => 1, + wanted => sub { + push @hooks, $File::Find::name if $File::Find::name =~ m{/xcat-selinux-relabel\.sh$}; + push @control, $File::Find::name if $File::Find::name =~ m{/xcatroot$}; + }, +}, $netboot); + +# The positive control: the same walk finds the xcatroot of every dracut generation, so +# an empty hook list means the hooks are gone, not that the walk looked nowhere. +ok(scalar(@control) >= 5, + "the walk of the netboot tree finds @{[scalar @control]} xcatroot scripts"); +is_deeply([ sort @hooks ], [], 'no dracut module ships a stateless SELinux relabel hook'); done_testing(); From 4ee82d40d8c2873c8192f6d7967f15d978147690 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:43:00 -0300 Subject: [PATCH 54/91] fix(xcat-core): a stateless node is told to run SELinux and cannot boot netboot_supported() answered 1 for rhels8 and later and for every openEuler, so mknetboot wrote no selinux= argument and a stateless node was asked to run SELinux enforcing. It does not boot. A stateless root is a cpio archive unpacked into tmpfs, and cpio carries no SELinux label, so the root starts unlabelled. Three boots of an AlmaLinux 10.1 image on an enforcing node measured both ways out of that, on cluster xcat163: - With the stock dracut selinux module, which this branch added to the module list, the policy loads at pre-pivot 50 over the unlabelled initramfs. 61 Permission denied lines follow, setfiles returns 126 and the node loops. That module ships with check() returning 255, so no image enables it by accident. - Without it, and with the relabel hook corrected, setfiles labels the root: /usr/lib/systemd/systemd reads init_exec_t. systemd then loads the policy after switch_root, cannot relabel /dev or /run, and stops with "Failed to allocate manager object. Freezing execution". The hook could not have worked as written either. It read the mode with sed piped into tail, and the initramfs has neither tail nor chroot: chroot arrived with the selinux module. The console reported "tail: command not found" twice and relabelled nothing. So netboot_supported() answers 0, mknetboot writes selinux=0 for every stateless node and nodeset says why. The code that only serves a stateless node with SELinux on is removed with it: the relabel hook and its two installers, the selinux dracut module, write_image_config, and the squashfs label machinery that stored labels nothing reads. The netboot postinstalls and the stateless xcatroot write SELINUX=disabled again, so the image says what the kernel command line does. What stays is what was measured working: a diskful node provisioned enforcing with zero xCAT denials, the kickstart templates, the policy package, and the service node mount options. Tests: selinux_netboot_kcmdline.t fails 34 of its 69 checks on the parent commit. selinux_cn_diskless_disabled_by_design in cases1 provisions a stateless node asked for enforcing and requires selinux=0 on its command line and getenforce Disabled. selinux_image_config.t and selinux_squashfs_labels.t go with the subs they tested. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- perl-xCAT/xCAT/SELinux.pm | 229 ++---------------- xCAT-server/lib/xcat/plugins/anaconda.pm | 12 +- xCAT-server/lib/xcat/plugins/packimage.pm | 22 -- .../rh/compute.rhels10.ppc64le.postinstall | 7 + .../rh/compute.rhels10.x86_64.postinstall | 7 + .../rh/compute.rhels8.ppc64le.postinstall | 7 + .../rh/compute.rhels8.x86_64.postinstall | 7 + .../rh/compute.rhels9.ppc64le.postinstall | 7 + .../rh/compute.rhels9.x86_64.postinstall | 7 + .../netboot/rh/dracut_047/install.netboot | 1 - .../rh/dracut_047/xcat-selinux-relabel.sh | 35 --- .../share/xcat/netboot/rh/dracut_047/xcatroot | 4 + .../rh/dracut_105/stateless/module-setup.sh | 3 - .../stateless/xcat-selinux-relabel.sh | 1 - .../netboot/rh/dracut_105/stateless/xcatroot | 4 + xCAT-server/share/xcat/netboot/rh/genimage | 22 -- .../rocky/compute.rocky10.riscv64.postinstall | 7 + xCAT-test/autotest/testcase/selinux/cases1 | 94 +------ xCAT-test/bats/selinux_relabel_hook.bats | 126 ---------- xCAT-test/native/netboot_profile_riscv64.t | 6 +- xCAT-test/unit/selinux_image_config.t | 51 ---- xCAT-test/unit/selinux_squashfs_labels.t | 116 --------- 22 files changed, 90 insertions(+), 685 deletions(-) delete mode 100755 xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh delete mode 120000 xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh delete mode 100644 xCAT-test/bats/selinux_relabel_hook.bats delete mode 100644 xCAT-test/unit/selinux_image_config.t delete mode 100644 xCAT-test/unit/selinux_squashfs_labels.t diff --git a/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm index 37f04dc1d5..7ed29943ba 100644 --- a/perl-xCAT/xCAT/SELinux.pm +++ b/perl-xCAT/xCAT/SELinux.pm @@ -10,9 +10,6 @@ our $CONFIG_FILE = '/etc/selinux/config'; our @MODES = qw(enforcing permissive disabled); -# packimage writes this file beside rootimg.sfs when the squashfs carries the image labels. -our $SQUASHFS_LABELS = 'rootimg.sfs.selinux'; - # The OS families that ship SELinux and get the xCAT policy. SLES 15 and Ubuntu use AppArmor. our $POLICY_OS = qr/^(?:rhel|rhes|rhels|centos|alma|rocky|ol|fedora|openeuler|sl\d)/i; @@ -232,12 +229,25 @@ sub node_modes { Descriptions: Reports whether a stateless image of this OS can boot with SELinux on. - genimage builds these images from the dracut_047 or dracut_105 module, - which carries the pre-pivot hook that labels the RAM root. + No OS can, so mknetboot writes selinux=0 for every stateless node. + + A stateless root is a cpio archive unpacked into tmpfs, and cpio + carries no SELinux label, so the root starts unlabelled. Three boots of + an AlmaLinux 10.1 image on an enforcing node measured both ways out of + that. A pre-pivot hook that loads the policy denies every later exec in + the initramfs, because the initramfs root is root_t and kernel_t cannot + execute it. A pre-pivot hook that runs setfiles and loads no policy does + label the root, and systemd then loads the policy after switch_root, + fails to relabel /dev and /run, and freezes with "Failed to allocate + manager object". + + Keep this sub as the one place that answers the question. Change it when + a stateless node is measured reaching status=booted with getenforce + reporting Enforcing. Arguments: osver - the OS of the image, for example rhels9.6 or openeuler24.03sp3 Returns: - 1 when it can, 0 otherwise. + 0. Example: my $ok = xCAT::SELinux->netboot_supported($osver); @@ -247,12 +257,6 @@ sub node_modes { sub netboot_supported { my ($class, $osver) = @_; - return 0 unless defined $osver; - return 1 if $osver =~ /^openeuler/i; - if ($osver =~ /^(?:rhels|rhel|alma|rocky|ol|centos-stream|centos)(\d+)/i) { - return $1 >= 8 ? 1 : 0; - } - return 0; } @@ -363,207 +367,6 @@ sub kickstart_mismatch { #----------------------------------------------------------------------------- -=head3 write_image_config - - Descriptions: - Sets SELINUX=enforcing in /etc/selinux/config of a rootimg. The - kernel command line that mknetboot writes then selects the mode of - each node. - Arguments: - root - the rootimg directory - Returns: - 1 when the file was written, 0 when the image has no SELinux policy. - -=cut - -#----------------------------------------------------------------------------- -sub write_image_config { - my ($class, %args) = @_; - my $path = "$args{root}$CONFIG_FILE"; - - open(my $in, '<', $path) or return 0; - my @lines = <$in>; - close($in); - - my $found = 0; - foreach my $line (@lines) { - next if $line =~ /^\s*#/; - $found = 1 if $line =~ s/^(\s*SELINUX\s*=\s*)\S*/${1}enforcing/; - } - push @lines, "SELINUX=enforcing\n" unless $found; - - open(my $out, '>', $path) or return 0; - print $out @lines; - close($out); - - return 1; -} - -#----------------------------------------------------------------------------- - -=head3 image_file_contexts - - Descriptions: - Finds the file_contexts of the policy that an image boots with. - Arguments: - root - the image root directory - Returns: - The path of the file under root, or undef when there is none. - -=cut - -#----------------------------------------------------------------------------- -sub image_file_contexts { - my ($class, $root) = @_; - - my $type = 'targeted'; - if (open(my $fh, '<', "$root$CONFIG_FILE")) { - while (my $line = <$fh>) { - $type = $1 if $line =~ /^\s*SELINUXTYPE\s*=\s*(\S+)/; - } - close($fh); - } - my $path = "$root/etc/selinux/$type/contexts/files/file_contexts"; - - return -r $path ? $path : undef; -} - -#----------------------------------------------------------------------------- - -=head3 mksquashfs_supports_pseudo_xattr - - Descriptions: - Reports whether mksquashfs takes xattr pseudo definitions, which - squashfs-tools 4.6 added. - Arguments: - version - the output of mksquashfs -version - Returns: - 1 or 0. - -=cut - -#----------------------------------------------------------------------------- -sub mksquashfs_supports_pseudo_xattr { - my ($class, $version) = @_; - - return 0 unless defined $version && $version =~ /version\s+(\d+)\.(\d+)/; - return ($1 > 4 || ($1 == 4 && $2 >= 6)) ? 1 : 0; -} - -#----------------------------------------------------------------------------- - -=head3 label_paths - - Descriptions: - Looks up the default context of node paths in the file_contexts of - an image. matchpathcon reads the file and does not ask the policy of - this host, so an image type that this host does not know is fine. - Arguments: - file_contexts - the file_contexts of the image - type - file, dir, lnk_file, chr_file, blk_file, sock_file - or fifo_file - paths - a reference to a list of absolute paths on the node - Returns: - A hash reference: path => context. A path with no context is absent. - -=cut - -#----------------------------------------------------------------------------- -sub label_paths { - my ($class, $file_contexts, $type, $paths) = @_; - - my %contexts; - my @todo = @{$paths}; - while (my @batch = splice(@todo, 0, 1000)) { - open(my $fh, '-|', 'matchpathcon', '-m', $type, '-f', $file_contexts, @batch) - or return \%contexts; - while (my $line = <$fh>) { - chomp($line); - $contexts{$1} = $2 if $line =~ /^(.*)\t(\S+)$/ && $2 ne '<>'; - } - close($fh); - } - - return \%contexts; -} - -#----------------------------------------------------------------------------- - -=head3 squashfs_label_args - - Descriptions: - Prepares mksquashfs to store the labels of the image policy. It - writes a pseudo file with one security.selinux definition for each - path, and drops the labels that the temporary copy got on this host. - Arguments: - root - the temporary copy of the rootimg that mksquashfs reads - pseudo - the pseudo file to write - version - the output of mksquashfs -version - Returns: - (\@args) with the mksquashfs arguments, or (undef, $warning) when - the image cannot be labelled. - -=cut - -#----------------------------------------------------------------------------- -sub squashfs_label_args { - my ($class, %args) = @_; - my ($root, $pseudo) = @args{qw(root pseudo)}; - - return (undef, 'squashfs-tools 4.6 or later is needed to store SELinux labels in a squashfs image') - unless $class->mksquashfs_supports_pseudo_xattr($args{version}); - my $fc = $class->image_file_contexts($root); - return (undef, 'the image has no SELinux file_contexts') unless $fc; - - my %by_type; - require File::Find; - File::Find::find({ - no_chdir => 1, - wanted => sub { - my $path = $File::Find::name; - my $rel = substr($path, length($root)); - return if $rel =~ /\n/; - $rel = '/' if $rel eq ''; - push @{ $by_type{ _file_type($path) } }, $rel; - }, - }, $root); - - open(my $out, '>', $pseudo) or return (undef, "cannot write $pseudo: $!"); - foreach my $type (sort keys %by_type) { - my $contexts = $class->label_paths($fc, $type, $by_type{$type}); - foreach my $path (@{ $by_type{$type} }) { - next unless defined $contexts->{$path}; - print $out _pseudo_name($path), " x security.selinux=$contexts->{$path}\n"; - } - } - close($out); - - return ([ '-xattrs-exclude', '^security\.selinux$', '-pf', $pseudo ]); -} - -sub _file_type { - my ($path) = @_; - - return 'lnk_file' if -l $path; - return 'dir' if -d _; - return 'chr_file' if -c _; - return 'blk_file' if -b _; - return 'sock_file' if -S _; - return 'fifo_file' if -p _; - return 'file'; -} - -# mksquashfs reads a quoted pseudo name with backslash escapes, relative to the image root. -sub _pseudo_name { - my ($path) = @_; - - return '"/"' if $path eq '/'; - (my $name = substr($path, 1)) =~ s/(["\\])/\\$1/g; - return "\"$name\""; -} - -#----------------------------------------------------------------------------- - =head3 nfs_mount_options Descriptions: diff --git a/xCAT-server/lib/xcat/plugins/anaconda.pm b/xCAT-server/lib/xcat/plugins/anaconda.pm index 4b20bd6a04..1cd75cc5a0 100644 --- a/xCAT-server/lib/xcat/plugins/anaconda.pm +++ b/xCAT-server/lib/xcat/plugins/anaconda.pm @@ -957,15 +957,9 @@ sub mknetboot } my $selinux = $selinux_modes->{$node} || 'disabled'; - if ($selinux ne 'disabled') { - if (!xCAT::SELinux->netboot_supported($osver)) { - $selinux_why{$node} = "the $osver stateless image cannot label its root"; - $selinux = 'disabled'; - } elsif (defined($compressedrootimg) and $compressedrootimg eq 'rootimg.sfs' - and !-e "$rootimgdir/$xCAT::SELinux::SQUASHFS_LABELS") { - $selinux_why{$node} = "rootimg.sfs has no SELinux labels, run packimage with squashfs-tools 4.6 or later"; - $selinux = 'disabled'; - } + if ($selinux ne 'disabled' and !xCAT::SELinux->netboot_supported($osver)) { + $selinux_why{$node} = "a stateless $osver node cannot label its RAM root"; + $selinux = 'disabled'; } if ($selinux_why{$node}) { $callback->({ warning => ["$node: SELinux is disabled: $selinux_why{$node}"] }); diff --git a/xCAT-server/lib/xcat/plugins/packimage.pm b/xCAT-server/lib/xcat/plugins/packimage.pm index d89e951713..54293761b5 100644 --- a/xCAT-server/lib/xcat/plugins/packimage.pm +++ b/xCAT-server/lib/xcat/plugins/packimage.pm @@ -37,7 +37,6 @@ use File::Path; use xCAT::Utils; use xCAT::TableUtils; use xCAT::SvrUtils; -use xCAT::SELinux; use xCAT::PasswordUtils; use Digest::MD5 qw(md5_hex); @@ -643,7 +642,6 @@ sub process_request { } $oldmask = umask 0077; } elsif ($method =~ /squashfs/) { - unlink("$destdir/$xCAT::SELinux::SQUASHFS_LABELS"); $temppath = eval { mkdtemp("/tmp/packimage.$$.XXXXXXXX") } or return $native_failure->("Cannot create a staging directory: $@"); chmod 0755, $temppath; @@ -674,26 +672,9 @@ sub process_request { } return $native_failure->("mksquashfs not found, squashfs-tools rpm should be installed on the management node"); } - # The temporary copy has the labels of this host. Store the labels of the image policy. - my $selinux_pseudo; - if ($osver =~ $xCAT::SELinux::POLICY_OS) { - my ($label_args, $label_warning) = xCAT::SELinux->squashfs_label_args( - root => $temppath, - pseudo => "$temppath.selinux", - version => scalar(`mksquashfs -version 2>&1`), - ); - if ($label_args) { - $selinux_pseudo = "$temppath.selinux"; - $flags .= join('', map { " '$_'" } @{$label_args}); - } else { - $callback->({ warning => ["$label_warning. Nodes that boot the squashfs image get SELinux disabled."] }); - } - } - my $mksquashfs_command = "mksquashfs $temppath $archive_output $flags"; xCAT::Utils->runcmd($mksquashfs_command, 0, 1); my $rc = $::RUNCMD_RC; - unlink($selinux_pseudo) if $selinux_pseudo; if ($rc) { return $native_failure->("Command \"$mksquashfs_command\" failed"); } @@ -701,9 +682,6 @@ sub process_request { if ($rc) { return $native_failure->("Failed to clean up temp space"); } - if ($selinux_pseudo and open(my $marker, '>', "$destdir/$xCAT::SELinux::SQUASHFS_LABELS")) { - close($marker); - } } if (my $error = xCAT::SvrUtils->write_rootimg_checksum("$stage/$image_file")) { diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall index e29e51aeec..dd2576c8f7 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall @@ -32,6 +32,13 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall index 8f99e37345..2ad53bb406 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall @@ -32,6 +32,13 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall index e29e51aeec..dd2576c8f7 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall @@ -32,6 +32,13 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall index 8f99e37345..2ad53bb406 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall @@ -32,6 +32,13 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall index e29e51aeec..dd2576c8f7 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall @@ -32,6 +32,13 @@ END #cons:12345:respawn:/sbin/smart_agetty -L 38400 console echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall index 8f99e37345..2ad53bb406 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall @@ -32,6 +32,13 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot b/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot index d9160f1cc0..0be90b3ec5 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_047/install.netboot @@ -8,7 +8,6 @@ dracut_install ethtool inst "$moddir/xcat-updateflag" "/tmp/updateflag" inst "$moddir/xcatroot" "/sbin/xcatroot" inst_hook cmdline 10 "$moddir/xcat-cmdline.sh" -inst_hook pre-pivot 60 "$moddir/xcat-selinux-relabel.sh" for file in /etc/udev/rules.d/*;do grep -qi xcat $file && inst $file $file done diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh deleted file mode 100755 index d5cbd581f6..0000000000 --- a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Label the stateless root with the policy of the image. dracut 98selinux loads that -# policy at pre-pivot 50, and systemd cannot start from an unlabelled tmpfs root. - -xcat_selinux_relabel() -{ - getarg selinux=0 >/dev/null && return 0 - - # A squashfs root carries its labels, and a relabel would copy every file to the overlay. - [ -e "${xcat_sfs_image:-/rootimg.sfs}" ] && return 0 - - local config="$NEWROOT/etc/selinux/config" mode type fc setfiles rc - [ -r "$config" ] || return 0 - mode=$(sed -n 's/^[[:space:]]*SELINUX[[:space:]]*=[[:space:]]*//p' "$config" | tail -n 1) - [ "$mode" = disabled ] && return 0 - type=$(sed -n 's/^[[:space:]]*SELINUXTYPE[[:space:]]*=[[:space:]]*//p' "$config" | tail -n 1) - fc="/etc/selinux/${type:-targeted}/contexts/files/file_contexts" - if [ ! -r "$NEWROOT$fc" ]; then - warn "xCAT: $fc is not in the image, the root is not labelled" - return 0 - fi - - setfiles=/usr/sbin/setfiles - [ -x "$NEWROOT$setfiles" ] || setfiles=/sbin/setfiles - - mount -t proc proc "$NEWROOT/proc" - mount --bind /sys "$NEWROOT/sys" - chroot "$NEWROOT" "$setfiles" -F -e /proc -e /sys -e /dev "$fc" / - rc=$? - umount "$NEWROOT/sys" - umount "$NEWROOT/proc" - [ "$rc" -eq 0 ] || warn "xCAT: setfiles returned $rc" -} - -xcat_selinux_relabel diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot index 0e6b683039..99b7b23317 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_047/xcatroot @@ -412,6 +412,10 @@ fi [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "Saving $NEWROOT/etc/resolv.conf" cp /etc/resolv.conf "$NEWROOT/etc/" +if [ -d "$NEWROOT/etc/sysconfig" -a ! -e "$NEWROOT/etc/sysconfig/selinux" ]; then + [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "disable selinux ..." + echo "SELINUX=disabled" >> "$NEWROOT/etc/sysconfig/selinux" +fi logger $SYSLOGHOST -t $log_label -p local4.info "Exiting xcatroot..." # inject new exit_if_exists diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh index 28bc073a65..b150bd42c4 100644 --- a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh +++ b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/module-setup.sh @@ -28,9 +28,6 @@ install() { # cmdline hook inst_hook cmdline 10 "$moddir/xcat-cmdline.sh" - # After 98selinux loads the policy of the image at pre-pivot 50. - inst_hook pre-pivot 60 "$moddir/xcat-selinux-relabel.sh" - # udev rules with "xcat" for file in /etc/udev/rules.d/*; do if grep -qi xcat "$file"; then diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh deleted file mode 120000 index 51972524cd..0000000000 --- a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh +++ /dev/null @@ -1 +0,0 @@ -../../dracut_047/xcat-selinux-relabel.sh \ No newline at end of file diff --git a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot index 0e6b683039..99b7b23317 100755 --- a/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot +++ b/xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcatroot @@ -412,6 +412,10 @@ fi [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "Saving $NEWROOT/etc/resolv.conf" cp /etc/resolv.conf "$NEWROOT/etc/" +if [ -d "$NEWROOT/etc/sysconfig" -a ! -e "$NEWROOT/etc/sysconfig/selinux" ]; then + [ "$xcatdebugmode" > "0" ] && logger -t $log_label -p local4.debug "disable selinux ..." + echo "SELINUX=disabled" >> "$NEWROOT/etc/sysconfig/selinux" +fi logger $SYSLOGHOST -t $log_label -p local4.info "Exiting xcatroot..." # inject new exit_if_exists diff --git a/xCAT-server/share/xcat/netboot/rh/genimage b/xCAT-server/share/xcat/netboot/rh/genimage index 231ffcb8ca..e6c2543ae3 100755 --- a/xCAT-server/share/xcat/netboot/rh/genimage +++ b/xCAT-server/share/xcat/netboot/rh/genimage @@ -20,7 +20,6 @@ use FindBin; use lib "$FindBin::Bin/../imgutils"; use imgutils; use xCAT::Utils; -use xCAT::SELinux; use Digest::MD5 qw(md5_hex); #use strict; @@ -823,9 +822,6 @@ xdie("Error: failed to generate the initial ramdisk: native image has no dracut imgutils::disable_vendor_repositories($rootimg_dir); -# The kernel command line that mknetboot writes selects the SELinux mode of each node. -xCAT::SELinux->write_image_config(root => $rootimg_dir); - #-- run postinstall script unless ($imagename) { $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); @@ -1096,7 +1092,6 @@ sub mkinitrd_dracut { 'installkernel', 'module-setup.sh', 'xcat-cmdline.sh', - 'xcat-selinux-relabel.sh', 'xcatroot', 'xcat-updateflag', ], @@ -1172,12 +1167,6 @@ sub mkinitrd_dracut { } } - # 98selinux loads the policy of the image before the xCAT relabel hook runs. - my @selinux_module = glob($dracutmoduledir . "[0-9]*selinux"); - if (-r "$dracutmpath/xcat-selinux-relabel.sh" and @selinux_module) { - $dracutmodulelist .= " selinux"; - } - # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); print $DRACUTCONF qq{dracutmodules+=" $dracutmodulelist "\n}; @@ -1256,11 +1245,6 @@ sub mkinitrd_dracut { $perm = (stat("$fullpath/$dracutdir/installkernel"))[2]; chmod($perm & 07777, "$dracutmpath/installkernel"); - if (-r "$fullpath/$dracutdir/xcat-selinux-relabel.sh") { - cp("$fullpath/$dracutdir/xcat-selinux-relabel.sh", "$dracutmpath/"); - chmod(0755, "$dracutmpath/xcat-selinux-relabel.sh"); - } - my $dracutmodulelist = "xcat nfs base network kernel-modules syslog"; if (defined(imgutils::openeuler_release_version($osver)) ? scalar(glob($dracutmoduledir . '[0-9]*network-manager')) @@ -1275,12 +1259,6 @@ sub mkinitrd_dracut { } } - # 98selinux loads the policy of the image before the xCAT relabel hook runs. - my @selinux_module = glob($dracutmoduledir . "[0-9]*selinux"); - if (-r "$dracutmpath/xcat-selinux-relabel.sh" and @selinux_module) { - $dracutmodulelist .= " selinux"; - } - # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); print $DRACUTCONF qq{dracutmodules+=" $dracutmodulelist "\n}; diff --git a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall index 0cc5674cdc..015cfec0f9 100755 --- a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall +++ b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall @@ -32,6 +32,13 @@ END #echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab +#-- Disable SELinux in the rootimg +#-- Redhat 7.3 will install selinux-policy and selinux is enabled by default +#-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" +if [ -f "$installroot/etc/selinux/config" ] +then + sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config +fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys FIREWALLD="$installroot/etc/systemd/system/multi-user.target.wants/firewalld.service" diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index 932188687a..86d38bca0a 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -41,110 +41,36 @@ check:rc==0 cmd:rm -f /tmp/selinux_cn_diskful.start end -start:selinux_cn_diskless_enforcing -description:on an enforcing management node, a stateless (cpio) compute node with noderes.selinux=enforcing labels its RAM root at boot and runs enforcing with no denial +start:selinux_cn_diskless_disabled_by_design +description:a stateless compute node asked for SELinux enforcing still boots with selinux=0, because a stateless root cannot be labelled, and nodeset says so label:selinux,provision os:Linux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_diskless.start' -check:rc==0 cmd:chdef -t node -o $$CN selinux=enforcing check:rc==0 cmd:genimage __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute check:rc==0 cmd:packimage -m cpio __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute check:rc==0 +cmd:nodeset $$CN osimage=__GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute +check:rc==0 +check:output=~SELinux is disabled +check:output=~cannot label its RAM root +cmd:sh -c 'grep -rhl "selinux=0" /tftpboot/xcat/xnba/nodes/$$CN /tftpboot/pxelinux.cfg/$$CN /tftpboot/petitboot/$$CN 2>/dev/null' +check:rc==0 cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute check:rc==0 check:output=~Provision node\(s\)\: $$CN -cmd:xdsh $$CN mount -check:rc==0 -check:output=~on / type tmpfs -cmd:xdsh $$CN getenforce -check:rc==0 -check:output=~Enforcing cmd:xdsh $$CN cat /proc/cmdline check:rc==0 -check:output!~selinux=0 -cmd:xdsh $$CN "ls -dZ / /usr/bin/bash /root/.ssh /etc/ssh/sshd_config /opt/xcat /xcatpost" -check:rc==0 -check:output=~bin_t -check:output=~ssh_home_t -check:output!~tmpfs_t -check:output!~default_t -check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -Rnv /xcatpost /opt/xcat /root /etc/ssh /usr/sbin" -check:rc==0 -check:output!~Would relabel -cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ -check:rc==0 -cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" -check:rc==0 -check:output=~XCAT_AVC=0 -cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" -check:rc==0 -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_diskless.start)"' -check:rc==0 -check:output=~XCAT_AVC=0 -cmd:chdef -t node -o $$CN selinux= -check:rc==0 -cmd:rm -f /tmp/selinux_cn_diskless.start -end - -start:selinux_cn_diskless_squashfs_enforcing -description:on an enforcing management node with squashfs-tools 4.6 or later, a stateless squashfs compute node with noderes.selinux=enforcing boots from labels stored in the image and runs enforcing with no denial -label:selinux,provision -os:Linux -cmd:getenforce -check:rc==0 -check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_squashfs.start' -check:rc==0 -cmd:chdef -t node -o $$CN selinux=enforcing -check:rc==0 -cmd:sh -c 'rpm -q squashfs-tools || dnf install -y squashfs-tools' -check:rc==0 -cmd:genimage __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute -check:rc==0 -cmd:packimage -m squashfs __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute -check:rc==0 -check:output=~archive method:squashfs -check:output!~Nodes that boot -cmd:sh -c 'ls "$(lsdef -t osimage -o __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute -i rootimgdir -c | cut -d= -f2)/rootimg.sfs.selinux"' -check:rc==0 -cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-netboot-compute -check:rc==0 -check:output=~Provision node\(s\)\: $$CN -cmd:xdsh $$CN mount -check:rc==0 -check:output=~on / type overlay +check:output=~selinux=0 cmd:xdsh $$CN getenforce check:rc==0 -check:output=~Enforcing -cmd:xdsh $$CN "ls -dZ / /usr/bin/bash /etc/ssh/sshd_config /opt/xcat /xcatpost" -check:rc==0 -check:output=~bin_t -check:output!~tmp_t -check:output!~default_t -check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -Rnv /usr/bin /usr/sbin /etc/ssh /xcatpost /opt/xcat" -check:rc==0 -check:output!~Would relabel -cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ -check:rc==0 -cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" -check:rc==0 -check:output=~XCAT_AVC=0 -cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" -check:rc==0 -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_squashfs.start)"' -check:rc==0 -check:output=~XCAT_AVC=0 +check:output=~Disabled cmd:chdef -t node -o $$CN selinux= check:rc==0 -cmd:rm -f /tmp/selinux_cn_squashfs.start end start:selinux_cn_diskless_site_disabled diff --git a/xCAT-test/bats/selinux_relabel_hook.bats b/xCAT-test/bats/selinux_relabel_hook.bats deleted file mode 100644 index 3b794b9bac..0000000000 --- a/xCAT-test/bats/selinux_relabel_hook.bats +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env bats -# -# Source the pre-pivot hook that labels a stateless root, as dracut does. getarg, warn, -# mount, umount and chroot are dracut and initramfs commands, so shadow them with functions. - -load 'helpers/shell_source' - -HOOKS=( - 'xCAT-server/share/xcat/netboot/rh/dracut_047/xcat-selinux-relabel.sh' - 'xCAT-server/share/xcat/netboot/rh/dracut_105/stateless/xcat-selinux-relabel.sh' -) - -setup() -{ - NEWROOT="${BATS_TEST_TMPDIR}/sysroot" - CALLS="${BATS_TEST_TMPDIR}/calls" - CMDLINE='' - xcat_sfs_image="${BATS_TEST_TMPDIR}/rootimg.sfs" - mkdir -p "$NEWROOT/etc/selinux/targeted/contexts/files" "$NEWROOT/usr/sbin" "$NEWROOT/proc" "$NEWROOT/sys" - : >"$NEWROOT/etc/selinux/targeted/contexts/files/file_contexts" - : >"$NEWROOT/usr/sbin/setfiles" - chmod 0755 "$NEWROOT/usr/sbin/setfiles" - write_config enforcing targeted - : >"$CALLS" -} - -write_config() -{ - printf 'SELINUX=%s\nSELINUXTYPE=%s\n' "$1" "$2" >"$NEWROOT/etc/selinux/config" -} - -getarg() -{ - local arg - for arg in $CMDLINE; do - [ "$arg" = "$1" ] && return 0 - done - return 1 -} - -warn() { echo "warn: $*" >>"$CALLS"; } -mount() { :; } -umount() { :; } -chroot() { echo "chroot $*" >>"$CALLS"; } - -source_hook() -{ - # dracut sources every hook into its own shell. - . "$(repo_path "$1")" -} - -@test "selinux=0 on the kernel command line runs no setfiles" { - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - CMDLINE='root=1 selinux=0 quiet' - source_hook "$hook" - run cat "$CALLS" - [ -z "$output" ] - done -} - -@test "an enforcing node runs setfiles once with the file_contexts of the image" { - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - CMDLINE='root=1 quiet' - source_hook "$hook" - run grep -c '^chroot ' "$CALLS" - [ "$output" = 1 ] - run cat "$CALLS" - [ "$output" = "chroot $NEWROOT /usr/sbin/setfiles -F -e /proc -e /sys -e /dev /etc/selinux/targeted/contexts/files/file_contexts /" ] - done -} - -@test "a permissive node also runs setfiles" { - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - CMDLINE='root=1 enforcing=0' - source_hook "$hook" - run grep -c '^chroot .*/usr/sbin/setfiles' "$CALLS" - [ "$output" = 1 ] - done -} - -@test "the file_contexts follows SELINUXTYPE of the image" { - mkdir -p "$NEWROOT/etc/selinux/mls/contexts/files" - : >"$NEWROOT/etc/selinux/mls/contexts/files/file_contexts" - write_config enforcing mls - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - source_hook "$hook" - run cat "$CALLS" - [[ "$output" == *" /etc/selinux/mls/contexts/files/file_contexts /" ]] - done -} - -@test "a squashfs root keeps the labels of the image" { - : >"$xcat_sfs_image" - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - source_hook "$hook" - run cat "$CALLS" - [ -z "$output" ] - done -} - -@test "an image configured with SELINUX=disabled runs no setfiles" { - write_config disabled targeted - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - source_hook "$hook" - run grep -c '^chroot ' "$CALLS" - [ "$output" = 0 ] - done -} - -@test "an image without file_contexts warns and runs no setfiles" { - rm -f "$NEWROOT/etc/selinux/targeted/contexts/files/file_contexts" - for hook in "${HOOKS[@]}"; do - : >"$CALLS" - source_hook "$hook" - run grep -c '^chroot ' "$CALLS" - [ "$output" = 0 ] - run grep -c '^warn: .*file_contexts' "$CALLS" - [ "$output" = 1 ] - done -} diff --git a/xCAT-test/native/netboot_profile_riscv64.t b/xCAT-test/native/netboot_profile_riscv64.t index 20f4e9152f..be5109d4c9 100644 --- a/xCAT-test/native/netboot_profile_riscv64.t +++ b/xCAT-test/native/netboot_profile_riscv64.t @@ -88,8 +88,10 @@ for my $family (@families) { if ($mode eq 'absent') { ok(!-e "$image/etc/selinux/config", "pass $pass leaves absent SELinux configuration absent"); } else { - is(read_text("$image/etc/selinux/config"), "SELINUX=$mode\nSELINUXTYPE=targeted\n", - "pass $pass keeps the SELinux mode the image was built with"); + local $TODO = 'The existing postinstall duplicates SELINUX= for permissive mode' + if $mode eq 'permissive'; + is(read_text("$image/etc/selinux/config"), "SELINUX=disabled\nSELINUXTYPE=targeted\n", + "pass $pass disables SELinux without changing the policy type"); } my @mounts = map { [split /\s+/] } grep { /\S/ } split /\n/, read_text("$image/etc/fstab"); is_deeply(\@mounts, [ diff --git a/xCAT-test/unit/selinux_image_config.t b/xCAT-test/unit/selinux_image_config.t deleted file mode 100644 index ecd83b5c00..0000000000 --- a/xCAT-test/unit/selinux_image_config.t +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env perl -use strict; -use warnings; - -# Keep modules out of an installed /opt/xcat, so the checkout is what loads. -BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } - -use FindBin; -use lib "$FindBin::Bin/../../perl-xCAT"; - -use File::Path qw(make_path); -use File::Slurper qw(read_text write_text); -use File::Temp qw(tempdir); -use Test::More; - -use xCAT::SELinux; - -like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, - 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); - -my $root = tempdir(CLEANUP => 1); -make_path("$root/etc/selinux"); -my $config = "$root/etc/selinux/config"; - -# The config an old genimage postinstall left behind. -write_text($config, "# comment SELINUX=keep\nSELINUX=disabled\nSELINUXTYPE=targeted\n"); -ok(xCAT::SELinux->write_image_config(root => $root), 'write_image_config changes a disabled image'); -is(read_text($config), "# comment SELINUX=keep\nSELINUX=enforcing\nSELINUXTYPE=targeted\n", - 'the image boots enforcing unless the kernel command line says otherwise'); -is(xCAT::SELinux->config_mode(root => $root), 'enforcing', 'config_mode of the image reads enforcing'); - -write_text($config, "SELINUX=permissive\nSELINUXTYPE=mls\n"); -xCAT::SELinux->write_image_config(root => $root); -is(read_text($config), "SELINUX=enforcing\nSELINUXTYPE=mls\n", 'a permissive image becomes enforcing; the policy type stays'); - -write_text($config, "SELINUXTYPE=targeted\n"); -xCAT::SELinux->write_image_config(root => $root); -is(read_text($config), "SELINUXTYPE=targeted\nSELINUX=enforcing\n", 'a config with no SELINUX line gets one'); - -my $bare = tempdir(CLEANUP => 1); -ok(!xCAT::SELinux->write_image_config(root => $bare), 'an image without an SELinux policy is left alone'); -ok(!-e "$bare/etc/selinux/config", 'no config is created in an image without an SELinux policy'); - -is(xCAT::SELinux->image_file_contexts($bare), undef, 'an image without a policy has no file_contexts'); -make_path("$root/etc/selinux/mls/contexts/files"); -write_text($config, "SELINUX=enforcing\nSELINUXTYPE=mls\n"); -write_text("$root/etc/selinux/mls/contexts/files/file_contexts", "/.* system_u:object_r:default_t:s0\n"); -is(xCAT::SELinux->image_file_contexts($root), "$root/etc/selinux/mls/contexts/files/file_contexts", - 'image_file_contexts follows SELINUXTYPE of the image'); - -done_testing(); diff --git a/xCAT-test/unit/selinux_squashfs_labels.t b/xCAT-test/unit/selinux_squashfs_labels.t deleted file mode 100644 index cbb4a573ed..0000000000 --- a/xCAT-test/unit/selinux_squashfs_labels.t +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env perl -use strict; -use warnings; - -# Keep modules out of an installed /opt/xcat, so the checkout is what loads. -BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } - -use FindBin; -use lib "$FindBin::Bin/../../perl-xCAT"; - -use File::Path qw(make_path); -use File::Slurper qw(read_lines write_text); -use File::Temp qw(tempdir); -use Test::More; - -use xCAT::SELinux; - -like($INC{'xCAT/SELinux.pm'}, qr/\Q$FindBin::Bin\E/, - 'xCAT::SELinux comes from this checkout, not from /opt/xcat'); - -ok(xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.6.1 (2023/03/25)'), - 'squashfs-tools 4.6.1 (EL10, openEuler 24.03) takes pseudo xattr definitions'); -ok(xCAT::SELinux->mksquashfs_supports_pseudo_xattr("mksquashfs version 4.10 (2030/01/01)\ncopyright"), - 'a later minor version takes them too'); -ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.5 (2021/07/22)'), - 'squashfs-tools 4.5 (openEuler 22.03) does not'); -ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.4-git.1 (2020/02/17)'), - 'squashfs-tools 4.4 (EL9) does not'); -ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr('mksquashfs version 4.3-git (2014/06/09)'), - 'squashfs-tools 4.3 (EL8) does not'); -ok(!xCAT::SELinux->mksquashfs_supports_pseudo_xattr(undef), 'no version output means no support'); - -# A temporary copy of a rootimg, as packimage makes it before mksquashfs. -my $tmp = tempdir(CLEANUP => 1); -my $root = "$tmp/copy"; -make_path("$root/usr/bin", "$root/etc/selinux/targeted/contexts/files", "$root/a dir"); -my $fc = "$root/etc/selinux/targeted/contexts/files/file_contexts"; -write_text("$root/etc/selinux/config", "SELINUX=enforcing\nSELINUXTYPE=targeted\n"); -write_text($fc, "/.* system_u:object_r:default_t:s0\n"); -write_text("$root/usr/bin/ls", "ELF\n"); -write_text("$root/a dir/say \"hi\"\\now", "x\n"); -write_text("$root/etc/bad\nname", "x\n"); -symlink('ls', "$root/usr/bin/dir") or die "symlink: $!"; - -# label_paths runs matchpathcon against the image policy. Answer by file type instead. -my @lookups; -my %context = (dir => 'root_t', file => 'bin_t', lnk_file => 'lnk_t'); -sub run_args { - my (%args) = @_; - @lookups = (); - no warnings 'redefine'; - local *xCAT::SELinux::label_paths = sub { - my ($class, $file_contexts, $type, $paths) = @_; - push @lookups, [ $file_contexts, $type, [ sort @{$paths} ] ]; - my %answer; - foreach my $path (@{$paths}) { - next if $path eq '/etc/selinux/config'; - $answer{$path} = "system_u:object_r:$context{$type}:s0"; - } - return \%answer; - }; - return xCAT::SELinux->squashfs_label_args(%args); -} - -my $pseudo = "$tmp/pseudo"; -my ($args, $warning) = run_args(root => $root, pseudo => $pseudo, - version => 'mksquashfs version 4.6.1 (2023/03/25)'); -is($warning, undef, 'squashfs-tools 4.6.1 gives no warning'); -is_deeply($args, [ '-xattrs-exclude', '^security\.selinux$', '-pf', $pseudo ], - 'mksquashfs drops the labels of the copy and takes the labels of the image from the pseudo file'); - -is_deeply([ sort map { $_->[1] } @lookups ], [qw(dir file lnk_file)], 'one lookup for each file type'); -is_deeply([ map { $_->[0] } @lookups ], [ ($fc) x 3 ], 'every lookup uses the file_contexts of the image'); -my %paths = map { $_->[1] => $_->[2] } @lookups; -is_deeply($paths{dir}, [ '/', '/a dir', '/etc', '/etc/selinux', '/etc/selinux/targeted', - '/etc/selinux/targeted/contexts', '/etc/selinux/targeted/contexts/files', '/usr', '/usr/bin' ], - 'directories are looked up at their path on the node'); -is_deeply($paths{file}, [ "/a dir/say \"hi\"\\now", '/etc/selinux/config', - '/etc/selinux/targeted/contexts/files/file_contexts', '/usr/bin/ls' ], - 'files are looked up, and a name with a newline is skipped'); -is_deeply($paths{lnk_file}, ['/usr/bin/dir'], 'symbolic links are looked up as lnk_file'); - -my @lines = sort(read_lines($pseudo)); -is_deeply(\@lines, [ sort( - '"/" x security.selinux=system_u:object_r:root_t:s0', - '"a dir" x security.selinux=system_u:object_r:root_t:s0', - '"a dir/say \"hi\"\\\\now" x security.selinux=system_u:object_r:bin_t:s0', - '"etc" x security.selinux=system_u:object_r:root_t:s0', - '"etc/selinux" x security.selinux=system_u:object_r:root_t:s0', - '"etc/selinux/targeted" x security.selinux=system_u:object_r:root_t:s0', - '"etc/selinux/targeted/contexts" x security.selinux=system_u:object_r:root_t:s0', - '"etc/selinux/targeted/contexts/files" x security.selinux=system_u:object_r:root_t:s0', - '"etc/selinux/targeted/contexts/files/file_contexts" x security.selinux=system_u:object_r:bin_t:s0', - '"usr" x security.selinux=system_u:object_r:root_t:s0', - '"usr/bin" x security.selinux=system_u:object_r:root_t:s0', - '"usr/bin/dir" x security.selinux=system_u:object_r:lnk_t:s0', - '"usr/bin/ls" x security.selinux=system_u:object_r:bin_t:s0', - ) ], - 'the pseudo file quotes each name and skips a path the policy gives no context'); - -unlink($pseudo); -($args, $warning) = run_args(root => $root, pseudo => $pseudo, - version => 'mksquashfs version 4.4-git.1 (2020/02/17)'); -is($args, undef, 'squashfs-tools 4.4 gives no label arguments'); -like($warning, qr/4\.6/, 'the warning names the squashfs-tools version that labels the image'); -is(scalar(@lookups), 0, 'squashfs-tools 4.4 looks up no label'); -ok(!-e $pseudo, 'squashfs-tools 4.4 writes no pseudo file'); - -my $bare = "$tmp/bare"; -make_path("$bare/usr"); -($args, $warning) = run_args(root => $bare, pseudo => $pseudo, - version => 'mksquashfs version 4.6.1 (2023/03/25)'); -is($args, undef, 'an image without an SELinux policy gives no label arguments'); -like($warning, qr/file_contexts/, 'the warning says the image has no file_contexts'); - -done_testing(); From 76e57d4a08c37f7317c51a74418a216bbd64b069 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:43:27 -0300 Subject: [PATCH 55/91] docs(xcat-core): say what SELinux an operator gets The branch changed what a cluster runs and added no documentation, while the quick start guide still told the operator to write SELINUX=disabled on the management node before installing xCAT. docs/source/advanced/security/selinux.rst says which machine gets which mode, why a stateless node runs with SELinux disabled, how to set noderes.selinux and site.selinux, and that xcatd, in.tftpd, kea-dhcp4 and goconserver run in unconfined_service_t, so the work is about running with SELinux enforcing and not about confining xCAT. It also covers the upgrade: recordselinuxdefault runs on INITIALINSTALL only, so an upgraded cluster has no site.selinux value, every node keeps being provisioned with SELinux off, and reprovisioning is what gives a node the new mode. The quick start step now says SELinux can stay enabled and links there. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/security/index.rst | 1 + docs/source/advanced/security/selinux.rst | 113 ++++++++++++++++++ .../source/guides/get-started/quick_start.rst | 7 +- 3 files changed, 117 insertions(+), 4 deletions(-) create mode 100644 docs/source/advanced/security/selinux.rst diff --git a/docs/source/advanced/security/index.rst b/docs/source/advanced/security/index.rst index 6fa0c2f57d..dd3705dddd 100644 --- a/docs/source/advanced/security/index.rst +++ b/docs/source/advanced/security/index.rst @@ -7,6 +7,7 @@ The security of a system covers a wide range of elements, from the security of s :maxdepth: 2 fips.rst + selinux.rst ssl_config.rst security.rst apache_hardening.rst diff --git a/docs/source/advanced/security/selinux.rst b/docs/source/advanced/security/selinux.rst new file mode 100644 index 0000000000..1cc97abf19 --- /dev/null +++ b/docs/source/advanced/security/selinux.rst @@ -0,0 +1,113 @@ +SELinux +======= + +xCAT runs with SELinux enforcing on the management node and on a diskful compute or +service node. A stateless node runs with SELinux disabled. + +xCAT never changes the SELinux mode. ``xcatconfig`` reads the mode and reports it, and +``/etc/selinux/config`` belongs to the site. + +What the cluster gets +--------------------- + +================= ========================= ========================================== +Machine Provisioning method SELinux +================= ========================= ========================================== +Management node any the mode the site set. Enforcing works +Compute node diskful (kickstart) the mode ``noderes.selinux`` resolves +Service node diskful (kickstart) the mode ``noderes.selinux`` resolves +Compute node stateless (netboot) disabled. ``nodeset`` says why +Compute node statelite disabled +================= ========================= ========================================== + +This covers the OS families that ship an SELinux policy: RHEL and its rebuilds, Fedora +and openEuler. Ubuntu and SLES use AppArmor, and a node of those families resolves to +disabled. + +Why a stateless node runs with SELinux disabled +----------------------------------------------- + +A stateless root is a cpio archive unpacked into tmpfs. cpio carries no SELinux label, so +the root starts unlabelled, and an unlabelled root cannot be made to boot: + +* A dracut hook that loads the policy before ``switch_root`` denies every later program in + the initramfs. The initramfs root is ``root_t``, and ``kernel_t`` cannot execute it. The + stock dracut ``98selinux`` module does this, which is why its ``check()`` returns 255 and + no xCAT image includes it. +* A dracut hook that labels the root with ``setfiles`` and loads no policy does label it, + and ``systemd`` then loads the policy after ``switch_root``, fails to relabel ``/dev`` + and ``/run``, and stops with ``Failed to allocate manager object``. + +So ``mknetboot`` writes ``selinux=0`` for every stateless node, whatever +``noderes.selinux`` and ``site.selinux`` say, and ``nodeset`` prints the reason:: + + cn1: SELinux is disabled: a stateless rhels10.0 node cannot label its RAM root + +``xCAT::SELinux->netboot_supported`` is the one place that answers this question. + +xCAT itself is not confined +--------------------------- + +``xcatd``, ``in.tftpd``, ``kea-dhcp4`` and ``goconserver`` run in +``unconfined_service_t``. The ``xCAT-selinux`` package defines no type and confines +nothing. It carries the rules that let the CONFINED services of the OS reach the files +xCAT owns, for example ``httpd`` reading ``/tftpboot``. + +So SELinux on an xCAT cluster constrains the OS services, not xCAT. Running xCAT with +SELinux enforcing is the goal; confining xCAT is not part of it. + +Setting the mode of a node +-------------------------- + +``noderes.selinux`` on the node, then the ``noderes.selinux`` of its groups, then +``site.selinux``, then disabled. A node row can turn SELinux on when ``site.selinux`` is +disabled:: + + chdef -t site selinux=enforcing + chdef cn1 selinux=permissive + lsdef cn1 -i selinux + +The value is ``enforcing``, ``permissive`` or ``disabled``. The first install of xCAT +records ``site.selinux`` from the mode of the management node, through +``recordselinuxdefault``. + +An existing cluster +------------------- + +``recordselinuxdefault`` runs on INITIALINSTALL only, so an upgrade does not write +``site.selinux``. An upgraded cluster has no value, which resolves to disabled, and every +node keeps being provisioned with SELinux off. Set the value to change that:: + + chdef -t site selinux=enforcing + +A cluster that xCAT provisioned before this release has SELinux disabled on its nodes, and +``/etc/selinux/config`` on those nodes says ``SELINUX=disabled``. Reprovisioning a node is +what gives it the new mode; ``chdef`` alone does not reach a running node. + +On the management node, xCAT never disabled SELinux, but the installation guides used to +ask the admin to. Turn it back on with the usual OS procedure, which relabels the +filesystem and reboots:: + + sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config + touch /.autorelabel + reboot + +Install ``xCAT-selinux`` before that reboot, so ``/install`` and ``/tftpboot`` are +relabelled with the xCAT rules in place. + +Checking a node +--------------- + +``xcatprobe xcatmn`` reports the mode, whether the ``xcat`` policy module is loaded, and +the labels of ``installdir`` and ``tftpdir``. + +Read the denials with ``ausearch --input-logs``. Without ``--input-logs``, ``ausearch`` +reads the journal, which carries no audit records on EL10, and answers that there are +none:: + + ausearch --input-logs -m AVC,USER_AVC -ts today + +A cluster denies things xCAT has nothing to do with: on an idle enforcing management node +``httpd`` asks for ``net_admin`` on itself every ten seconds, and the base policy has no +``dontaudit`` rule for it. ``selinux_avc_check.sh`` in the xCAT test suite reports only the +denials whose subject program or object path belongs to xCAT. diff --git a/docs/source/guides/get-started/quick_start.rst b/docs/source/guides/get-started/quick_start.rst index b85d5c9e4c..3ff3e4d8e9 100644 --- a/docs/source/guides/get-started/quick_start.rst +++ b/docs/source/guides/get-started/quick_start.rst @@ -20,10 +20,9 @@ All the following steps should be executed in ``xcatmn.mydomain.com``. Prepare the Management Node ``xcatmn.mydomain.com`` ``````````````````````````````````````````````````` -#. Disable SELinux: :: - - echo 0 > /selinux/enforce - sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config +#. SELinux can stay enabled. xCAT runs with SELinux enforcing on the management node, and + the ``xCAT-selinux`` package carries the rules the confined OS services need. See + :doc:`SELinux <../../advanced/security/selinux>`. #. Set the hostname of ``xcatmn.mydomain.com``: :: From dc4fb8f0c2b8bbfad92026089409f5fb809ebec5 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:36:47 -0300 Subject: [PATCH 56/91] test(xcat-core): the netboot postinstall SELinux substitution is unanchored Thirteen netboot postinstall scripts, and the xcat_inventory postinstall fixture, disable SELinux in the rootimg with s/SELINUX=enforcing\|permissive/SELINUX=disabled/. The second alternative is a bare word with no key, so a config that reads SELINUX=permissive becomes SELINUX=SELINUX=disabled. The same alternative matches the stock comment that names permissive, which is rewritten on every image. sed returns 0 in both cases. postinstall_selinux_config.bats runs each script over a scratch image root and reads the config the script writes. Three of its six tests fail on this tree: the permissive value, the already-disabled config and the comment. The other three hold down behaviour the fix must keep. A no-op substitution turns the enforcing test red, and a dropped -f guard turns the absent-config test red. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../bats/postinstall_selinux_config.bats | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 xCAT-test/bats/postinstall_selinux_config.bats diff --git a/xCAT-test/bats/postinstall_selinux_config.bats b/xCAT-test/bats/postinstall_selinux_config.bats new file mode 100644 index 0000000000..59957e5861 --- /dev/null +++ b/xCAT-test/bats/postinstall_selinux_config.bats @@ -0,0 +1,116 @@ +#!/usr/bin/env bats +# +# Run each postinstall script that disables SELinux over a scratch image root, and read the +# config it writes. genimage gives the image root as $1, so every write stays under it. + +load 'helpers/shell_source' + +setup() +{ + IMAGE_ROOT="${BATS_TEST_TMPDIR}/rootimg" + CONFIG="${IMAGE_ROOT}/etc/selinux/config" + mkdir -p "${IMAGE_ROOT}/etc/selinux" "${IMAGE_ROOT}/tmp" +} + +# Each postinstall script that writes the SELinux config. A symlink shares the file it points +# at, so -type f gives one entry for each distinct script. +selinux_postinstalls() +{ + find "$(repo_root)" -name .git -prune -o -name '*.postinstall' -type f -print | + xargs -r grep -l 'etc/selinux/config' | sort +} + +# The stock EL config. The third comment line holds the word permissive, which an unanchored +# pattern matches. +write_config() +{ + cat >"$CONFIG" <&1 +} + +complain() +{ + printf '%s: %s\n' "$1" "$2" >&2 + return 1 +} + +@test "every postinstall that writes the SELinux config is under test" { + run selinux_postinstalls + [ "$status" -eq 0 ] + [[ "$output" == *"xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall"* ]] + [[ "$output" == *"xCAT-server/share/xcat/netboot/rh/service.postinstall"* ]] + [[ "$output" == *"xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall"* ]] + [ "$(printf '%s\n' "$output" | wc -l)" -ge 13 ] +} + +@test "an enforcing config becomes SELINUX=disabled" { + for script in $(selinux_postinstalls); do + write_config enforcing + run run_postinstall "$script" + [ "$status" -eq 0 ] || complain "$script" "exit $status: $output" + grep -qx 'SELINUX=disabled' "$CONFIG" || + complain "$script" "no SELINUX=disabled line: $(grep '^SELINUX=' "$CONFIG")" + done +} + +@test "a permissive config becomes SELINUX=disabled and not SELINUX=SELINUX=disabled" { + for script in $(selinux_postinstalls); do + write_config permissive + run run_postinstall "$script" + [ "$status" -eq 0 ] || complain "$script" "exit $status: $output" + grep -qx 'SELINUX=disabled' "$CONFIG" || + complain "$script" "no SELINUX=disabled line: $(grep '^SELINUX=' "$CONFIG")" + refute_grep -q 'SELINUX=SELINUX=' "$CONFIG" || + complain "$script" "the key is doubled: $(grep 'SELINUX=SELINUX=' "$CONFIG")" + done +} + +@test "a config that is already disabled keeps every line" { + for script in $(selinux_postinstalls); do + write_config disabled + cp "$CONFIG" "${BATS_TEST_TMPDIR}/before" + run run_postinstall "$script" + [ "$status" -eq 0 ] || complain "$script" "exit $status: $output" + diff -u "${BATS_TEST_TMPDIR}/before" "$CONFIG" || + complain "$script" "the disabled config changed" + done +} + +@test "the comment that names permissive keeps its text" { + local comment='# permissive - SELinux prints warnings instead of enforcing.' + for script in $(selinux_postinstalls); do + write_config enforcing + run run_postinstall "$script" + [ "$status" -eq 0 ] || complain "$script" "exit $status: $output" + grep -qxF "$comment" "$CONFIG" || + complain "$script" "the comment changed: $(grep -n permissive "$CONFIG")" + done +} + +@test "an absent SELinux config does not fail the script" { + for script in $(selinux_postinstalls); do + rm -f "$CONFIG" + run run_postinstall "$script" + [ "$status" -eq 0 ] || complain "$script" "exit $status: $output" + [ ! -e "$CONFIG" ] || complain "$script" "created $CONFIG" + # sed names the file it cannot read, so this text appears only when the script runs + # the substitution on an image that has no SELinux config. + [[ "$output" != *"selinux/config"* ]] || + complain "$script" "read a config that is not there: $output" + done +} From e7b24beba7b9470e47cc9c030b55bd7ef4123a81 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:37:00 -0300 Subject: [PATCH 57/91] fix(xcat-core): the netboot postinstall SELinux substitution doubles the key The substitution had two unanchored alternatives, SELINUX=enforcing and the bare word permissive. An image whose /etc/selinux/config reads SELINUX=permissive therefore gets SELINUX=SELINUX=disabled, which the policy loader rejects, so the image boots with SELinux enabled. The bare alternative also matches the comment that lists the three values, so every image gets a rewritten comment line. The substitution is now anchored on the whole assignment, the form xcatconfig already uses. Thirteen scripts carry it, and eleven more postinstall paths are symlinks into those files. The postinstall scripts source no shared library, so each copy is edited in place. Symlinks are how this tree already shares a postinstall between distributions. The xcat_inventory fixture test1.postinstall is changed as well. cases.environment names it as the postinstall attribute of an osimage, so genimage runs it on a real diskless image. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels7.ppc64.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels7.x86_64.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall | 2 +- .../share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall | 2 +- xCAT-server/share/xcat/netboot/rh/service.postinstall | 2 +- .../xcat/netboot/rocky/compute.rocky10.riscv64.postinstall | 2 +- .../templates/environment/gitrepo/postinstall/test1.postinstall | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall index dd2576c8f7..20fe449142 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall @@ -37,7 +37,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall index 2ad53bb406..6d62a73c14 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels7.ppc64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels7.ppc64.postinstall index eac5a8f4d8..a7c86c8088 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels7.ppc64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels7.ppc64.postinstall @@ -37,7 +37,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #-- Example of booted image versioning diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels7.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels7.x86_64.postinstall index 366e3d1df4..22bc97fe44 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels7.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels7.x86_64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #-- Example of booted image versioning diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall index dd2576c8f7..20fe449142 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall @@ -37,7 +37,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall index 2ad53bb406..6d62a73c14 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.x86_64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall index dd2576c8f7..20fe449142 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall @@ -37,7 +37,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall index 2ad53bb406..6d62a73c14 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.x86_64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-server/share/xcat/netboot/rh/service.postinstall b/xCAT-server/share/xcat/netboot/rh/service.postinstall index e410490db4..76df1cbc4d 100755 --- a/xCAT-server/share/xcat/netboot/rh/service.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/service.postinstall @@ -41,7 +41,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #-- Example of booted image versioning diff --git a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall index 015cfec0f9..b81f49e7ff 100755 --- a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall +++ b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys diff --git a/xCAT-test/autotest/testcase/xcat_inventory/templates/environment/gitrepo/postinstall/test1.postinstall b/xCAT-test/autotest/testcase/xcat_inventory/templates/environment/gitrepo/postinstall/test1.postinstall index 46b69ee521..e4a18cfffe 100755 --- a/xCAT-test/autotest/testcase/xcat_inventory/templates/environment/gitrepo/postinstall/test1.postinstall +++ b/xCAT-test/autotest/testcase/xcat_inventory/templates/environment/gitrepo/postinstall/test1.postinstall @@ -37,7 +37,7 @@ echo "co:2345:respawn:/sbin/agetty -L 38400 console" >> $installroot/etc/inittab #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #-- Example of booted image versioning From 7190ea979e341a2afc45d57135af260b69897025 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:27:28 -0300 Subject: [PATCH 58/91] test(xcat-core): no case runs the xcatmn probe No case in xCAT-test/autotest/testcase runs xcatprobe xcatmn, so a broken MN check reaches a release unseen. The new case runs the probe and asserts that the SELinux checkpoint appears and does not carry the FAIL marker. The case cannot reach the enforcing mode. A management node under test runs with SELinux disabled, and a disabled node needs a reboot and a relabel to become enforcing. probe_utils_selinux.t covers the enforcing verdict. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/bundle/alma10_x86_daily.bundle | 1 + xCAT-test/autotest/testcase/probe/xcatmn | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 xCAT-test/autotest/testcase/probe/xcatmn diff --git a/xCAT-test/autotest/bundle/alma10_x86_daily.bundle b/xCAT-test/autotest/bundle/alma10_x86_daily.bundle index f985cfd5c6..8aac7e004e 100644 --- a/xCAT-test/autotest/bundle/alma10_x86_daily.bundle +++ b/xCAT-test/autotest/bundle/alma10_x86_daily.bundle @@ -1,4 +1,5 @@ setup_vm #INCLUDE:rhels_x86_daily.bundle# xcatprobe_work +xcatprobe_xcatmn_selinux clean_up_env diff --git a/xCAT-test/autotest/testcase/probe/xcatmn b/xCAT-test/autotest/testcase/probe/xcatmn new file mode 100644 index 0000000000..6dae5014df --- /dev/null +++ b/xCAT-test/autotest/testcase/probe/xcatmn @@ -0,0 +1,7 @@ +start:xcatprobe_xcatmn_selinux +description:To test if xcatprobe xcatmn reports the SELinux mode of the management node, and does not report that mode as a failure. This case must run in xcat mn +label:mn_only,ci_test +cmd:xcatprobe xcatmn 2>&1 | grep -i selinux +check:rc==0 +check:output!~FAIL +end From 27586f1717d9b8527f86bd5a65ffc842831fb1e0 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:36:42 -0300 Subject: [PATCH 59/91] docs(xcat-core): the quick start shows a probe line the probe no longer prints The xcatmn probe checkpoint became "Checking SELinux policy for xCAT" when the probe started to check the xcat policy module and the labels of installdir and tftpdir. The transcript in the quick start still shows "Checking SELinux is disabled", which tells a reader that xCAT wants SELinux off. Show the line the probe prints. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/guides/get-started/quick_start.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/guides/get-started/quick_start.rst b/docs/source/guides/get-started/quick_start.rst index 3ff3e4d8e9..e6e889cc7e 100644 --- a/docs/source/guides/get-started/quick_start.rst +++ b/docs/source/guides/get-started/quick_start.rst @@ -101,7 +101,7 @@ Stage 2 Provision a node and manage it with parallel shell [mn]: Checking provision network is configured... [ OK ] [mn]: Checking 'passwd' table is configured... [ OK ] [mn]: Checking important directories(installdir,tftpdir) are configured... [ OK ] - [mn]: Checking SELinux is disabled... [ OK ] + [mn]: Checking SELinux policy for xCAT... [ OK ] [mn]: Checking HTTP service is configured... [ OK ] [mn]: Checking TFTP service is configured... [ OK ] [mn]: Checking DNS service is configured... [ OK ] From 900ed7d484fb0c45edbc7e97b7096502ec3ae89c Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:37:26 -0300 Subject: [PATCH 60/91] fix(xcat-test): no bundle names the client-domain SELinux case selinux_bundle.t fails on this branch: selinux_client_domain is in no bundle, so no run selects it. The case measures that an xCAT client command execs and transitions into xcat_t, which is the check that a client cannot run at all under enforcing. Name it in selinux.bundle and selinux_mn.bundle. It needs no compute node, so it belongs in both. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/bundle/selinux.bundle | 1 + xCAT-test/autotest/bundle/selinux_mn.bundle | 1 + 2 files changed, 2 insertions(+) diff --git a/xCAT-test/autotest/bundle/selinux.bundle b/xCAT-test/autotest/bundle/selinux.bundle index c911b45964..5bb2f1c8c2 100644 --- a/xCAT-test/autotest/bundle/selinux.bundle +++ b/xCAT-test/autotest/bundle/selinux.bundle @@ -1,4 +1,5 @@ selinux_xcatd_domain +selinux_client_domain selinux_mn_labels selinux_restapi_avc selinux_cn_diskful_enforcing diff --git a/xCAT-test/autotest/bundle/selinux_mn.bundle b/xCAT-test/autotest/bundle/selinux_mn.bundle index bebb26dbce..8da860fc9b 100644 --- a/xCAT-test/autotest/bundle/selinux_mn.bundle +++ b/xCAT-test/autotest/bundle/selinux_mn.bundle @@ -1,3 +1,4 @@ selinux_xcatd_domain +selinux_client_domain selinux_mn_labels selinux_restapi_avc From 9c41bffb963fc0f18eb1a2584f5f4eb455018e79 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:44:04 -0300 Subject: [PATCH 61/91] fix(xcat-test): the postinstall inventory check counts names, not files postinstall_selinux_config.bats required at least 13 postinstall scripts that write the SELinux config. Three riscv64 scripts are now symlinks to the rocky one, and the find uses -type f, which counts a shared file once, so the list holds 12 entries for 15 names and the check fails on a tree where nothing is wrong. Lower the bound to 12 and name the aarch64 script among the representatives. The bound exists to catch a find that stops matching; a new script needs no new bound, because every other test in the file loops over the same list. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/bats/postinstall_selinux_config.bats | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xCAT-test/bats/postinstall_selinux_config.bats b/xCAT-test/bats/postinstall_selinux_config.bats index 59957e5861..ec0cb51f05 100644 --- a/xCAT-test/bats/postinstall_selinux_config.bats +++ b/xCAT-test/bats/postinstall_selinux_config.bats @@ -55,7 +55,11 @@ complain() [[ "$output" == *"xCAT-server/share/xcat/netboot/rh/compute.rhels10.x86_64.postinstall"* ]] [[ "$output" == *"xCAT-server/share/xcat/netboot/rh/service.postinstall"* ]] [[ "$output" == *"xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall"* ]] - [ "$(printf '%s\n' "$output" | wc -l)" -ge 13 ] + [[ "$output" == *"xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall"* ]] + # Three riscv64 scripts are symlinks to the rocky one, and -type f counts a shared file + # once, so the twelve entries cover fifteen names. The bound catches a find that stops + # matching; a new script needs no new bound, because every test loops over this list. + [ "$(printf '%s\n' "$output" | wc -l)" -ge 12 ] } @test "an enforcing config becomes SELINUX=disabled" { From 10c2bd5d9b3509ff18d336bfb7aea4dd1654ca8f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:44:04 -0300 Subject: [PATCH 62/91] fix(xcat-core): the aarch64 postinstall SELinux substitution doubles the key compute.rhels10.aarch64.postinstall arrived after the other netboot postinstall scripts were anchored, and it carries the old pattern: s/SELINUX=enforcing\|permissive/SELINUX=disabled/. The alternation binds to the whole pattern, so the right branch is the bare word permissive. On a permissive image the substitution writes SELINUX=SELINUX=disabled, which no SELinux reads, and it rewrites the comment line that names permissive. On a disabled image it still rewrites that comment. Anchor the pattern to the SELINUX= line, as the other scripts do. postinstall_selinux_config.bats fails three of its six checks against this script before the change. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall index 2ad53bb406..6d62a73c14 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall @@ -37,7 +37,7 @@ END #-- Need to disable selinux, otherwise, the booting will hang on "Loading selinux policy" if [ -f "$installroot/etc/selinux/config" ] then - sed -i 's/SELINUX=enforcing\|permissive/SELINUX=disabled/' $installroot/etc/selinux/config + sed -i 's/^SELINUX=.*$/SELINUX=disabled/' $installroot/etc/selinux/config fi #--for redhat 8 and 8.1 #-- Need to disable firewalld, otherwise, the remoteshell script will not able to get all the SSH keys From cec69be3d243ec8fe416ef8c1fb8f3f21dd96ff9 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:48:23 -0300 Subject: [PATCH 63/91] test(xcat-core): no case measures SELinux on a service node or a statelite node The selinux cases cover the management node and a compute node. A hierarchical cluster has a service node, which installs xCAT itself and serves /install and /tftpboot to its own nodes, and nothing measured it under SELinux. A statelite node was not measured either, although node_modes resolves it to disabled on purpose. selinux_sn_enforcing reads the provisioned service node: getenforce, the kernel command line, the xcat policy module, the labels of /install, /tftpboot, /opt/xcat and /xcatpost, a restorecon dry run that must find nothing to relabel, xcatd active, and no xCAT denial since boot. selinux_sn_per_node_switch sets noderes.selinux on the service node and reads the mode out of the kickstart that nodeset writes for it, in all three directions, and checks that a value on the compute node does not reach the service node. selinux_cn_statelite_disabled_by_design asks for enforcing on a statelite node and requires selinux=0 on its boot configuration, with nodeset saying why. selinux_bundle.t now keeps a service-node case out of the management-node bundle, the same way it keeps a compute-node case out. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/bundle/selinux.bundle | 3 + xCAT-test/autotest/testcase/selinux/cases1 | 92 ++++++++++++++++++++++ xCAT-test/unit/selinux_bundle.t | 5 +- 3 files changed, 98 insertions(+), 2 deletions(-) diff --git a/xCAT-test/autotest/bundle/selinux.bundle b/xCAT-test/autotest/bundle/selinux.bundle index 5bb2f1c8c2..d893351af1 100644 --- a/xCAT-test/autotest/bundle/selinux.bundle +++ b/xCAT-test/autotest/bundle/selinux.bundle @@ -5,3 +5,6 @@ selinux_restapi_avc selinux_cn_diskful_enforcing selinux_cn_diskless_disabled_by_design selinux_cn_diskless_site_disabled +selinux_sn_enforcing +selinux_sn_per_node_switch +selinux_cn_statelite_disabled_by_design diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index 86d38bca0a..6d78fbaf98 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -104,3 +104,95 @@ cmd:sh -c 'chtab key=selinux site.value="$(cat /tmp/selinux_site.orig)"' check:rc==0 cmd:rm -f /tmp/selinux_site.orig end + +start:selinux_sn_enforcing +description:in a hierarchical cluster, the service node runs SELinux enforcing with the xCAT labels in place and no xCAT denial since boot +label:selinux,sn_diskful +os:rhels +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:xdsh $$SN getenforce +check:rc==0 +check:output=~Enforcing +cmd:xdsh $$SN cat /proc/cmdline +check:rc==0 +check:output!~selinux=0 +cmd:xdsh $$SN "rpm -q xCAT-selinux" +check:rc==0 +cmd:xdsh $$SN "semodule -l | grep -x -E 'xcat([[:space:]].*)?'" +check:rc==0 +cmd:xdsh $$SN "ls -dZ /install /tftpboot /opt/xcat /xcatpost" +check:rc==0 +check:output!~unlabeled_t +check:output!~default_t +cmd:xdsh $$SN "restorecon -Rnv /xcatpost /opt/xcat /etc/xcat /var/log/xcat" +check:rc==0 +check:output!~Would relabel +cmd:xdsh $$SN "systemctl is-active xcatd" +check:rc==0 +check:output=~active +cmd:xdcp $$SN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ +check:rc==0 +cmd:xdsh $$SN "sh /tmp/selinux_avc_check.sh boot" +check:rc==0 +check:output=~XCAT_AVC=0 +cmd:xdsh $$SN "rm -f /tmp/selinux_avc_check.sh" +check:rc==0 +end + +start:selinux_sn_per_node_switch +description:noderes.selinux on one service node decides the SELinux mode its installer configures, without touching the rest of the cluster +label:selinux,sn_diskful +os:rhels +cmd:sh -c 'lsdef -t node -o $$SN -i selinux -c > /tmp/selinux_sn_switch.orig' +check:rc==0 +cmd:chdef -t node -o $$SN selinux=disabled +check:rc==0 +cmd:nodeset $$SN osimage=__GETNODEATTR($$SN,os)__-__GETNODEATTR($$SN,arch)__-install-service +check:rc==0 +cmd:grep -E "^selinux --" /install/autoinst/$$SN +check:rc==0 +check:output=~disabled +cmd:chdef -t node -o $$SN selinux=enforcing +check:rc==0 +cmd:nodeset $$SN osimage=__GETNODEATTR($$SN,os)__-__GETNODEATTR($$SN,arch)__-install-service +check:rc==0 +cmd:grep -E "^selinux --" /install/autoinst/$$SN +check:rc==0 +check:output=~enforcing +cmd:grep -c restorecon /install/autoinst/$$SN +check:rc==0 +check:output!~^0$ +cmd:chdef -t node -o $$CN selinux=permissive +check:rc==0 +cmd:nodeset $$SN osimage=__GETNODEATTR($$SN,os)__-__GETNODEATTR($$SN,arch)__-install-service +check:rc==0 +cmd:grep -E "^selinux --" /install/autoinst/$$SN +check:rc==0 +check:output=~enforcing +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +cmd:sh -c 'chdef -z < /tmp/selinux_sn_switch.orig' +check:rc==0 +cmd:rm -f /tmp/selinux_sn_switch.orig +end + +start:selinux_cn_statelite_disabled_by_design +description:a statelite compute node asked for SELinux enforcing gets selinux=0, because its root is assembled from read-only mounts, and nodeset says so +label:selinux,provision +os:rhels +cmd:getenforce +check:rc==0 +check:output=~^Enforcing$ +cmd:chdef -t node -o $$CN selinux=enforcing +check:rc==0 +cmd:nodeset $$CN osimage=$$STATELITE +check:rc==0 +check:output=~SELinux is disabled +cmd:sh -c 'grep -rh "selinux=0" /tftpboot/xcat/xnba/nodes/$$CN /tftpboot/pxelinux.cfg/$$CN /tftpboot/petitboot/$$CN 2>/dev/null | wc -l' +check:rc==0 +check:output!~^0$ +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +end diff --git a/xCAT-test/unit/selinux_bundle.t b/xCAT-test/unit/selinux_bundle.t index dc7a7e721c..7b9fdf06d9 100644 --- a/xCAT-test/unit/selinux_bundle.t +++ b/xCAT-test/unit/selinux_bundle.t @@ -30,8 +30,9 @@ is_deeply(\@orphans, [], 'every selinux case is named by a bundle'); my @mn = grep { /\S/ } read_lines("$root/xCAT-test/autotest/bundle/selinux_mn.bundle"); my %mn = map { $_ => 1 } @mn; foreach my $case (@cases) { - next unless $case =~ /_cn_/; - ok(!$mn{$case}, "$case needs a compute node, so the management node bundle leaves it out"); + next unless $case =~ /_(cn|sn)_/; + my $needs = $1 eq 'cn' ? 'a compute node' : 'a service node'; + ok(!$mn{$case}, "$case needs $needs, so the management node bundle leaves it out"); } done_testing(); From 4e7cdef8ceed94ea26b8a52f6bfb559e1b9e6eb5 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:58:07 -0300 Subject: [PATCH 64/91] fix(xcat-test): the statelite SELinux case has no image to boot selinux_cn_statelite_disabled_by_design ran nodeset against the statelite osimage without building it. copycds declares the osimage, and nodeset needs the image tree and the litefile links that genimage and liteimg create, so the case failed on a fresh cluster for a reason that has nothing to do with SELinux. Build the image in the case. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/selinux/cases1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index 6d78fbaf98..5450fb3312 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -187,6 +187,10 @@ check:rc==0 check:output=~^Enforcing$ cmd:chdef -t node -o $$CN selinux=enforcing check:rc==0 +cmd:genimage $$STATELITE +check:rc==0 +cmd:liteimg $$STATELITE +check:rc==0 cmd:nodeset $$CN osimage=$$STATELITE check:rc==0 check:output=~SELinux is disabled From 4487162ff6a0148effec373e507d8d633bb93bd3 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:37:00 -0300 Subject: [PATCH 65/91] test(xcat-core): no case has an image root called rootimg The file contexts exclude a guest tree by the name rootimg at any depth under /install. The native lookup case has no image whose profile is rootimg, so nothing measured what happens when the image root itself carries that name. Add three images: a profile called rootimg, one called rootimg-statelite and one whose name only contains rootimg. Each contributes its guest files and its published files, so the case asks for both answers on the same path depth. Record the choice for a rootimg component inside an image root, which is ambiguous, and add four guest files whose own names are published names. 54 of the 224 checks fail against the file contexts before the next commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/native/selinux_file_contexts.t | 31 +++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/xCAT-test/native/selinux_file_contexts.t b/xCAT-test/native/selinux_file_contexts.t index c0e15681b0..a54b5ce09b 100644 --- a/xCAT-test/native/selinux_file_contexts.t +++ b/xCAT-test/native/selinux_file_contexts.t @@ -81,12 +81,20 @@ sub lookup { install_module(); +# The last component of an image root is the profile, and a profile may be +# called rootimg. The guest tree is then <...>/rootimg/rootimg and the +# published kernel is <...>/rootimg/kernel, so a rule that matches the name +# rootimg anywhere in the path takes the kernel with it. my @images = ( '/install/netboot/rhels9/x86_64/compute', + '/install/netboot/rhels9/x86_64/rootimg', + '/install/netboot/rhels9/x86_64/rootimg-statelite', + '/install/netboot/rhels9/x86_64/rootimg-custom', '/install/netboot/custom-image', '/install/custom/images/rhels9-compute', ); -my @guest = map { ("$_/rootimg/etc/shadow", "$_/rootimg-statelite/etc/shadow") } @images; +my @guest = map { ("$_/rootimg/etc/shadow", "$_/rootimg/etc/passwd", + "$_/rootimg-statelite/etc/shadow") } @images; my @published = map { my $dir = $_; map { "$dir/$_" } qw(kernel initrd-stateless.gz initrd-statelite.gz rootimg.cpio.gz @@ -101,6 +109,27 @@ foreach my $path (@published, '/install', '/install/postscripts/xcatdsklspost') is(lookup($path), 'public_content_t', "$path is public_content_t"); } +# rootimgdir is any path under /install, so a component called rootimg in the +# MIDDLE of an image root cannot be told from a guest tree rooted there: +# /install/netboot/rootimg/a/b/kernel is either a published kernel below an +# image root called .../rootimg/a/b, or a file inside a guest tree rooted at +# /install/netboot/rootimg. The rules keep the guest labels, which leaves the +# first reading unlabelled. Hold that choice down, so a change of direction +# fails here instead of silently relabelling a guest. +foreach my $path ('/install/netboot/rootimg/rhels9/x86_64/compute/kernel', + '/install/netboot/rootimg/rhels9/x86_64/compute/rootimg/etc/shadow') { + is(lookup($path), '<>', + "a rootimg component inside an image root keeps $path out of the relabel"); +} + +# A guest file whose own name is a published name keeps its label: the rules +# name the component directly below rootimg, not a name at any depth. +foreach my $path (map { "/install/netboot/rhels9/x86_64/$_" } + qw(compute/rootimg/usr/src/kernel rootimg/rootimg/usr/src/kernel + rootimg/rootimg/boot/initrd.img rootimg/rootimg/var/lib/rootimg.sfs)) { + is(lookup($path), '<>', "a guest file at $path keeps its own label"); +} + # A management node: each guest file keeps the label of its own operating # system, and each published file starts with the label it had before the # package was installed. From 07ef2be0dece17c7017fe6d8f2ed239b5b98631d Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:37:00 -0300 Subject: [PATCH 66/91] fix(xcat-core): a published kernel loses public_content_t beside an image root called rootimg The exclusions match the component name rootimg anywhere under /install. A profile may be called rootimg, and the image root is then /install/netboot///rootimg. The files genimage and packimage publish in that image root, among them kernel and the initrds, sit one component below a name the exclusions match, so each resolves to <> instead of public_content_t and httpd cannot serve it. The same happens for a profile called rootimg-statelite. Name each published file in the image root: kernel, hypervisor, the initrds, the rootimg archives, rootimgtree, litefile.csv, common.filelist, common and overlay. The entry names the component directly below the rootimg component, so a guest file deeper in the tree matches none of them and keeps the label of its own operating system. selinux_file_contexts.t fails 54 of its 224 checks without this change. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 9b24c4bdb3..65c2299aed 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -20,3 +20,21 @@ # depth under /install. /install(/.*)?/rootimg(/.*)? <> /install(/.*)?/rootimg-statelite(/.*)? <> + +# A profile may be called rootimg or rootimg-statelite. The image root is then +# itself called rootimg, the guest tree is <...>/rootimg/rootimg, and the files +# genimage and packimage publish in the image root sit one component below a +# name the two rules above match. Each published name is listed here, so the +# published file keeps public_content_t while the tree beside it stays excluded. +# A guest file matches none of these: the name must be the one directly below +# the rootimg component. +/install(/.*)?/rootimg(-statelite)?/kernel -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/hypervisor -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/initrd[^/]* -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/rootimg\.[^/]* -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/rootimg-statelite\.[^/]* -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/rootimgtree\.[^/]* -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/litefile\.csv -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/common\.filelist -- gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/common(/.*)? gen_context(system_u:object_r:public_content_t,s0) +/install(/.*)?/rootimg(-statelite)?/overlay(/.*)? gen_context(system_u:object_r:public_content_t,s0) From 14f0f284773ed4a130146baa873605b2ec936009 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:50:32 -0300 Subject: [PATCH 67/91] test(xcat-core): no case starts xcatd from a relocated installation xcatd_service_direct_exec.t reads the shipped unit on a default install, where the prefix in the unit and the prefix of the installation are the same path. It cannot fail when they differ, which is the case the systemd startup has to get right. xcatd_relocated_startup.t installs the built xCAT-server package twice, once with the default prefix and once with rpm --prefix /srv/xcat. For each one it composes the environment the unit gives ExecStart, in the order the unit lists Environment and EnvironmentFile, then asserts XCATROOT, that every xCAT directory on PATH is under that prefix, and that the daemon the start command runs receives the prefix. The /srv/xcat subtest fails 3 of its 11 checks before the next commit; the /opt/xcat subtest passes either way. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .github/workflows/xcat_test.yml | 2 +- xCAT-test/native/README.md | 1 + xCAT-test/native/xcatd_relocated_startup.t | 138 +++++++++++++++++++++ 3 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 xCAT-test/native/xcatd_relocated_startup.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index b2069561ed..8256dfd474 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -115,7 +115,7 @@ jobs: - name: Enable lifecycle test namespaces run: sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - name: Test RPM package lifecycle - run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/xcatd_rpm_lifecycle.t xCAT-test/native/apache_rpm_configuration.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t' + run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/xcatd_rpm_lifecycle.t xCAT-test/native/xcatd_relocated_startup.t xCAT-test/native/apache_rpm_configuration.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t' selinux_policy_test: runs-on: ubuntu-24.04 timeout-minutes: 20 diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 98c6e6a144..eea92b32f5 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -223,6 +223,7 @@ On EL8 or EL10, install `bubblewrap`, `rpm-build`, `systemd`, `chkconfig`, ``` prove xCAT-test/native/xcatd_rpm_lifecycle.t \ + xCAT-test/native/xcatd_relocated_startup.t \ xCAT-test/native/apache_rpm_configuration.t \ xCAT-test/native/apache_package_lifecycle.t \ xCAT-test/native/package_upgrade_logging.t diff --git a/xCAT-test/native/xcatd_relocated_startup.t b/xCAT-test/native/xcatd_relocated_startup.t new file mode 100644 index 0000000000..c9427b5af7 --- /dev/null +++ b/xCAT-test/native/xcatd_relocated_startup.t @@ -0,0 +1,138 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use Test::More; +use Text::ParseWords qw(shellwords); +use XCAT::Test::RPM; + +plan skip_all => 'Native RPM distribution and Linux namespaces are required' + unless $^O eq 'linux' && -f '/etc/redhat-release'; + +my $rpm = XCAT::Test::RPM->build('xCAT-server', 1); + +#--- + +=head3 service_settings + + Descriptions: Read the [Service] section of a unit file, in order. + Arguments: The text of the unit file. + Returns: A list of [directive, value] pairs. + +=cut + +#--- +sub service_settings { + my ($text) = @_; + my ($section, @settings); + foreach my $line (split /\n/, $text) { + if ($line =~ /^\s*\[([^]]+)\]\s*$/) { $section = $1; next; } + next unless ($section // '') eq 'Service'; + push @settings, [ $1, $2 ] if $line =~ /^\s*(\w+)\s*=\s*(.*)$/; + } + return @settings; +} + +#--- + +=head3 unit_environment + + Descriptions: Compose the environment systemd gives ExecStart. Environment + and EnvironmentFile apply in the order the unit lists them, + and a later setting replaces an earlier one. A leading - on + an EnvironmentFile path makes a missing file not an error. + Arguments: The scratch root, and the unit path inside it. + Returns: A hash reference of the composed variables. + +=cut + +#--- +sub unit_environment { + my ($root, $unit) = @_; + my %env; + foreach my $setting (service_settings($root->read($unit))) { + my ($directive, $value) = @{$setting}; + if ($directive eq 'Environment') { + foreach my $word (shellwords($value)) { + $env{$1} = $2 if $word =~ /^(\w+)=(.*)$/; + } + } elsif ($directive eq 'EnvironmentFile') { + (my $path = $value) =~ s/^-//; + next unless -f $root->path($path); + foreach my $line (split /\n/, $root->read($path)) { + next if $line =~ /^\s*(?:#|$)/; + next unless $line =~ /^\s*(\w+)\s*=\s*(.*?)\s*$/; + my ($name, $word) = ($1, $2); + $word =~ s/^"(.*)"$/$1/ or $word =~ s/^'(.*)'$/$1/; + $env{$name} = $word; + } + } + } + return \%env; +} + +#--- + +=head3 exec_start + + Descriptions: Give the start command of a unit, as systemd would run it. + Arguments: The scratch root, and the unit path inside it. + Returns: The command and its arguments. + +=cut + +#--- +sub exec_start { + my ($root, $unit) = @_; + my @commands = map { $_->[1] } + grep { $_->[0] eq 'ExecStart' && length $_->[1] } service_settings($root->read($unit)); + die 'Expected one service start command' unless @commands == 1; + return shellwords($commands[0]); +} + +my $unit = '/usr/lib/systemd/system/xcatd.service'; + +# One subtest per prefix. The daemon runs from the prefix rpm relocated the +# package to, so XCATROOT and the command directories on PATH must name that +# prefix and not the one the unit file was written with. +foreach my $prefix ('/opt/xcat', '/srv/xcat') { + subtest "a package installed under $prefix starts the daemon of $prefix" => sub { + my $root = XCAT::Test::RPM->new; + $root->write('/etc/os-release', "ID=rhel\nVERSION_ID=\"10.0\"\n"); + my ($status, $out, $err) = $root->install($rpm, '--prefix', $prefix); + is($status, 0, "install under $prefix") or diag "$out$err"; + + ok(-e $root->path("$prefix/sbin/xcatd"), "the daemon is installed in $prefix"); + is(readlink($root->path('/usr/sbin/xcatd')), "$prefix/sbin/xcatd", + 'the daemon symlink names the installed prefix'); + + my $env = unit_environment($root, $unit); + is($env->{XCATROOT}, $prefix, "XCATROOT of the unit is $prefix"); + + my @xcat = grep { m{/xcat(/|$)} } split /:/, ($env->{PATH} // ''); + ok(scalar(@xcat) >= 3, 'PATH carries the xCAT command directories') + or diag($env->{PATH} // '(no PATH)'); + my @wrong = grep { !m{^\Q$prefix\E/} } @xcat; + is_deeply(\@wrong, [], "every xCAT directory on PATH is under $prefix"); + + # Run the start command with the environment the unit composes, and read + # back what the daemon received. + my @start = exec_start($root, $unit); + is($start[0], '/usr/sbin/xcatd', 'the unit starts the daemon without a shell'); + $root->write("$prefix/sbin/xcatd", + "#!/bin/sh\nprintf 'xcatd XCATROOT=%s\\n' \"\$XCATROOT\" >> /calls\n", 0755); + ($status, $out, $err) = $root->run('env', "XCATROOT=$env->{XCATROOT}", + "PATH=$env->{PATH}", @start); + is($status, 0, 'the start command runs') or diag "$out$err"; + is($root->read('/calls'), "xcatd XCATROOT=$prefix\n", + "the daemon receives XCATROOT=$prefix"); + + ($status, $out, $err) = $root->run('rpm', '--nodeps', '-e', 'xCAT-server'); + is($status, 0, 'erase transaction') or diag "$out$err"; + ok(!-e $root->path('/etc/xcat/xcatroot.env'), + 'erase removes the generated environment file'); + }; +} + +done_testing(); From 3d58aefcbab7ccacccbe95f23b84fec02112538f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:50:33 -0300 Subject: [PATCH 68/91] fix(xcat-core): a relocated xcatd loads the modules of another installation xcatd.service sets XCATROOT and PATH to the literal /opt/xcat. The previous ExecStart sourced xcat.sh, which %post generates from RPM_INSTALL_PREFIX0, so a relocated package got its own prefix. With the package installed under /srv/xcat the daemon symlink reaches /srv/xcat/sbin/xcatd and the Perl search path still names /opt/xcat, so xcatd cannot load its own modules unless the administrator overrides the environment or a default installation is left behind. %post writes /etc/xcat/xcatroot.env with XCATROOT and PATH built from RPM_INSTALL_PREFIX0, and the unit reads it with EnvironmentFile. The order is the default in the unit, then that file, then /etc/sysconfig/xcat, so the recorded prefix replaces the default and the site file keeps the last word. ExecStart stays a direct call, so the kernel still enters xcat_t on the xcatd script. %preun removes the file on erase. The file is not in %files, so rpm --verify is unaffected. xcatd_relocated_startup.t fails 3 checks of its /srv/xcat subtest without this change. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-server/etc/init.d/xcatd.service | 5 +++++ xCAT-server/xCAT-server.spec | 10 ++++++++++ xCAT-test/unit/xcatd_service_direct_exec.t | 8 ++++++-- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/xCAT-server/etc/init.d/xcatd.service b/xCAT-server/etc/init.d/xcatd.service index 6e368ef37b..4ae5e0f099 100644 --- a/xCAT-server/etc/init.d/xcatd.service +++ b/xCAT-server/etc/init.d/xcatd.service @@ -7,6 +7,11 @@ After=network.target syslog.service # kernel enters xcat_t on the xcatd script. Environment=XCATROOT=/opt/xcat PERL_BADLANG=0 Environment=PATH=/opt/xcat/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +# The two lines above hold the default prefix. %post writes xcatroot.env with +# the prefix rpm relocated the package to, and a later setting replaces an +# earlier one, so a relocated install reaches its own modules. The site file +# comes last and keeps the last word. +EnvironmentFile=-/etc/xcat/xcatroot.env EnvironmentFile=-/etc/sysconfig/xcat Type=forking PIDFile=/run/xcatd.pid diff --git a/xCAT-server/xCAT-server.spec b/xCAT-server/xCAT-server.spec index b26692aec9..c4c5307bc6 100644 --- a/xCAT-server/xCAT-server.spec +++ b/xCAT-server/xCAT-server.spec @@ -519,6 +519,15 @@ ln -sf $RPM_INSTALL_PREFIX0/share/xcat/netboot/centos $RPM_INSTALL_PREFIX0/share xcatd_init_compat=$RPM_INSTALL_PREFIX0/share/xcat/scripts/xcatd-init-compat export XCATROOT="$RPM_INSTALL_PREFIX0" +# xcatd.service carries the default prefix. Record the prefix of this install, +# so a relocated package starts the daemon of its own tree. +mkdir -p /etc/xcat +cat > /etc/xcat/xcatroot.env <{EnvironmentFile}, ['-/etc/sysconfig/xcat'], - '/etc/sysconfig/xcat can still override the environment'); +# A later setting replaces an earlier one, so the order decides who wins: the +# prefix %post recorded beats the default in the unit, and the site file beats +# both. +is_deeply($service->{EnvironmentFile}, + [ '-/etc/xcat/xcatroot.env', '-/etc/sysconfig/xcat' ], + 'the install prefix is read before the site file, and both are optional'); done_testing(); From 4ba2cd0d70d82629949f9d604685cd1f80c67f4a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:50:52 -0300 Subject: [PATCH 69/91] docs(selinux): the page says the daemon context is always in /opt/xcat The page states that the context belongs to the file in /opt/xcat. The prefix is now recorded at install time, so a relocated package starts the daemon of its own tree, and the file contexts still name /opt/xcat. Say both, so a reader of a relocated installation knows the entrypoints need their own entries. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 5dd7abadc8..fb935e3a57 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -64,6 +64,12 @@ unit must name ``xcatd`` and not a shell. 115 command names are symlinks to file it points to. ``/usr/sbin/xcatd`` is a symlink, and ``execve`` resolves it, so the context belongs to the file in ``/opt/xcat``. +The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes +``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit +reads after that default. The file contexts name ``/opt/xcat``, so a package +relocated with ``rpm --prefix`` starts in its own tree but needs its own file +context entries before the entrypoints reach ``xcat_t``. + Read the domain of the running daemon with:: ps -o label= -p "$(cat /run/xcatd.pid)" From d7f579440d8c54590ffb39c9d58151579f2d05e2 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:16:06 -0300 Subject: [PATCH 70/91] test(xcat-core): nothing starts xcatd without the recorded prefix file %post writes /etc/xcat/xcatroot.env and %preun removes it, so the file is absent on rpm --justdb, before %post runs, and after an interrupted install. Both subtests of xcatd_relocated_startup.t have the file present, so neither reads what happens without it. Add a subtest that removes the file: each EnvironmentFile of the unit carries a leading -, which makes a missing file not an error, XCATROOT is the default of the unit, and the daemon starts with that default instead of the installed prefix. Dropping the default XCATROOT from the unit fails checks 4 and 7 of that subtest. Record the trade the file contexts make for a rootimg component in the middle of an image root: the guest labels are kept, which leaves the published kernel of that one layout unlabeled, so httpd cannot serve it and that osimage cannot netboot. The note names the recovery. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 8 +++++ xCAT-selinux/xcat.fc | 9 +++++ xCAT-test/native/xcatd_relocated_startup.t | 42 ++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index fb935e3a57..38036d0806 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -64,6 +64,14 @@ unit must name ``xcatd`` and not a shell. 115 command names are symlinks to file it points to. ``/usr/sbin/xcatd`` is a symlink, and ``execve`` resolves it, so the context belongs to the file in ``/opt/xcat``. +A rootimg component in the middle of an image root is ambiguous, because +``rootimgdir`` is any path under ``/install``. The file contexts keep the guest +labels there, so an osimage whose ``rootimgdir`` has a directory called +``rootimg`` above the tree leaves its published kernel and initrd unlabeled, +and ``httpd`` cannot serve them. Give such an osimage a ``rootimgdir`` with no +``rootimg`` component, or run ``restorecon`` over the image root after the +package is installed. + The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit reads after that default. The file contexts name ``/opt/xcat``, so a package diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 65c2299aed..733f7b14b0 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -28,6 +28,15 @@ # published file keeps public_content_t while the tree beside it stays excluded. # A guest file matches none of these: the name must be the one directly below # the rootimg component. +# +# A rootimg component in the MIDDLE of an image root stays ambiguous, because +# rootimgdir is any path: /install/netboot/rootimg/a/b/kernel is either a +# published kernel of the image root /install/netboot/rootimg/a/b, or a file +# inside a guest tree rooted at /install/netboot/rootimg. These rules keep the +# guest labels, so that layout leaves the published kernel unlabeled and httpd +# cannot serve it, which stops netboot for that one osimage. Losing a boot file +# of a named layout is recoverable with restorecon; relabeling a guest +# operating system is not. /install(/.*)?/rootimg(-statelite)?/kernel -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/hypervisor -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/initrd[^/]* -- gen_context(system_u:object_r:public_content_t,s0) diff --git a/xCAT-test/native/xcatd_relocated_startup.t b/xCAT-test/native/xcatd_relocated_startup.t index c9427b5af7..db0bb10062 100644 --- a/xCAT-test/native/xcatd_relocated_startup.t +++ b/xCAT-test/native/xcatd_relocated_startup.t @@ -135,4 +135,46 @@ foreach my $prefix ('/opt/xcat', '/srv/xcat') { }; } +# %post writes the environment file and %preun takes it away, so it is absent +# on rpm --justdb, before %post runs, and after an interrupted install. The +# unit must still start: each EnvironmentFile carries a leading -, which makes +# a missing file not an error, and the unit keeps a default XCATROOT. +subtest 'the unit starts when the recorded prefix file is absent' => sub { + my $root = XCAT::Test::RPM->new; + $root->write('/etc/os-release', "ID=rhel\nVERSION_ID=\"10.0\"\n"); + my ($status, $out, $err) = $root->install($rpm, '--prefix', '/srv/xcat'); + is($status, 0, 'install under /srv/xcat') or diag "$out$err"; + + foreach my $setting (service_settings($root->read($unit))) { + next unless $setting->[0] eq 'EnvironmentFile'; + like($setting->[1], qr{^-}, + "a missing $setting->[1] does not stop the unit"); + } + + unlink($root->path('/etc/xcat/xcatroot.env')) + or die 'removing the recorded prefix: ' . $!; + # The default in the unit is the only source left, so name it. An empty + # value would satisfy a check that only compared the composed value with + # itself. + my $env = unit_environment($root, $unit); + is($env->{XCATROOT}, '/opt/xcat', 'XCATROOT is the default of the unit'); + like($env->{PATH} // '', qr{\Q/opt/xcat/sbin\E}, + 'PATH is the default of the unit'); + + # The daemon symlink still names /srv/xcat, and XCATROOT falls back to the + # default in the unit, so the daemon starts and reads the modules of the + # other prefix. That is the state before this change, and it is what the + # recorded prefix file removes. Record at the path the symlink names, so + # the test writes nothing outside its scratch tree. + my @start = exec_start($root, $unit); + my $target = readlink($root->path('/usr/sbin/xcatd')); + $root->write($target, + "#!/bin/sh\nprintf 'xcatd XCATROOT=%s\\n' \"\$XCATROOT\" >> /calls\n", 0755); + ($status, $out, $err) = $root->run('env', "XCATROOT=$env->{XCATROOT}", + "PATH=$env->{PATH}", @start); + is($status, 0, 'the start command runs without the recorded prefix') or diag "$out$err"; + is($root->read('/calls'), "xcatd XCATROOT=/opt/xcat\n", + 'the daemon starts with the default prefix, not the installed one'); +}; + done_testing(); From b5607a944c85f4d5b2c79cb16b0f880eee5db67a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:00:10 -0300 Subject: [PATCH 71/91] fix(xcat-test): every AVC check in the selinux cases searches an empty window The cases marked the start of their window with date "+%x %T" and gave it to ausearch. audit 4.0.3 takes a bare HH:MM:SS and rejects that format: it prints nothing and exits 0. Measured on an enforcing AlmaLinux 10.2 management node, with the raw log holding 4197 records: "-ts 10/21/2026 20:59:08" returned 0 records, "-ts 20:59:08" returned 22 and "-ts today" returned 4006. So selinux_avc_check.sh searched nothing and reported XCAT_AVC=0 whatever the node did. The positive control of selinux_mn_labels is what found it. The case mislabels /install/postscripts/xcatdsklspost, shows httpd answering 403 and requires the check to report XCAT_AVC=[1-9]; it reported SEARCHED=0 AVC=0 XCAT_AVC=0 and the case failed on an enforcing el10 node. The four cases now write date "+%H:%M:%S". selinux_avc_check.sh refuses a window that holds no audit record at all, because that is not a credible answer on a running node, and names the format in the message. selinux_avc_check.bats fails its ninth check against the unguarded script. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../autotest/testcase/commoncmd/selinux_avc_check.sh | 11 +++++++++++ xCAT-test/autotest/testcase/selinux/cases0 | 6 +++--- xCAT-test/autotest/testcase/selinux/cases1 | 2 +- xCAT-test/bats/selinux_avc_check.bats | 7 +++++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh index bc3bbd7809..e9ddb39ef5 100755 --- a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh +++ b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh @@ -14,6 +14,12 @@ # no audit records, so --input-logs is not optional: without it the search returns 0 # records and every answer is "clean". # +# audit 4.0.3 takes a bare HH:MM:SS and rejects the output of date "+%x %T". It prints +# nothing and exits 0, so a window that holds records reads as empty. Measured on an +# enforcing el10 node: "-ts 10/21/2026 20:59:08" returned 0 records, "-ts 20:59:08" +# returned 22 and "-ts today" returned 4006. A window with no audit record at all is not a +# credible answer on a running node, so SEARCHED=0 is a usage error and not a clean result. +# # Usage: # selinux_avc_check.sh search and report # selinux_avc_check.sh --classify read raw records on stdin @@ -37,6 +43,11 @@ selinux_avc_report() [ -n "$since" ] || return 2 searched=$(ausearch --input-logs -ts "$since" --raw 2>/dev/null | grep -c '^type=') + if [ "$searched" -eq 0 ]; then + echo "SEARCHED=0 AVC=0 XCAT_AVC=0" + echo "no audit record since '$since'. ausearch takes a bare HH:MM:SS." >&2 + return 2 + fi denials=$(ausearch --input-logs -m AVC,USER_AVC -ts "$since" --raw 2>/dev/null) all=$(printf '%s\n' "$denials" | grep -c '^type=') kept=$(printf '%s\n' "$denials" | selinux_avc_classify) diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index eef22eb219..8f74f09e82 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -58,7 +58,7 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; date "+%x %T" > /tmp/selinux_mn_labels.start; true' +cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; date "+%H:%M:%S" > /tmp/selinux_mn_labels.start; true' check:rc==0 cmd:rpm -q xCAT-selinux check:rc==0 @@ -99,7 +99,7 @@ check:output=~^0$ cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_mn_labels.start)"' check:rc==0 check:output=~XCAT_AVC=0 -cmd:sh -c 'date "+%x %T" > /tmp/selinux_mn_control.start; sleep 1; chcon -t shadow_t /install/postscripts/xcatdsklspost' +cmd:sh -c 'date "+%H:%M:%S" > /tmp/selinux_mn_control.start; sleep 1; chcon -t shadow_t /install/postscripts/xcatdsklspost' check:rc==0 cmd:sh -c 'curl -s -o /dev/null -w "%{http_code}" http://localhost/install/postscripts/xcatdsklspost' check:rc==0 @@ -123,7 +123,7 @@ label:mn_only,selinux,restapi cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; date "+%x %T" > /tmp/selinux_restapi_avc.start; true' +cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; date "+%H:%M:%S" > /tmp/selinux_restapi_avc.start; true' check:rc==0 cmd:sh -c 'rpm -q mod_ssl || dnf install -y mod_ssl' check:rc==0 diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index 5450fb3312..a6c9a3ed23 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -5,7 +5,7 @@ os:Linux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%x %T" > /tmp/selinux_cn_diskful.start' +cmd:sh -c 'date "+%H:%M:%S" > /tmp/selinux_cn_diskful.start' check:rc==0 cmd:chdef -t node -o $$CN selinux=enforcing check:rc==0 diff --git a/xCAT-test/bats/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats index 8decd6a85e..bef27f69a0 100644 --- a/xCAT-test/bats/selinux_avc_check.bats +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -76,3 +76,10 @@ SSH_RECORD='type=AVC msg=audit(1759000002.333:444): avc: denied { siginh } for run "$(repo_path 'xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh')" [ "$status" -eq 2 ] } + +@test "a window with no audit record is a usage error, not a clean answer" { + run selinux_avc_report "01/01/1970 00:00:00" + [ "$status" -eq 2 ] + [[ "$output" == *"SEARCHED=0"* ]] + [[ "$output" == *"bare HH:MM:SS"* ]] +} From 745d7f4d198e04816e5942f36c67eff25dd233fd Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:04:35 -0300 Subject: [PATCH 72/91] fix(xcat-core): the policy omits three accesses an EL9 management node makes The policy was measured on EL10. An enforcing AlmaLinux 9.8 management node running the same bundle logged 38 denials in xcat_t that the EL10 node did not log at all. The domain is permissive, so nothing failed, but each one has to be granted before the domain can enforce. Three causes, all of them EL9 running ISC DHCP where EL10 runs Kea: - omshell reads /proc/sys/net/ipv4/ip_local_port_range before it opens the OMAPI socket, which is 9 read, 9 open, 9 getattr on sysctl_net_t and 8 dir search. makedhcp runs omshell on every ISC backend. kernel_read_net_sysctls covers it. - makedhcp asks systemd to start and query dhcpd.service, whose unit carries dhcpd_unit_file_t. The Kea units carry systemd_unit_file_t, which the policy already grants, so EL10 recorded nothing. - copycds loop-mounts the install DVD, and mount asks the kernel for the iso9660 and loop modules. kernel_request_load_module covers it. The module compiles against the EL9 and the EL10 policy headers. selinux_file_contexts.t keeps its 224 checks on EL10. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.te | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te index c555187053..5be39a605d 100644 --- a/xCAT-selinux/xcat.te +++ b/xCAT-selinux/xcat.te @@ -4,7 +4,7 @@ gen_require(` type httpd_t, httpd_sys_script_t, tftpdir_t, ntop_port_t; type rsync_t, shadow_t; type useradd_t, groupadd_t, public_content_t; - type named_zone_t, named_unit_file_t, systemd_unit_file_t; + type named_zone_t, named_unit_file_t, systemd_unit_file_t, dhcpd_unit_file_t; type auditd_etc_t, selinux_config_t, ldconfig_cache_t, setfiles_t, tmp_t; type device_t; attribute file_type; @@ -259,6 +259,18 @@ allow xcat_t named_unit_file_t:service { start status stop reload enable disable # denial was recorded for either: the audit window was empty while makedhcp # still reported "Failed to enable kea-dhcp-ddns". allow xcat_t systemd_unit_file_t:service { start status stop reload enable disable }; +# EL9 and earlier run ISC dhcpd, so makedhcp asks systemd for dhcpd.service. +# EL10 runs Kea, whose units carry systemd_unit_file_t, which is why the EL10 +# measurement showed no denial for this one. +allow xcat_t dhcpd_unit_file_t:service { start status stop reload enable disable }; + +# omshell reads /proc/sys/net/ipv4/ip_local_port_range before it opens the OMAPI +# socket. makedhcp runs it on every ISC backend. +kernel_read_net_sysctls(xcat_t) + +# copycds loop-mounts the install DVD, and mount asks the kernel for the +# iso9660 and loop modules. +kernel_request_load_module(xcat_t) # xcatd keeps its credentials under /etc/xcat and its socket under /run/xcat. manage_dirs_pattern(xcat_t, cert_t, cert_t) From cd75a9f820aff8aca6389ea0664ac2bf37a53a44 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:25:22 -0300 Subject: [PATCH 73/91] test(xcat-core): no case measures a common or overlay directory in a guest tree The published-name rules for an image root called rootimg end with two recursive entries, common(/.*)? and overlay(/.*)?. A recursive entry below the rootimg component matches a guest tree as well: with rootimgdir=/install/rootimg/common/compute, the guest file /install/rootimg/common/compute/rootimg/etc/shadow resolves to public_content_t, and so does a directory called common at the root of any guest tree. selinux_file_contexts.t covers neither shape. Add three case groups: an image root that holds a rootimg component in the middle, a guest tree that holds a common or an overlay directory at its own root, and the published files of such an image root. Each new path is measured in the lookup and in both relabel passes. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/native/selinux_file_contexts.t | 80 ++++++++++++++++-------- 1 file changed, 55 insertions(+), 25 deletions(-) diff --git a/xCAT-test/native/selinux_file_contexts.t b/xCAT-test/native/selinux_file_contexts.t index a54b5ce09b..5e4c3a3510 100644 --- a/xCAT-test/native/selinux_file_contexts.t +++ b/xCAT-test/native/selinux_file_contexts.t @@ -93,35 +93,59 @@ my @images = ( '/install/netboot/custom-image', '/install/custom/images/rhels9-compute', ); -my @guest = map { ("$_/rootimg/etc/shadow", "$_/rootimg/etc/passwd", - "$_/rootimg-statelite/etc/shadow") } @images; + +# rootimgdir is any path under /install, so an image root can carry a rootimg +# component in the MIDDLE. /install/netboot/rootimg/a/b/kernel is either a +# published kernel of the image root /install/netboot/rootimg/a/b, or a file +# inside a guest tree rooted at /install/netboot/rootimg. The two readings are +# the same path, so the rules keep the guest labels and leave everything in +# such a root alone, published files included. Hold that choice down, so a +# change of direction fails here instead of silently relabelling a guest. +my @custom_roots = ( + '/install/netboot/rootimg/rhels9/x86_64/compute', + '/install/rootimg/common/compute', + '/install/rootimg/overlay/compute', + '/install/rootimg-statelite/common/compute', + '/install/rootimg-statelite/overlay/compute', +); + +# A guest operating system can carry a directory called common or overlay at +# its own root. The path is the same as a published common or overlay of an +# image root called rootimg, so neither name has a rule and the guest keeps its +# labels. +my @guest_dirs = map { ("$_/rootimg/common", "$_/rootimg/overlay", + "$_/rootimg-statelite/common", "$_/rootimg-statelite/overlay") } @images; + +my @guest = ( + (map { ("$_/rootimg/etc/shadow", "$_/rootimg/etc/passwd", + "$_/rootimg-statelite/etc/shadow") } @images), + (map { ("$_/etc/shadow", "$_/usr/bin/sh") } @guest_dirs), + (map { ("$_/rootimg/etc/shadow", "$_/rootimg/etc/passwd", + "$_/rootimg-statelite/etc/shadow") } @custom_roots), +); + +my @published_names = qw(kernel initrd-stateless.gz initrd-statelite.gz + rootimg.cpio.gz rootimg.cpio.gz.sha256 rootimg.cpio.gz.metainfo + rootimg.tar.xz rootimg.sfs rootimg-statelite.gz); my @published = map { my $dir = $_; - map { "$dir/$_" } qw(kernel initrd-stateless.gz initrd-statelite.gz rootimg.cpio.gz - rootimg.cpio.gz.sha256 rootimg.cpio.gz.metainfo rootimg.tar.xz rootimg.sfs - rootimg-statelite.gz) + map { "$dir/$_" } @published_names; } @images; -foreach my $path (@guest) { +# A published file of a custom root keeps the label it had. That costs the +# netboot of that one osimage and is recoverable with restorecon. +my @unlabelled = map { + my $dir = $_; + map { "$dir/$_" } @published_names; +} @custom_roots; + +foreach my $path (@guest, @guest_dirs, @unlabelled) { is(lookup($path), '<>', "restorecon leaves $path alone"); } foreach my $path (@published, '/install', '/install/postscripts/xcatdsklspost') { is(lookup($path), 'public_content_t', "$path is public_content_t"); } -# rootimgdir is any path under /install, so a component called rootimg in the -# MIDDLE of an image root cannot be told from a guest tree rooted there: -# /install/netboot/rootimg/a/b/kernel is either a published kernel below an -# image root called .../rootimg/a/b, or a file inside a guest tree rooted at -# /install/netboot/rootimg. The rules keep the guest labels, which leaves the -# first reading unlabelled. Hold that choice down, so a change of direction -# fails here instead of silently relabelling a guest. -foreach my $path ('/install/netboot/rootimg/rhels9/x86_64/compute/kernel', - '/install/netboot/rootimg/rhels9/x86_64/compute/rootimg/etc/shadow') { - is(lookup($path), '<>', - "a rootimg component inside an image root keeps $path out of the relabel"); -} - # A guest file whose own name is a published name keeps its label: the rules # name the component directly below rootimg, not a name at any depth. foreach my $path (map { "/install/netboot/rhels9/x86_64/$_" } @@ -136,13 +160,19 @@ foreach my $path (map { "/install/netboot/rhels9/x86_64/$_" } my $mn = "$work/mn"; my %before; $before{$_} = 'shadow_t' foreach @guest; -$before{$_} = 'default_t' foreach @published; +$before{$_} = 'etc_t' foreach @guest_dirs; +$before{$_} = 'default_t' foreach @published, @unlabelled; +my %is_dir = map { $_ => 1 } @guest_dirs; foreach my $path (sort keys %before) { my $file = "$mn$path"; - (my $dir = $file) =~ s{/[^/]+$}{}; - make_path($dir); - open(my $fh, '>', $file) or die "$file: $!"; - close($fh); + if ($is_dir{$path}) { + make_path($file); + } else { + (my $dir = $file) =~ s{/[^/]+$}{}; + make_path($dir); + open(my $fh, '>', $file) or die "$file: $!"; + close($fh); + } run('setfattr', '-n', 'security.selinux', '-v', "system_u:object_r:$before{$path}:s0", $file); } @@ -168,7 +198,7 @@ sub label_of { foreach my $step ('install', 'upgrade') { install_module() if $step eq 'upgrade'; run('setfiles', '-F', '-r', $mn, $fc, "$mn/install"); - foreach my $path (@guest) { + foreach my $path (@guest, @guest_dirs, @unlabelled) { is(label_of($path), $before{$path}, "after the $step relabel $path keeps $before{$path}"); } foreach my $path (@published) { From fa703a5943de7f14c5f8f3f29fd59b44d7c97409 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:25:30 -0300 Subject: [PATCH 74/91] fix(xcat-core): restorecon relabels a guest tree below a common directory The published-name rules end with /install(/.*)?/rootimg(-statelite)?/common(/.*)? and the same entry for overlay. The trailing (/.*)? takes a whole subtree, so the entry matches a guest tree as well as a published directory. With rootimgdir=/install/rootimg/common/compute, the guest files rootimg/etc/shadow and rootimg-statelite/etc/shadow resolve to public_content_t, and so does a directory called common or overlay at the root of any guest tree. %posttrans runs restorecon -R /install, so an install or an upgrade of the package overwrites the labels of the guest operating system. A common or an overlay directory one component below a rootimg component has the same path as the same directory at the root of a guest tree, so no rule can keep one and leave the other. Remove both entries. The remaining entries each name one file and cannot take a tree with them. A published common or overlay of an image root called rootimg is left unlabeled, which restorecon over the image root repairs. selinux_file_contexts.t fails 360 of its 618 checks without this change, measured in a privileged almalinux:10 container on rome01. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-selinux/xcat.fc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index 733f7b14b0..da4486a506 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -45,5 +45,9 @@ /install(/.*)?/rootimg(-statelite)?/rootimgtree\.[^/]* -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/litefile\.csv -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/common\.filelist -- gen_context(system_u:object_r:public_content_t,s0) -/install(/.*)?/rootimg(-statelite)?/common(/.*)? gen_context(system_u:object_r:public_content_t,s0) -/install(/.*)?/rootimg(-statelite)?/overlay(/.*)? gen_context(system_u:object_r:public_content_t,s0) + +# There is no rule for a common or an overlay directory below the rootimg +# component. Such a rule must match a subtree, and a subtree under that name is +# the same path as a guest tree that has a directory called common or overlay at +# its own root, so the rule relabels the guest. Each entry above names one file +# and cannot take a tree with it. From 95127756f1efaf14dc9af3963a63172e3e922c41 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:27:38 -0300 Subject: [PATCH 75/91] test(xcat-core): no case compares the SELinux pages with the shipped policy Two pages describe SELinux, and both disagree with xCAT-selinux. The security page says the package defines no type and that xcatd runs in unconfined_service_t. The older page says a service node and a compute node are out of scope because xCAT does not select their mode, and the branch ships noderes.selinux. selinux_docs.t reads the permissive domains out of xcat.te and requires each page to name them, to call them permissive, and to leave out the two claims above. Nothing held the pages to the module before. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/selinux_docs.t | 54 +++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 xCAT-test/unit/selinux_docs.t diff --git a/xCAT-test/unit/selinux_docs.t b/xCAT-test/unit/selinux_docs.t new file mode 100644 index 0000000000..e180a5fe45 --- /dev/null +++ b/xCAT-test/unit/selinux_docs.t @@ -0,0 +1,54 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use File::Slurper qw(read_text); +use Test::More; + +# The SELinux pages and the policy module disagreed. The security page said the +# package defines no type and that xcatd runs in unconfined_service_t, while +# xcat.te declared two domains. Derive the domain set from the policy source, +# so a page cannot describe a module that is not shipped. +my $root = "$FindBin::Bin/../.."; + +my $te = read_text("$root/xCAT-selinux/xcat.te"); +my @permissive = sort($te =~ /^\s*permissive\s+(\w+)\s*;/mg); +is_deeply(\@permissive, [ 'xcat_image_t', 'xcat_t' ], + "xcat.te declares the permissive domains @permissive"); + +my @pages = ( + 'docs/source/advanced/security/selinux.rst', + 'docs/source/advanced/selinux/index.rst', +); +my %text; +foreach my $page (@pages) { + $text{$page} = read_text("$root/$page"); + ok(length($text{$page}) > 1000, "$page holds @{[length $text{$page}]} characters"); +} + +foreach my $page (@pages) { + foreach my $domain (@permissive) { + like($text{$page}, qr/\Q$domain\E/, "$page names $domain"); + } + like($text{$page}, qr/permissive/, "$page says the domains are permissive"); + + # xcatd enters xcat_t on the xcatd script. A page that still names the + # domain of an unconfined service describes the module before xcat_t. + unlike($text{$page}, qr/unconfined_service_t/, + "$page does not put an xCAT service in unconfined_service_t"); + unlike($text{$page}, qr/defines no type/, + "$page does not say the package defines no type"); +} + +# The branch ships noderes.selinux, so a page cannot place the nodes outside +# the scope of what xCAT decides. +my $modes = read_text("$root/perl-xCAT/xCAT/SELinux.pm"); +like($modes, qr/sub node_modes/, 'SELinux.pm resolves the mode of a node'); +foreach my $page (@pages) { + like($text{$page}, qr/noderes\.selinux/, "$page names noderes.selinux"); + unlike($text{$page}, qr/xCAT does not select their mode/, + "$page does not say xCAT leaves the mode of a node alone"); +} + +done_testing(); From c9210eb26e6efe8b64af653474069e39933938cf Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:27:46 -0300 Subject: [PATCH 76/91] docs(selinux): two pages describe a module that is not the one shipped The security page said xcatd runs in unconfined_service_t and that xCAT-selinux defines no type. The module defines xcat_t for xcatd and the client commands, and xcat_image_t for the image build, and declares both permissive. The older page placed a service node and a compute node outside the scope because xCAT does not select their mode, and the branch ships noderes.selinux and site.selinux. Both pages now state what the module does: the two permissive domains, the transitions to tftpd_t and chronyd_t for the services xCAT starts, the mode a node resolves, and the goal of an enforcing management node. The scope page also records that a published common or overlay directory of an image root called rootimg is unlabeled, for the same reason as a published kernel there. selinux_docs.t fails 6 of its 18 checks without this change, on rome01. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/security/selinux.rst | 22 ++++++++++++++-------- docs/source/advanced/selinux/index.rst | 16 +++++++++++++--- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/docs/source/advanced/security/selinux.rst b/docs/source/advanced/security/selinux.rst index 1cc97abf19..8cdb44d130 100644 --- a/docs/source/advanced/security/selinux.rst +++ b/docs/source/advanced/security/selinux.rst @@ -45,16 +45,22 @@ So ``mknetboot`` writes ``selinux=0`` for every stateless node, whatever ``xCAT::SELinux->netboot_supported`` is the one place that answers this question. -xCAT itself is not confined ---------------------------- +xCAT runs in two permissive domains +----------------------------------- -``xcatd``, ``in.tftpd``, ``kea-dhcp4`` and ``goconserver`` run in -``unconfined_service_t``. The ``xCAT-selinux`` package defines no type and confines -nothing. It carries the rules that let the CONFINED services of the OS reach the files -xCAT owns, for example ``httpd`` reading ``/tftpboot``. +``xCAT-selinux`` defines ``xcat_t`` for ``xcatd`` and the xCAT client commands, and +``xcat_image_t`` for the image build. The module declares both domains permissive, so +the kernel records an access that is outside the rules instead of refusing it. The host +policy stays enforcing. -So SELinux on an xCAT cluster constrains the OS services, not xCAT. Running xCAT with -SELinux enforcing is the goal; confining xCAT is not part of it. +The module also transitions the services xCAT starts itself to the stock domains: +``in.tftpd`` to ``tftpd_t`` and ``chronyd`` to ``chronyd_t``. And it grants the confined +services of the OS the access they need to the files xCAT owns, for example ``httpd`` +reading ``/tftpboot``. + +Running xCAT on an enforcing management node is the goal. A later release removes the +permissive declaration. See :doc:`SELinux ` for what each +domain holds, how a command enters it, and how to read the records the kernel writes. Setting the mode of a node -------------------------- diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 38036d0806..9aaf9877cc 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -7,8 +7,15 @@ installation does not change the SELinux mode of the machine. Scope ----- -This version covers the management node. A service node and a compute node are -out of scope: no run measures them, and xCAT does not select their mode. +The policy module covers the management node. It defines the domain of ``xcatd``, +of the client commands and of the image build, and it labels the files xCAT +owns. A service node and a compute node get no xCAT domain. + +They get a mode. ``noderes.selinux`` on the node, then the ``noderes.selinux`` +of its groups, then ``site.selinux`` decides the mode that the installer of a +diskful compute or service node configures. A stateless or statelite node gets +``selinux=0``, because its root carries no label. See +:doc:`SELinux ` for the table and for the switches. The two domains --------------- @@ -70,7 +77,10 @@ labels there, so an osimage whose ``rootimgdir`` has a directory called ``rootimg`` above the tree leaves its published kernel and initrd unlabeled, and ``httpd`` cannot serve them. Give such an osimage a ``rootimgdir`` with no ``rootimg`` component, or run ``restorecon`` over the image root after the -package is installed. +package is installed. A published ``common`` or ``overlay`` directory of an +image root called ``rootimg`` is unlabeled for the same reason: its path is +also the path of a ``common`` or ``overlay`` directory at the root of a guest +tree. The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit From ea658e280e34aa3eb23826e1fdd5569e3c8bcf3b Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:30:14 -0300 Subject: [PATCH 77/91] test(xcat-core): the xcatmn probe case throws away the output it checks xcatprobe_xcatmn_selinux runs the probe through grep -i selinux. grep keeps the lines that name SELinux and discards every other checkpoint, so the one CI failure of this case reported rc 1 with an empty output and said nothing about which checkpoint the probe stopped at. The second check, on the word FAIL, read that empty output and passed. probe_xcatmn_selinux_case.t requires the case to keep the whole output, to assert at least one pattern the output must hold, and to name the SELinux checkpoint in every pattern. It takes the marks of a checkpoint from probe_utils->send_msg, and requires each pattern to tell a passing checkpoint from a failing one. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/probe_xcatmn_selinux_case.t | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 xCAT-test/unit/probe_xcatmn_selinux_case.t diff --git a/xCAT-test/unit/probe_xcatmn_selinux_case.t b/xCAT-test/unit/probe_xcatmn_selinux_case.t new file mode 100644 index 0000000000..768e29e5bb --- /dev/null +++ b/xCAT-test/unit/probe_xcatmn_selinux_case.t @@ -0,0 +1,79 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +# Keep modules out of an installed /opt/xcat, so the checkout is what loads. +BEGIN { $ENV{XCATROOT} = '/nonexistent/xcatroot' } + +use Capture::Tiny qw(capture_stdout); +use File::Slurper qw(read_lines); +use FindBin; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-probe/lib/perl"; +use Test::More; + +require probe_utils; +like($INC{'probe_utils.pm'}, qr/\Q$FindBin::Bin\E/, 'probe_utils comes from this checkout'); + +# The case ran the probe through grep. ausearch is not involved here: grep kept +# the lines that name SELinux and discarded every other checkpoint, so the one +# CI failure reported an empty output and said nothing about the probe. The +# second check, on the word FAIL, then had nothing to read. +my %case; +my $name; +foreach my $line (read_lines("$FindBin::Bin/../autotest/testcase/probe/xcatmn")) { + $name = $1 if ($line =~ /^start:(\S+)/); + push @{ $case{$name}{cmd} }, $1 if ($line =~ /^cmd:(.+)/); + push @{ $case{$name}{check} }, $1 if ($line =~ /^check:(.+)/); +} +my $probe = $case{xcatprobe_xcatmn_selinux}; +ok($probe, 'the testcase file declares xcatprobe_xcatmn_selinux'); +my @cmds = @{ $probe->{cmd} || [] }; +my @checks = @{ $probe->{check} || [] }; +ok(scalar(@cmds) >= 1, "the case runs @{[scalar @cmds]} commands"); +ok(scalar(@checks) >= 1, "the case makes @{[scalar @checks]} checks"); + +foreach my $cmd (@cmds) { + unlike($cmd, qr/\|/, + "the case keeps the whole output of '$cmd', instead of filtering it"); +} + +my @patterns = map { /^output\s*[=!]~\s*(\S.*)/ ? $1 : () } @checks; +my @positive = map { /^output\s*=~\s*(\S.*)/ ? $1 : () } @checks; +ok(scalar(@positive) >= 1, + "the case asserts @{[scalar @positive]} patterns that the probe output must hold"); +foreach my $pattern (@patterns) { + like($pattern, qr/SELinux/, + "the pattern '$pattern' names the SELinux checkpoint, so another checkpoint cannot satisfy it"); +} + +# The subcommand marks each checkpoint through send_msg, and xcatprobe rewrites +# that mark as a right hand [ OK ] or [FAIL]. Take the subcommand marks by +# calling send_msg, so a change of format fails here. +my $checkpoint = 'Checking SELinux policy for xCAT...'; +my %mark; +foreach my $tag (qw(o f)) { + $mark{$tag} = capture_stdout { probe_utils->send_msg('stdout', $tag, $checkpoint) }; + chomp($mark{$tag}); +} +isnt($mark{o}, $mark{f}, + "send_msg marks an ok checkpoint '$mark{o}' apart from a failed one '$mark{f}'"); +like($mark{o}, qr/\QSELinux\E/, 'the ok mark carries the checkpoint text'); + +my %rendered = ( + ok => $checkpoint . (' ' x 39) . '[ OK ]', + failed => $checkpoint . (' ' x 39) . '[FAIL]', +); +foreach my $pattern (@positive) { + like($rendered{ok}, qr/$pattern/, "a passing SELinux checkpoint matches '$pattern'"); + unlike($rendered{failed}, qr/$pattern/, + "a failing SELinux checkpoint does not match '$pattern'"); +} +foreach my $pattern (map { /^output\s*!~\s*(\S.*)/ ? $1 : () } @checks) { + like($rendered{failed}, qr/$pattern/, + "a failing SELinux checkpoint matches the excluded pattern '$pattern'"); + unlike($rendered{ok}, qr/$pattern/, + "a passing SELinux checkpoint does not match the excluded pattern '$pattern'"); +} + +done_testing(); From 27fdca22a85a98ce0f899f867516fd81d6280a31 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:30:21 -0300 Subject: [PATCH 78/91] fix(xcat-test): the xcatmn probe case reports an empty output as a failure The case ran xcatprobe xcatmn through grep -i selinux and checked the rc of the pipeline. Nothing in the output named SELinux, so grep exited 1, the case failed with an empty output, and the log carries no checkpoint and no reason. The probe prints every checkpoint, so the diagnostics existed and the filter threw them away. The case now runs the probe with -H, which runs the checks on this node instead of dispatching them, and keeps the whole output. It asserts that the SELinux checkpoint is marked [ OK ] and is not marked [FAIL], which xcatprobe writes for a checkpoint that passes and one that fails. It no longer asserts the rc of the probe: a management node under test can report another checkpoint as a problem, and that is not this case. probe_xcatmn_selinux_case.t fails 3 of its 11 checks without this change, on rome01. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/probe/xcatmn | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/xCAT-test/autotest/testcase/probe/xcatmn b/xCAT-test/autotest/testcase/probe/xcatmn index 6dae5014df..fc4ac30736 100644 --- a/xCAT-test/autotest/testcase/probe/xcatmn +++ b/xCAT-test/autotest/testcase/probe/xcatmn @@ -1,7 +1,7 @@ start:xcatprobe_xcatmn_selinux -description:To test if xcatprobe xcatmn reports the SELinux mode of the management node, and does not report that mode as a failure. This case must run in xcat mn +description:To test if xcatprobe xcatmn reports the SELinux policy of the management node, and does not report it as a problem. The output is not filtered, so a failure of any checkpoint is in the log. -H runs the checks on this node, instead of dispatching them. This case must run in xcat mn label:mn_only,ci_test -cmd:xcatprobe xcatmn 2>&1 | grep -i selinux -check:rc==0 -check:output!~FAIL +cmd:xcatprobe xcatmn -H 2>&1 +check:output=~Checking SELinux policy for xCAT\.\.\..*\[ OK \] +check:output!~Checking SELinux policy for xCAT\.\.\..*\[FAIL\] end From 830b731143f4f965c7b2827032ab98a99ba127e8 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:35:20 -0300 Subject: [PATCH 79/91] test(xcat-test): no check tells a quiet audit window from a broken search selinux_avc_check.sh refuses a window that holds no audit record, and calls it a usage error. On a quiet node that answer is wrong: the body of selinux_mn_labels runs inside one second, so an el9 run of the case failed with SEARCHED=0 AVC=0 XCAT_AVC=0 while the search was working. The guard has no way to tell the two apart, and no check names which guard fires. The time window has a second defect that no check covers. ausearch -ts has one second of granularity, so the denials the positive control of selinux_mn_labels creates on purpose land in the window of the case that runs next: selinux_restapi_avc failed with SEARCHED=50 AVC=6 XCAT_AVC=2, and both kept records were the control's httpd_t getattr on /install/postscripts/xcatdsklspost. selinux_avc_check.bats now requires a checkpoint interface, --init and --since, and requires the count to refuse an ausearch error message while it accepts an empty read. It also requires the time window to consult today before it calls an empty window a usage error. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/bats/selinux_avc_check.bats | 56 ++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/xCAT-test/bats/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats index bef27f69a0..060ec143b0 100644 --- a/xCAT-test/bats/selinux_avc_check.bats +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -77,9 +77,61 @@ SSH_RECORD='type=AVC msg=audit(1759000002.333:444): avc: denied { siginh } for [ "$status" -eq 2 ] } -@test "a window with no audit record is a usage error, not a clean answer" { +@test "the report refuses a checkpoint call with no file" { + run selinux_avc_since "" + [ "$status" -eq 2 ] + run selinux_avc_init "" + [ "$status" -eq 2 ] +} + +@test "an empty window with nothing today is a usage error, not a clean answer" { run selinux_avc_report "01/01/1970 00:00:00" [ "$status" -eq 2 ] [[ "$output" == *"SEARCHED=0"* ]] - [[ "$output" == *"bare HH:MM:SS"* ]] + [[ "$output" == *"none today"* ]] +} + +# The guard the checkpoint form needs. ausearch answers with records, with +# '', or with nothing once it has read to the end of the log. An +# error message is none of those, and counting it reports a clean window. +@test "an ausearch error message is not a clean window" { + run selinux_avc_count "Invalid start time (10/21/2026 20:59:08). Hour, Minute, and Second are required." + [ "$status" -eq 2 ] + [[ "$output" == *"neither a record nor"* ]] +} + +@test "a log read to its end is a clean window" { + run selinux_avc_count "" + [ "$status" -eq 0 ] + [ "$output" = "AVC=0 XCAT_AVC=0" ] + run selinux_avc_count "" + [ "$status" -eq 0 ] + [ "$output" = "AVC=0 XCAT_AVC=0" ] +} + +@test "an xCAT denial after the checkpoint is kept" { + ausearch() { printf '%s\n' "$XCAT_RECORD"; } + run selinux_avc_since /tmp/selinux_avc_check_bats.ck + [ "$status" -eq 1 ] + [[ "$output" == *"AVC=1 XCAT_AVC=1"* ]] + [[ "$output" == *'/tftpboot/xcat/xnba.kpxe'* ]] +} + +@test "noise after the checkpoint is counted and not kept" { + ausearch() { printf '%s\n' "$TIMER_RECORD"; } + run selinux_avc_since /tmp/selinux_avc_check_bats.ck + [ "$status" -eq 0 ] + [ "$output" = "AVC=1 XCAT_AVC=0" ] +} + +# A checkpoint that reads no record is not a quiet node: ausearch writes no +# checkpoint file, so the next call reads the whole log. +@test "the baseline counts the records the checkpoint consumed" { + ausearch() { printf '%s\n' "$TIMER_RECORD" "$SSH_RECORD"; } + run selinux_avc_init /tmp/selinux_avc_check_bats.ck + [ "$status" -eq 0 ] + [ "$output" = "BASELINE=2" ] + ausearch() { printf '%s\n' ""; } + run selinux_avc_init /tmp/selinux_avc_check_bats.ck + [ "$output" = "BASELINE=0" ] } From cb4e7bc09b57514b935849de569b0e26fb53d63c Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:35:31 -0300 Subject: [PATCH 80/91] fix(xcat-test): a quiet audit window fails, and a control leaks into the next case The SELinux cases marked their audit window with date "+%H:%M:%S" and gave it to selinux_avc_check.sh. Two failures follow from the time window. The body of selinux_mn_labels runs inside one second, so an el9 run reported SEARCHED=0 and the guard called a quiet node a usage error. And ausearch -ts has one second of granularity, so the denials that the positive control of selinux_mn_labels creates on purpose landed in the window of selinux_restapi_avc, which failed with XCAT_AVC=2 on two httpd_t getattr records it did not cause. selinux_avc_check.sh takes a checkpoint file: --init consumes the records written so far and prints BASELINE, --since reports the denials after that point. A checkpoint is an offset, so an empty answer has one meaning and two cases cannot read one record. Each case opens its own checkpoint, and the positive control opens a second one, which also removes the sleep 1 that the granularity needed. The count refuses an answer that is neither a record nor '', so an ausearch error message cannot read as a clean window. The -ts form stays for the keywords boot and today, and now asks for today's records before it calls an empty window a usage error. /xcatpost is reported and no longer asserted on a compute or service node. The kickstart relabel runs in %post, the xCAT post scripts write that tree at the first boot, and the node carries no xCAT-selinux, so a clean restorecon -Rnv there is not what the design promises. selinux_avc_check.bats fails 7 of its 15 checks without this change, on rome01. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .../testcase/commoncmd/selinux_avc_check.sh | 96 +++++++++++++++---- xCAT-test/autotest/testcase/selinux/cases0 | 25 +++-- xCAT-test/autotest/testcase/selinux/cases1 | 19 ++-- 3 files changed, 105 insertions(+), 35 deletions(-) diff --git a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh index e9ddb39ef5..ffe4357bd1 100755 --- a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh +++ b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh @@ -14,18 +14,26 @@ # no audit records, so --input-logs is not optional: without it the search returns 0 # records and every answer is "clean". # -# audit 4.0.3 takes a bare HH:MM:SS and rejects the output of date "+%x %T". It prints -# nothing and exits 0, so a window that holds records reads as empty. Measured on an -# enforcing el10 node: "-ts 10/21/2026 20:59:08" returned 0 records, "-ts 20:59:08" -# returned 22 and "-ts today" returned 4006. A window with no audit record at all is not a -# credible answer on a running node, so SEARCHED=0 is a usage error and not a clean result. +# A time window cannot say whether an empty answer means a quiet node or a broken +# search, and -ts has one second of granularity, so a denial in the second a case starts +# lands in that case's window. A checkpoint file is an offset: nothing since the +# checkpoint has one meaning, there is no format to reject, and two cases cannot share a +# record. Prefer --init and --since. The -ts form stays for the keywords boot and today, +# where the window is not a case boundary. +# +# audit 4.0.3 rejects the output of date "+%x %T" and names the format on stderr, which +# the pipeline below discards, so a window that holds records reads as empty. Measured on +# an enforcing el10 node: "-ts 10/21/2026 20:59:08" returned 0 records, "-ts 20:59:08" +# returned 22 and "-ts today" returned 4006. # # Usage: -# selinux_avc_check.sh search and report +# selinux_avc_check.sh --init start a window, print the records it read +# selinux_avc_check.sh --since report the denials after that window +# selinux_avc_check.sh search a time window and report # selinux_avc_check.sh --classify read raw records on stdin # -# Prints: SEARCHED= AVC= XCAT_AVC= -# then the records it kept. +# Prints: BASELINE= for --init. AVC= XCAT_AVC= for a +# report, then the records it kept. The -ts form adds SEARCHED=. # Exits: 0 when it kept none, 1 when it kept any, 2 on a usage error. # Subjects: the programs xCAT runs. Objects: the directories xCAT owns. @@ -37,6 +45,55 @@ selinux_avc_classify() grep -E "(comm|exe)=\"[^\"]*(${XCAT_AVC_COMM})[^\"]*\"|(path|name)=\"[^\"]*(${XCAT_AVC_PATH})" } +# Report the denials ausearch answered with. An error message is not a clean window: +# ausearch prints the records, or '', or nothing at all when it has read to +# the end of the log, and anything else is a failure of the search. +selinux_avc_count() +{ + denials=$1 + noise=$(printf '%s\n' "$denials" | grep -v -e '^type=' -e '^$' -e '^$') + if [ -n "$noise" ]; then + echo "AVC=? XCAT_AVC=?" + echo "ausearch answered neither a record nor '': $noise" >&2 + return 2 + fi + + all=$(printf '%s\n' "$denials" | grep -c '^type=') + kept=$(printf '%s\n' "$denials" | selinux_avc_classify) + ours=$(printf '%s\n' "$kept" | grep -c '^type=') + + echo "AVC=$all XCAT_AVC=$ours" + [ "$ours" -eq 0 ] && return 0 + printf '%s\n' "$kept" + return 1 +} + +# Consume every record written so far, so the checkpoint names this moment. BASELINE +# counts them: on a running node a zero means the search reads nothing, not that the node +# is quiet, and the checkpoint file is then not written. +selinux_avc_init() +{ + checkpoint=$1 + [ -n "$checkpoint" ] || return 2 + + rm -f "$checkpoint" + records=$(ausearch --input-logs --checkpoint "$checkpoint" -ts today --raw 2>&1 \ + | grep -c '^type=') + echo "BASELINE=$records" + return 0 +} + +selinux_avc_since() +{ + checkpoint=$1 + [ -n "$checkpoint" ] || return 2 + + selinux_avc_count "$(ausearch --input-logs -m AVC,USER_AVC \ + --checkpoint "$checkpoint" --raw 2>&1)" +} + +# The -ts form keeps the two-query discriminator: an empty narrow window with records +# today is a quiet node, an empty window in both is a search that reads nothing. selinux_avc_report() { since=$1 @@ -44,26 +101,25 @@ selinux_avc_report() searched=$(ausearch --input-logs -ts "$since" --raw 2>/dev/null | grep -c '^type=') if [ "$searched" -eq 0 ]; then - echo "SEARCHED=0 AVC=0 XCAT_AVC=0" - echo "no audit record since '$since'. ausearch takes a bare HH:MM:SS." >&2 - return 2 + today=$(ausearch --input-logs -ts today --raw 2>/dev/null | grep -c '^type=') + if [ "$today" -eq 0 ]; then + echo "SEARCHED=0 AVC=0 XCAT_AVC=0" + echo "no audit record since '$since' and none today. ausearch takes a bare HH:MM:SS." >&2 + return 2 + fi fi - denials=$(ausearch --input-logs -m AVC,USER_AVC -ts "$since" --raw 2>/dev/null) - all=$(printf '%s\n' "$denials" | grep -c '^type=') - kept=$(printf '%s\n' "$denials" | selinux_avc_classify) - ours=$(printf '%s\n' "$kept" | grep -c '^type=') - echo "SEARCHED=$searched AVC=$all XCAT_AVC=$ours" - [ "$ours" -eq 0 ] && return 0 - printf '%s\n' "$kept" - return 1 + echo "SEARCHED=$searched" + selinux_avc_count "$(ausearch --input-logs -m AVC,USER_AVC -ts "$since" --raw 2>&1)" } # Sourced by the bats test, which calls the functions directly. if [ "$(basename "$0")" = selinux_avc_check.sh ]; then case $1 in --classify) selinux_avc_classify ;; - '') echo "usage: $0 " >&2; exit 2 ;; + --init) selinux_avc_init "$2" ;; + --since) selinux_avc_since "$2" ;; + '') echo "usage: $0 --init|--since | " >&2; exit 2 ;; *) selinux_avc_report "$1" ;; esac fi diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 index 8f74f09e82..ebf95660ea 100644 --- a/xCAT-test/autotest/testcase/selinux/cases0 +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -58,8 +58,11 @@ label:mn_only,selinux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; date "+%H:%M:%S" > /tmp/selinux_mn_labels.start; true' +cmd:sh -c 'rm -f /tmp/selinux_mn_labels.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_mn_labels.ck -ts today > /dev/null 2>&1; true' check:rc==0 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --init /tmp/selinux_mn_labels.avcck' +check:rc==0 +check:output=~BASELINE=[1-9] cmd:rpm -q xCAT-selinux check:rc==0 cmd:sh -c 'semodule -l | grep -x -E "xcat([[:space:]].*)?"' @@ -96,15 +99,18 @@ check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_mn_labels.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_mn_labels.start)"' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --since /tmp/selinux_mn_labels.avcck' check:rc==0 check:output=~XCAT_AVC=0 -cmd:sh -c 'date "+%H:%M:%S" > /tmp/selinux_mn_control.start; sleep 1; chcon -t shadow_t /install/postscripts/xcatdsklspost' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --init /tmp/selinux_mn_control.avcck' +check:rc==0 +check:output=~BASELINE=[1-9] +cmd:chcon -t shadow_t /install/postscripts/xcatdsklspost check:rc==0 cmd:sh -c 'curl -s -o /dev/null -w "%{http_code}" http://localhost/install/postscripts/xcatdsklspost' check:rc==0 check:output=~403 -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_mn_control.start)"' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --since /tmp/selinux_mn_control.avcck' check:rc==1 check:output=~XCAT_AVC=[1-9] cmd:restorecon -F /install/postscripts/xcatdsklspost @@ -114,7 +120,7 @@ check:rc==0 check:output=~:public_content_t: cmd:sh -c 'curl -s -f -o /dev/null http://localhost/install/postscripts/xcatdsklspost' check:rc==0 -cmd:rm -f /tmp/selinux_mn_labels.start /tmp/selinux_mn_control.start /tmp/selinux_mn_labels.ck /tmp/selinux_mn_labels.avc +cmd:rm -f /tmp/selinux_mn_labels.ck /tmp/selinux_mn_labels.avc /tmp/selinux_mn_labels.avcck /tmp/selinux_mn_control.avcck end start:selinux_restapi_avc @@ -123,8 +129,11 @@ label:mn_only,selinux,restapi cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; date "+%H:%M:%S" > /tmp/selinux_restapi_avc.start; true' +cmd:sh -c 'rm -f /tmp/selinux_restapi_avc.ck; ausearch --input-logs -m AVC,USER_AVC --checkpoint /tmp/selinux_restapi_avc.ck -ts today > /dev/null 2>&1; true' check:rc==0 +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --init /tmp/selinux_restapi_avc.avcck' +check:rc==0 +check:output=~BASELINE=[1-9] cmd:sh -c 'rpm -q mod_ssl || dnf install -y mod_ssl' check:rc==0 cmd:systemctl restart httpd @@ -139,8 +148,8 @@ check:rc==0 cmd:sh -c 'grep -F "permissive=0" /tmp/selinux_restapi_avc.avc | wc -l' check:rc==0 check:output=~^0$ -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_restapi_avc.start)"' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --since /tmp/selinux_restapi_avc.avcck' check:rc==0 check:output=~XCAT_AVC=0 -cmd:rm -f /tmp/selinux_restapi_avc.start /tmp/selinux_restapi_avc.ck /tmp/selinux_restapi_avc.avc +cmd:rm -f /tmp/selinux_restapi_avc.ck /tmp/selinux_restapi_avc.avc /tmp/selinux_restapi_avc.avcck end diff --git a/xCAT-test/autotest/testcase/selinux/cases1 b/xCAT-test/autotest/testcase/selinux/cases1 index a6c9a3ed23..defdf7c18c 100644 --- a/xCAT-test/autotest/testcase/selinux/cases1 +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -1,12 +1,13 @@ start:selinux_cn_diskful_enforcing -description:on an enforcing management node, a diskful compute node with noderes.selinux=enforcing boots enforcing, with correct labels and no denial +description:on an enforcing management node, a diskful compute node with noderes.selinux=enforcing boots enforcing, with correct labels and no denial. The labels of /xcatpost are reported and not asserted: the kickstart relabel runs in %post, the xCAT post scripts write that tree at the first boot, and the node carries no xCAT-selinux label:selinux,provision os:Linux cmd:getenforce check:rc==0 check:output=~^Enforcing$ -cmd:sh -c 'date "+%H:%M:%S" > /tmp/selinux_cn_diskful.start' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --init /tmp/selinux_cn_diskful.avcck' check:rc==0 +check:output=~BASELINE=[1-9] cmd:chdef -t node -o $$CN selinux=enforcing check:rc==0 cmd:/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/retry_install.sh $$CN __GETNODEATTR($$CN,os)__-__GETNODEATTR($$CN,arch)__-install-compute @@ -23,9 +24,11 @@ check:rc==0 check:output=~ssh_home_t check:output!~default_t check:output!~unlabeled_t -cmd:xdsh $$CN "restorecon -Rnv /xcatpost /opt/xcat /root /etc/ssh /var/log/xcat" +cmd:xdsh $$CN "restorecon -Rnv /opt/xcat /root /etc/ssh /var/log/xcat" check:rc==0 check:output!~Would relabel +cmd:xdsh $$CN "restorecon -Rnv /xcatpost; true" +check:rc==0 cmd:xdcp $$CN /opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh /tmp/ check:rc==0 cmd:xdsh $$CN "sh /tmp/selinux_avc_check.sh boot" @@ -33,12 +36,12 @@ check:rc==0 check:output=~XCAT_AVC=0 cmd:xdsh $$CN "rm -f /tmp/selinux_avc_check.sh" check:rc==0 -cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh "$(cat /tmp/selinux_cn_diskful.start)"' +cmd:sh -c '/opt/xcat/share/xcat/tools/autotest/testcase/commoncmd/selinux_avc_check.sh --since /tmp/selinux_cn_diskful.avcck' check:rc==0 check:output=~XCAT_AVC=0 cmd:chdef -t node -o $$CN selinux= check:rc==0 -cmd:rm -f /tmp/selinux_cn_diskful.start +cmd:rm -f /tmp/selinux_cn_diskful.avcck end start:selinux_cn_diskless_disabled_by_design @@ -106,7 +109,7 @@ cmd:rm -f /tmp/selinux_site.orig end start:selinux_sn_enforcing -description:in a hierarchical cluster, the service node runs SELinux enforcing with the xCAT labels in place and no xCAT denial since boot +description:in a hierarchical cluster, the service node runs SELinux enforcing with the xCAT labels in place and no xCAT denial since boot. The labels of /xcatpost are reported and not asserted, as on a compute node label:selinux,sn_diskful os:rhels cmd:getenforce @@ -126,9 +129,11 @@ cmd:xdsh $$SN "ls -dZ /install /tftpboot /opt/xcat /xcatpost" check:rc==0 check:output!~unlabeled_t check:output!~default_t -cmd:xdsh $$SN "restorecon -Rnv /xcatpost /opt/xcat /etc/xcat /var/log/xcat" +cmd:xdsh $$SN "restorecon -Rnv /opt/xcat /etc/xcat /var/log/xcat" check:rc==0 check:output!~Would relabel +cmd:xdsh $$SN "restorecon -Rnv /xcatpost; true" +check:rc==0 cmd:xdsh $$SN "systemctl is-active xcatd" check:rc==0 check:output=~active From 45ebeacab8b1760b295b5d3ca4e8cf0267d64259 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:53:51 -0300 Subject: [PATCH 81/91] docs(selinux): the page says a path left out of the relabel is unlabeled A file context of <> stops restorecon changing the label. It does not clear it. A tree that genimage creates under an image root that is already public_content_t inherits that type, measured on an enforcing el10 host: mkdir -p rootimg/common/sub under a public_content_t parent gives every new component public_content_t, and the same tree under a default_t parent gives default_t. Say what the label is, and name the case that costs something: a tree older than the package keeps default_t, and restorecon -RF over the image root sets it. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 9aaf9877cc..f9d7362909 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -78,9 +78,15 @@ labels there, so an osimage whose ``rootimgdir`` has a directory called and ``httpd`` cannot serve them. Give such an osimage a ``rootimgdir`` with no ``rootimg`` component, or run ``restorecon`` over the image root after the package is installed. A published ``common`` or ``overlay`` directory of an -image root called ``rootimg`` is unlabeled for the same reason: its path is -also the path of a ``common`` or ``overlay`` directory at the root of a guest -tree. +image root called ``rootimg`` is left out for the same reason: its path is also +the path of a ``common`` or ``overlay`` directory at the root of a guest tree. + +A path the file contexts leave out keeps the label it has. ``restorecon`` does +not change it and does not clear it. A tree that ``genimage`` creates under an +image root that is already ``public_content_t`` inherits that type, so the two +directories above cost nothing in that case. A tree that is older than the +package keeps ``default_t``, and ``restorecon -RF`` over the image root sets +it. The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit From 6f578741afeb120603bfbe9e5621d7143c5fb935 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:03:44 -0300 Subject: [PATCH 82/91] fix(xcat-core): the comment says an unlabeled kernel stops netboot, and it does not The file contexts leave the published kernel of a middle-rootimg image root out of the relabel. The comment and the SELinux page read that as the kernel being unlabeled, httpd refusing to serve it, and that osimage losing netboot, with restorecon as the repair. Three of those four claims are wrong. Measured. An entry of <> keeps the label a path has: restorecon -R, restorecon -RF and setfiles -F all left a kernel at default_t, while the same setfiles call relabeled a path that has a rule. A new file inherits the type of its directory, so a kernel that genimage writes into an image root already made public_content_t is public_content_t. In the policy with the xcat module loaded, httpd_t holds one allow rule to read public_content_t and none for default_t. So the ordinary case serves and netboot works, and restorecon is not the repair for the case that does not: chcon -R -t public_content_t over the image root is, and a later relabel leaves that value alone. selinux_file_contexts.t now starts half the custom roots at public_content_t, which is what genimage produces, and half at default_t, and requires each to keep its own type. It fails 324 of its 618 checks against the previous xcat.fc. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 32 ++++++++++++++---------- xCAT-selinux/xcat.fc | 12 +++++---- xCAT-test/native/selinux_file_contexts.t | 28 ++++++++++++++------- 3 files changed, 45 insertions(+), 27 deletions(-) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index f9d7362909..7189d199a2 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -72,21 +72,27 @@ file it points to. ``/usr/sbin/xcatd`` is a symlink, and ``execve`` resolves it, so the context belongs to the file in ``/opt/xcat``. A rootimg component in the middle of an image root is ambiguous, because -``rootimgdir`` is any path under ``/install``. The file contexts keep the guest -labels there, so an osimage whose ``rootimgdir`` has a directory called -``rootimg`` above the tree leaves its published kernel and initrd unlabeled, -and ``httpd`` cannot serve them. Give such an osimage a ``rootimgdir`` with no -``rootimg`` component, or run ``restorecon`` over the image root after the -package is installed. A published ``common`` or ``overlay`` directory of an -image root called ``rootimg`` is left out for the same reason: its path is also -the path of a ``common`` or ``overlay`` directory at the root of a guest tree. +``rootimgdir`` is any path under ``/install``. The file contexts leave the +published kernel and initrd of such an image root out of the relabel, so that +they cannot take the guest labels with them. A published ``common`` or +``overlay`` directory of an image root called ``rootimg`` is left out for the +same reason: its path is also the path of a ``common`` or ``overlay`` +directory at the root of a guest tree. A path the file contexts leave out keeps the label it has. ``restorecon`` does -not change it and does not clear it. A tree that ``genimage`` creates under an -image root that is already ``public_content_t`` inherits that type, so the two -directories above cost nothing in that case. A tree that is older than the -package keeps ``default_t``, and ``restorecon -RF`` over the image root sets -it. +not change it and does not clear it. ``genimage`` writes into an image root +that ``restorecon`` already made ``public_content_t``, and a new file inherits +the type of its directory, so the kernel is ``public_content_t`` and ``httpd`` +serves it. Netboot works. + +The cost is a path that already carries another type, from before the package +was installed or from a ``chcon``. It keeps that type, and ``restorecon`` over +``/install`` cannot repair it, with or without ``-F``: there is no context to +apply. Set it directly:: + + chcon -R -t public_content_t /install/netboot/rootimg/rhels9/x86_64/compute + +A later ``restorecon`` leaves that value alone, so the repair holds. The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index da4486a506..cb637372c6 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -32,11 +32,13 @@ # A rootimg component in the MIDDLE of an image root stays ambiguous, because # rootimgdir is any path: /install/netboot/rootimg/a/b/kernel is either a # published kernel of the image root /install/netboot/rootimg/a/b, or a file -# inside a guest tree rooted at /install/netboot/rootimg. These rules keep the -# guest labels, so that layout leaves the published kernel unlabeled and httpd -# cannot serve it, which stops netboot for that one osimage. Losing a boot file -# of a named layout is recoverable with restorecon; relabeling a guest -# operating system is not. +# inside a guest tree rooted at /install/netboot/rootimg. +# +# An entry of <> keeps whatever label the path has. It does not clear one. +# genimage creates such a kernel under an image root that restorecon already +# made public_content_t, so the kernel inherits that type and httpd serves it. +# A path that carries another type keeps it, and no restorecon repairs that: +# chcon -R -t public_content_t over the image root does. /install(/.*)?/rootimg(-statelite)?/kernel -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/hypervisor -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/initrd[^/]* -- gen_context(system_u:object_r:public_content_t,s0) diff --git a/xCAT-test/native/selinux_file_contexts.t b/xCAT-test/native/selinux_file_contexts.t index 5e4c3a3510..44bea1c0ce 100644 --- a/xCAT-test/native/selinux_file_contexts.t +++ b/xCAT-test/native/selinux_file_contexts.t @@ -132,14 +132,23 @@ my @published = map { map { "$dir/$_" } @published_names; } @images; -# A published file of a custom root keeps the label it had. That costs the -# netboot of that one osimage and is recoverable with restorecon. -my @unlabelled = map { - my $dir = $_; - map { "$dir/$_" } @published_names; -} @custom_roots; +# A published file of a custom root keeps the label it had, whichever it is. +# genimage writes into an image root that restorecon already made +# public_content_t, so the file inherits that type and httpd serves it. A file +# that carries another type keeps it, and no relabel pass repairs that. +# Half the roots start public_content_t, which is what genimage produces, and +# half start default_t, which is a tree older than the package. +my (@custom_published, %custom_before); +foreach my $i (0 .. $#custom_roots) { + my $type = $i % 2 ? 'default_t' : 'public_content_t'; + foreach my $name (@published_names) { + my $path = "$custom_roots[$i]/$name"; + push @custom_published, $path; + $custom_before{$path} = $type; + } +} -foreach my $path (@guest, @guest_dirs, @unlabelled) { +foreach my $path (@guest, @guest_dirs, @custom_published) { is(lookup($path), '<>', "restorecon leaves $path alone"); } foreach my $path (@published, '/install', '/install/postscripts/xcatdsklspost') { @@ -161,7 +170,8 @@ my $mn = "$work/mn"; my %before; $before{$_} = 'shadow_t' foreach @guest; $before{$_} = 'etc_t' foreach @guest_dirs; -$before{$_} = 'default_t' foreach @published, @unlabelled; +$before{$_} = 'default_t' foreach @published; +$before{$_} = $custom_before{$_} foreach @custom_published; my %is_dir = map { $_ => 1 } @guest_dirs; foreach my $path (sort keys %before) { my $file = "$mn$path"; @@ -198,7 +208,7 @@ sub label_of { foreach my $step ('install', 'upgrade') { install_module() if $step eq 'upgrade'; run('setfiles', '-F', '-r', $mn, $fc, "$mn/install"); - foreach my $path (@guest, @guest_dirs, @unlabelled) { + foreach my $path (@guest, @guest_dirs, @custom_published) { is(label_of($path), $before{$path}, "after the $step relabel $path keeps $before{$path}"); } foreach my $path (@published) { From f38418bd753bd97ca10ed43fd7ed161e32bfe0e0 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:49:37 -0300 Subject: [PATCH 83/91] test(xcat-probe): the probe case measures a checkpoint line the test wrote itself xcatprobe_xcatmn_selinux asserts the text of the SELinux checkpoint, and probe_xcatmn_selinux_case.t built that line by hand. The line xcatprobe prints in the GitHub Actions container carries no text, so the test passed while the case failed. xcatprobe held the layout in format_cmd_output, which no test can call. This moves the layout to probe_format and leaves xcatprobe the printing. The rendering is unchanged at every width: an identical column of output for widths 7, 40, 79, 80, 120, 121 and 200, truncated and wrapped, with and without colour. The test now renders the checkpoint through probe_format at the width the container gives, and it fails here. screen_width returns 0 for a terminal 'tput cols' cannot measure, the message is cut to the empty string, and three assertions read '[ OK ]' where they expect the checkpoint text. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-probe/lib/perl/probe_format.pm | 120 ++++++++++++++++++ xCAT-probe/xcatprobe | 134 ++++++--------------- xCAT-test/unit/probe_xcatmn_selinux_case.t | 17 ++- 3 files changed, 173 insertions(+), 98 deletions(-) create mode 100644 xCAT-probe/lib/perl/probe_format.pm diff --git a/xCAT-probe/lib/perl/probe_format.pm b/xCAT-probe/lib/perl/probe_format.pm new file mode 100644 index 0000000000..585bd52991 --- /dev/null +++ b/xCAT-probe/lib/perl/probe_format.pm @@ -0,0 +1,120 @@ +# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html +package probe_format; + +use strict; +use warnings; + +my $DESIRED_WIDTH = 120; +my $DEFAULT_WIDTH = 80; +my $FLAG_WIDTH = 6; + +#----------------------------------- + +=head3 screen_width + + Descriptions: + Return the number of columns to format a message in. + Arguments: + raw: the output of 'tput cols', or undef when there is no terminal + Returns: + the column count + +=cut + +#----------------------------------- +sub screen_width { + my ($raw) = @_; + + return $DEFAULT_WIDTH unless (defined($raw)); + return $raw =~ /(\d+)/ ? $1 + 0 : 0; +} + +#----------------------------------- + +=head3 render + + Descriptions: + Lay out one message line of a probe subcommand. + Arguments: + line: the line the subcommand printed, "[]:" + fullmsg: true to wrap a long message, false to truncate it + screenwidth: the column count from screen_width() + Returns: + (lines, mark). lines is an array reference. Print every line but the + last with a newline. mark is what follows the last line: undef when + the line carries no flag, and otherwise the mark to print, which + already holds its newline. + +=cut + +#----------------------------------- +sub render { + my ($line, $fullmsg, $screenwidth) = @_; + + my $msg = $line; + my $flag; + if ($line =~ /\[(\w+)\]\s*:(.+)/) { + $flag = $1; + $msg = $2; + } + + $msg =~ s/\t/ /g; + my $maxlen = ($screenwidth > $DESIRED_WIDTH ? $DESIRED_WIDTH : $screenwidth); + + my @finalmsg = (); + my $msglen = length($msg); + if ($msglen <= $maxlen) { + if (!$fullmsg && $flag) { + my $leftspace = $maxlen - length($msg); + if ($leftspace < $FLAG_WIDTH) { + $msg = substr($msg, 0, $maxlen - $FLAG_WIDTH); + $msg =~ s/(.*).../$1\.\.\./g; + } + } + push @finalmsg, $msg; + } else { + my $head = 0; + my $tail = $maxlen; + while ($head < $msglen) { + push @finalmsg, substr($msg, $head, ($tail - $head)); + if (!$fullmsg) { + if ($flag) { + $finalmsg[0] =~ s/(.*).........$/$1\.\.\./g; + } else { + $finalmsg[0] =~ s/(.*)...$/$1\.\.\./g; + } + last; + } + $head = $tail; + $tail = $head + ($maxlen <= ($msglen - $tail) ? $maxlen : ($msglen - $tail)); + } + } + + return (\@finalmsg, undef) unless ($flag); + + my $last = $finalmsg[-1]; + my $leftspace = $maxlen - length($last); + my $debug = ($flag =~ /debug/i) ? 1 : 0; + my $mark = ''; + if ($flag =~ /failed/i) { + $mark = "[FAIL]\n"; + } elsif ($flag =~ /warning/i) { + $mark = "[WARN]\n"; + } elsif ($flag =~ /ok/i) { + $mark = "[ OK ]\n"; + } elsif ($debug) { + $mark = "\n"; + } elsif ($flag =~ /info/i) { + $mark = "[INFO]\n"; + } + + my $spacenum = 0; + if (!$debug) { + $spacenum = (($leftspace >= $FLAG_WIDTH) ? ($leftspace - $FLAG_WIDTH) : ($screenwidth - length($last) + $maxlen - $FLAG_WIDTH)); + } + $finalmsg[-1] = $last . (" " x $spacenum); + + return (\@finalmsg, $mark); +} + +1; diff --git a/xCAT-probe/xcatprobe b/xCAT-probe/xcatprobe index 5a732c7831..6b1371c9ee 100755 --- a/xCAT-probe/xcatprobe +++ b/xCAT-probe/xcatprobe @@ -1,6 +1,10 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html +BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } + +use lib "$::XCATROOT/probe/lib/perl"; +use probe_format; use File::Basename; use Data::Dumper; use File::Path; @@ -8,8 +12,6 @@ use POSIX qw(WNOHANG setsid :errno_h); use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; -$::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; - my $program_name = basename($0); my $pro_dir = "$::XCATROOT/probe/"; @@ -74,6 +76,20 @@ sub loadsubcmds { } +#----------------------------------- + +=head3 + Description: + Ask the terminal how wide it is. 'tput cols' writes nothing when TERM + names a terminal terminfo does not carry, so probe_format decides what an + unusable answer means. +=cut + +#----------------------------------- +sub terminal_width { + return probe_format::screen_width($ENV{'TERM'} ? `tput cols 2>/dev/null` : undef); +} + #----------------------------------- =head3 @@ -87,96 +103,29 @@ sub format_cmd_output { my $color = shift; my $fullmsg = shift; - my $msg; - my $flag; + my ($lines, $mark) = probe_format::render($line, $fullmsg, terminal_width()); - if ($line =~ /\[(\w+)\]\s*:(.+)/) { - $flag = $1; - $msg = $2; + my $last = pop @$lines; + print "$_\n" foreach (@$lines); + + unless (defined($mark)) { + print "$last\n"; + return 0; + } + + print $last; + return 0 unless (length($mark)); + + if (!$color) { + print $mark; + } elsif ($mark =~ /FAIL/) { + print BOLD RED $mark; + } elsif ($mark =~ /WARN/) { + print BOLD BLUE $mark; + } elsif ($mark =~ /OK/) { + print BOLD GREEN $mark; } else { - $msg = $line; - } - - $msg =~ s/\t/ /g; - my $flaglen = 6; - my $desiredwidth = 120; - my $screenwidth = 80; - if ($ENV{'TERM'}) { - $screenwidth = (`tput cols` + 0); - } - my $maxlen = ($screenwidth > $desiredwidth ? $desiredwidth : $screenwidth); - - my @finalmsg = (); - my $msglen = length($msg); - if ($msglen <= $maxlen) { - if (!$fullmsg && $flag) { - my $leftspace = $maxlen - length($msg); - if ($leftspace < $flaglen) { - $msg = substr($msg, 0, $maxlen - $flaglen); - $msg =~ s/(.*).../$1\.\.\./g; - } - } - push @finalmsg, $msg; - } else { - my @tmpmsg = split("", $msg); - my $head = 0; - my $tail = $maxlen; - while ($head < $msglen) { - push @finalmsg, substr($msg, $head, ($tail - $head)); - if (!$fullmsg) { - if ($flag) { - $finalmsg[0] =~ s/(.*).........$/$1\.\.\./g; - } else { - $finalmsg[0] =~ s/(.*)...$/$1\.\.\./g; - } - last; - } - $head = $tail; - $tail = $head + ($maxlen <= ($msglen - $tail) ? $maxlen : ($msglen - $tail)); - } - } - - for (my $i = 0 ; $i < $#finalmsg + 1 ; ++$i) { - if ($i ne $#finalmsg) { - print "$finalmsg[$i]\n"; - next; - } - - if ($flag) { - my $leftspace = $maxlen - length($finalmsg[$i]); - my $spacenum = 0; - if($flag !~ /debug/i) { - $spacenum = (($leftspace >= $flaglen) ? ($leftspace - $flaglen) : ($screenwidth - length($finalmsg[$i]) + $maxlen - $flaglen)); - } - my $spacestr = " " x $spacenum; - print "$finalmsg[$i]$spacestr"; - - if ($flag =~ /failed/i) { - if ($color) { - print BOLD RED "[FAIL]\n"; - } else { - print "[FAIL]\n"; - } - } elsif ($flag =~ /warning/i) { - if ($color) { - print BOLD BLUE "[WARN]\n"; - } else { - print "[WARN]\n"; - } - } elsif ($flag =~ /ok/i) { - if ($color) { - print BOLD GREEN "[ OK ]\n"; - } else { - print "[ OK ]\n"; - } - } elsif ($flag =~ /debug/i) { - print "\n"; - } elsif ($flag =~ /info/i) { - print "[INFO]\n"; - } - } else { - print "$finalmsg[$i]\n"; - } + print $mark; } return 0; } @@ -197,10 +146,7 @@ sub listvalidsubcmd { $maxlen += 4; my $desiredwidth = 120; - my $screenwidth = 80; - if ($ENV{'TERM'}) { - $screenwidth = (`tput cols` + 0); - } + my $screenwidth = terminal_width(); my $finallen = ($screenwidth > $desiredwidth ? $desiredwidth : $screenwidth); print "Supported sub commands are:\n"; diff --git a/xCAT-test/unit/probe_xcatmn_selinux_case.t b/xCAT-test/unit/probe_xcatmn_selinux_case.t index 768e29e5bb..921897b70e 100644 --- a/xCAT-test/unit/probe_xcatmn_selinux_case.t +++ b/xCAT-test/unit/probe_xcatmn_selinux_case.t @@ -13,6 +13,7 @@ use lib "$FindBin::Bin/../../xCAT-probe/lib/perl"; use Test::More; require probe_utils; +require probe_format; like($INC{'probe_utils.pm'}, qr/\Q$FindBin::Bin\E/, 'probe_utils comes from this checkout'); # The case ran the probe through grep. ausearch is not involved here: grep kept @@ -60,10 +61,18 @@ isnt($mark{o}, $mark{f}, "send_msg marks an ok checkpoint '$mark{o}' apart from a failed one '$mark{f}'"); like($mark{o}, qr/\QSELinux\E/, 'the ok mark carries the checkpoint text'); -my %rendered = ( - ok => $checkpoint . (' ' x 39) . '[ OK ]', - failed => $checkpoint . (' ' x 39) . '[FAIL]', -); +# Lay the marks out the way xcatprobe does, at the width the GitHub Actions +# container gives: it sets TERM to a name terminfo does not carry, so +# 'tput cols' writes nothing. The case reads what this renders. +my $width = probe_format::screen_width(''); +my %rendered; +foreach my $tag (qw(o f)) { + my ($lines, $flag) = probe_format::render($mark{$tag}, 0, $width); + chomp($flag); + $rendered{ $tag eq 'o' ? 'ok' : 'failed' } = join("\n", @$lines) . $flag; +} +like($rendered{ok}, qr/\Q$checkpoint\E/, + "the rendered checkpoint keeps its text without a terminal: '$rendered{ok}'"); foreach my $pattern (@positive) { like($rendered{ok}, qr/$pattern/, "a passing SELinux checkpoint matches '$pattern'"); unlike($rendered{failed}, qr/$pattern/, From 37de3e634ebee74cb2ff0b0f69b967ab4632415c Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:49:45 -0300 Subject: [PATCH 84/91] fix(xcat-probe): a terminal tput cannot measure erases every checkpoint message xcatprobe asks 'tput cols' for the screen width whenever TERM is set. The GitHub Actions container sets TERM=unknown, terminfo carries no such terminal, and tput writes nothing. The width became 0 and the layout cut every checkpoint message to the empty string, so the probe printed a column of bare [ OK ], [WARN] and [FAIL] marks with no text beside them. xcatprobe_xcatmn_selinux failed on that output. It asserts that the SELinux checkpoint reports [ OK ], and no checkpoint text reached the log. The rest of the probe diagnostics were unreadable for the same reason, so the one [FAIL] in the run named no checkpoint. probe_format::screen_width keeps the 80 column default when 'tput cols' gives no usable number. probe_xcatmn_selinux_case.t renders the checkpoint at that width and three of its assertions fail without this change. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-probe/lib/perl/probe_format.pm | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/xCAT-probe/lib/perl/probe_format.pm b/xCAT-probe/lib/perl/probe_format.pm index 585bd52991..6abbd0e391 100644 --- a/xCAT-probe/lib/perl/probe_format.pm +++ b/xCAT-probe/lib/perl/probe_format.pm @@ -17,7 +17,7 @@ my $FLAG_WIDTH = 6; Arguments: raw: the output of 'tput cols', or undef when there is no terminal Returns: - the column count + the column count, always more than the flag width =cut @@ -25,8 +25,12 @@ my $FLAG_WIDTH = 6; sub screen_width { my ($raw) = @_; - return $DEFAULT_WIDTH unless (defined($raw)); - return $raw =~ /(\d+)/ ? $1 + 0 : 0; + # 'tput cols' writes nothing when TERM names a terminal terminfo does not + # carry, and the GitHub Actions container sets TERM=unknown. A width of 0 + # cuts every checkpoint message down to the empty string. + return $DEFAULT_WIDTH unless (defined($raw) && $raw =~ /(\d+)/); + my $cols = $1 + 0; + return $cols > $FLAG_WIDTH ? $cols : $DEFAULT_WIDTH; } #----------------------------------- From bd91348c547e887dad93f1a1749d1892cd8ed364 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:03:35 -0300 Subject: [PATCH 85/91] test(xcat-selinux): assert the policy package is built for EL targets only Nothing holds the scope of xCAT-selinux down. The package is in the default set of buildrpms.pl, so every target builds it, and xCAT-server and xCATsn require it on openEuler as well as on EL. The test reads the build-plan decision and the two spec conditions. It fails on this commit: BuildUtils has no build-plan decision, and both conditions still name openEuler. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/selinux_el_only_scope.t | 74 ++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 xCAT-test/unit/selinux_el_only_scope.t diff --git a/xCAT-test/unit/selinux_el_only_scope.t b/xCAT-test/unit/selinux_el_only_scope.t new file mode 100644 index 0000000000..296c88d7d2 --- /dev/null +++ b/xCAT-test/unit/selinux_el_only_scope.t @@ -0,0 +1,74 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use File::Slurper qw(read_lines); +use Test::More; + +use lib "$FindBin::Bin/../../build-utils/lib"; +use XCAT::BuildUtils (); + +# SELinux support is EL only. Two artifacts carry that scope: the build plan, +# which decides the (package, target) pairs buildrpms.pl builds, and the two +# specs that make a management node or a service node pull xCAT-selinux in. +# +# Measured 2026-10-22 in mock chroots: openEuler 20.03sp4 and 22.03sp4 carry +# selinux-policy 3.14.2 and cannot compile the module, 24.03sp4 carries 40.7 +# and can. 24.03sp4 is excluded as well, so no openEuler release ships a +# package the other releases cannot build. +my @openeuler_targets = qw( + openeuler-20.03sp4-x86_64 + openeuler-22.03sp4-x86_64 + openeuler-24.03sp4-x86_64 + openeuler-24.03-ppc64le +); +my @el_targets = qw( + alma+epel-8-x86_64 + alma+epel-9-x86_64 + alma+epel-10-x86_64 + alma+epel-10-ppc64le +); + +my $decides = XCAT::BuildUtils->can('package_skip_reason'); +ok($decides, 'BuildUtils decides which packages a target builds'); + +SKIP: { + skip 'BuildUtils has no build-plan decision', 17 unless $decides; + + foreach my $target (@openeuler_targets) { + ok($decides->('xCAT-selinux', $target), + "xCAT-selinux is not built for $target"); + } + + foreach my $target (@el_targets) { + is($decides->('xCAT-selinux', $target), undef, + "xCAT-selinux is built for $target"); + } + + # The gate names one package. Every other package keeps every target. + foreach my $pkg (qw(perl-xCAT xCAT xCATsn xCAT-client xCAT-server xCAT-probe + xCAT-genesis-scripts xCAT-test xCAT-release)) { + is($decides->($pkg, 'openeuler-22.03sp4-x86_64'), undef, + "$pkg is built for openEuler"); + } +} + +# A node that resolves this dependency on openEuler cannot install xCAT, because +# the package is no longer in the repository. openEuler defines %openEuler and +# no %rhel, so the condition must not name openEuler. +my $root = "$FindBin::Bin/../.."; +foreach my $pkg (qw(xCAT-server xCATsn)) { + my @lines = read_lines("$root/$pkg/$pkg.spec"); + my ($index) = grep { + $lines[$_] =~ /^Requires:\s*\(xCAT-selinux = 4:%\{version\}-%\{release\} if selinux-policy-targeted\)\s*$/ + } 0 .. $#lines; + ok(defined $index, "$pkg requires xCAT-selinux when selinux-policy-targeted is installed"); + + my $if = defined $index ? $lines[$index - 1] : ''; + like($if, qr/^%if\b/, "... behind a condition"); + like($if, qr/0%\{\?rhel\} >= 8/, "... that holds on EL 8 and later"); + unlike($if, qr/openEuler/i, "... and not on openEuler"); +} + +done_testing(); From b46826434ac2ce3412142c26cd0596f456edb57f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:03:43 -0300 Subject: [PATCH 86/91] fix(xcat-selinux): openEuler builds a policy package it cannot compile xCAT-selinux is in the default package set of buildrpms.pl, so every target builds it. openEuler 20.03sp4 and 22.03sp4 carry selinux-policy 3.14.2, which defines none of unconfined_server_stream_connectto(), files_map_etc_files() or chronyd_manage_pid_files(). m4 leaves an undefined interface name in its output and checkmodule stops with a syntax error, so rpmbuild fails and the core build for that target publishes no repository at all. SELinux support is EL only. XCAT::BuildUtils::package_skip_reason names the packages an openEuler target does not build, and buildrpms.pl prints each pair it skips. openEuler 24.03sp4 carries selinux-policy 40.7 and does compile the module. It is excluded as well, so no openEuler release ships a package the other releases cannot build. xCAT-server and xCATsn required xCAT-selinux when selinux-policy-targeted was installed, on openEuler too. openEuler defines %openEuler and no %rhel, so the condition now names EL 8 and later and Fedora only. Without this an openEuler management node cannot resolve xCAT-server. xCAT-test/unit/selinux_el_only_scope.t fails on the parent commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- build-utils/lib/XCAT/BuildUtils.pm | 23 ++++++++++++++++++++++- buildrpms.pl | 9 ++++++++- xCAT-server/xCAT-server.spec | 2 +- xCATsn/xCATsn.spec | 2 +- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/build-utils/lib/XCAT/BuildUtils.pm b/build-utils/lib/XCAT/BuildUtils.pm index c5268a109c..36571f5fdf 100644 --- a/build-utils/lib/XCAT/BuildUtils.pm +++ b/build-utils/lib/XCAT/BuildUtils.pm @@ -43,7 +43,7 @@ our @EXPORT_OK = qw( rewrite_file write_script read_line buildinfo_text targetarch_from_target - openeuler_build_target openeuler_repo_subdir + openeuler_build_target openeuler_repo_subdir package_skip_reason mock_config_text mock_build_owner prepare_mock_resultdirs genesis_chroot_name genesis_target_arch genesis_build_plan genesis_log_errors genesis_log_deny_rules deb_belongs_to_dist @@ -806,6 +806,27 @@ sub cancel_build { sub DESTROY { shift->release } } +# The packages that only the EL targets build, and why. xCAT-selinux is EL +# only: its policy module is compiled against the selinux-policy of the build +# target, and openEuler 20.03 and 22.03 carry selinux-policy 3.14.2, which +# defines none of unconfined_server_stream_connectto(), files_map_etc_files() +# or chronyd_manage_pid_files(). m4 leaves an undefined interface name in its +# output, and checkmodule stops on it. openEuler 24.03sp4 carries +# selinux-policy 40.7 and does compile the module, and is excluded too, so no +# openEuler release ships a package the other releases cannot build. +my %EL_ONLY_PACKAGES = ( + 'xCAT-selinux' => 'SELinux support is EL only', +); + +# Why $pkg is not built for $target, or undef when the pair is built. openEuler +# is the one non-EL family buildrpms.pl targets. +sub package_skip_reason { + my ($pkg, $target) = @_; + my $reason = $EL_ONLY_PACKAGES{ $pkg // '' } or return undef; + return undef unless defined($target) && $target =~ /\Aopeneuler-/; + return $reason; +} + sub openeuler_build_target { my ($os, $arch) = @_; return undef unless lc($os->{ID} // '') eq 'openeuler'; diff --git a/buildrpms.pl b/buildrpms.pl index 74eab3b195..9a26673dc9 100755 --- a/buildrpms.pl +++ b/buildrpms.pl @@ -60,6 +60,7 @@ use XCAT::BuildUtils qw(git_revision source_date_epoch sh sh_or_die usage buildi stage_genesis_base_sources write_script read_line targetarch_from_target openeuler_build_target openeuler_repo_subdir + package_skip_reason mock_config_text); use POSIX (); # EEXIST, for the directory build lock (see main()) use Getopt::Long qw(GetOptions); @@ -1028,7 +1029,13 @@ sub main { # A builder killed with SIGKILL together with this parent leaves its directory behind. sweep_build_sources_dirs($SOURCES_BASE); - my @rpms = product($opts{packages}, $opts{targets}); + my @rpms; + for my $pair (product($opts{packages}, $opts{targets})) { + my $why = package_skip_reason($pair->@*); + $why ? print "Skipping $pair->[0] for $pair->[1]: $why\n" : push @rpms, $pair; + } + die "FATAL: every requested package is out of scope for the requested targets\n" + unless @rpms; my $pm = Parallel::ForkManager->new($opts{nproc}); # Track which mock chroot each live child is building so abort_builds can scrub it. diff --git a/xCAT-server/xCAT-server.spec b/xCAT-server/xCAT-server.spec index ca3e8a6dc7..8fc21abee1 100644 --- a/xCAT-server/xCAT-server.spec +++ b/xCAT-server/xCAT-server.spec @@ -104,7 +104,7 @@ Requires: perl-IO-Tty perl-Crypt-SSLeay make httpd Requires: perl-xCAT = 4:%{version}-%{release} Requires: xCAT-client = 4:%{version}-%{release} -%if 0%{?rhel} >= 8 || 0%{?fedora} || 0%{?openEuler} +%if 0%{?rhel} >= 8 || 0%{?fedora} Requires: (xCAT-selinux = 4:%{version}-%{release} if selinux-policy-targeted) %endif diff --git a/xCATsn/xCATsn.spec b/xCATsn/xCATsn.spec index 81c577d8e3..cea6eeda81 100644 --- a/xCATsn/xCATsn.spec +++ b/xCATsn/xCATsn.spec @@ -25,7 +25,7 @@ Requires: xCAT-client = 4:%{version}-%{release} Requires: xCAT-server = 4:%{version}-%{release} Requires: xCAT-probe = 4:%{version}-%{release} -%if 0%{?rhel} >= 8 || 0%{?fedora} || 0%{?openEuler} +%if 0%{?rhel} >= 8 || 0%{?fedora} Requires: (xCAT-selinux = 4:%{version}-%{release} if selinux-policy-targeted) %endif From 576370bdf93bc5a162add964816f62701b68d907 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:25:22 -0300 Subject: [PATCH 87/91] test(xcat-core): no case measures the documented repair of a published artifact The SELinux page documents a recursive chcon to repair a published artifact that carries the wrong type. No case runs that procedure, so nothing measures what it does to the guest trees of the image root, and nothing measures whether the repair survives a later relabel. selinux_image_repair.t starts with default_t on every published artifact of an image root and with valid types in both rootimg and rootimg-statelite. It runs the repair, then reads the labels back after a recursive relabel and after a reinstall of the module. It covers the standard publication directory and one that site.installdir moved, because the packaged mappings name /install. semanage writes to the policy store of the host, so the case refuses to run where SELinux is enabled and removes every mapping it adds. restorecon is a no-op where SELinux is disabled, so the case applies the mappings with setfiles and asserts that the merged file_contexts answers what the store answers for each path. selinux_docs.t gains the checks that keep the page and the xcat.fc comment from describing a chcon repair. 7 of its 26 checks fail on this commit. With the chcon of the page in place of the documented procedure, selinux_image_repair.t fails 101 of its 170 checks, 36 of them guest labels that the recursive chcon overwrote. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- .github/workflows/xcat_test.yml | 5 +- xCAT-test/native/README.md | 14 ++ xCAT-test/native/selinux_image_repair.t | 303 ++++++++++++++++++++++++ xCAT-test/unit/selinux_docs.t | 17 ++ 4 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 xCAT-test/native/selinux_image_repair.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 7cd811699f..2ad1300ebc 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -142,9 +142,12 @@ jobs: - name: Install policy test dependencies run: | dnf install -y epel-release - dnf --enablerepo=crb install -y make selinux-policy-devel selinux-policy-targeted libselinux-utils policycoreutils attr perl perl-Capture-Tiny perl-Test-Simple perl-Test-Harness + dnf --enablerepo=crb install -y make selinux-policy-devel selinux-policy-targeted libselinux-utils policycoreutils policycoreutils-python-utils attr perl perl-Capture-Tiny perl-Test-Simple perl-Test-Harness - name: Look up and relabel the xCAT file contexts run: | mkdir -p /mnt/labels mount -t tmpfs -o size=1g tmpfs /mnt/labels TMPDIR=/mnt/labels prove -v xCAT-test/native/selinux_file_contexts.t + - name: Repair a published artifact and keep the guest labels + if: ${{ !cancelled() }} + run: TMPDIR=/mnt/labels prove -v xCAT-test/native/selinux_image_repair.t diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 58b33f4e0b..4fbe848840 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -214,6 +214,20 @@ The case looks up labels in the compiled `file_contexts` and relabels a copy of `/install` with `setfiles`. It does not need an enforcing kernel, and it does not run the rpm scriptlets. +The repair case drives the procedure the SELinux page documents for a published +artifact that carries the wrong type: + +``` +TMPDIR=/mnt/labels prove xCAT-test/native/selinux_image_repair.t +``` + +It adds local file-context mappings with `semanage`, so it also needs +`policycoreutils-python-utils`. Those mappings go into the policy store of the +host, so the case refuses to run where SELinux is enabled, and it removes every +mapping it adds. `restorecon` is a no-op where SELinux is disabled, so the case +applies the mappings with `setfiles` and asserts that the merged `file_contexts` +answers what the store answers for each path it measures. + Check the TAP output for skipped prerequisites. A successful `prove` exit with skipped cases does not qualify those cases. diff --git a/xCAT-test/native/selinux_image_repair.t b/xCAT-test/native/selinux_image_repair.t new file mode 100644 index 0000000000..fd985a2185 --- /dev/null +++ b/xCAT-test/native/selinux_image_repair.t @@ -0,0 +1,303 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Capture::Tiny qw(capture); +use File::Path qw(make_path); +use File::Temp qw(tempdir); +use FindBin; +use Test::More; + +# The documented repair of a published artifact adds local file-context +# mappings, so this test writes to the policy store of the host. It runs only +# where SELinux is disabled, which is the container the CI uses, and it removes +# every mapping it adds. +die "run as root\n" unless $> == 0; +die "requires the targeted policy store\n" unless -d '/var/lib/selinux/targeted'; +die "requires semanage\n" if system('command -v semanage >/dev/null 2>&1') != 0; +die "refuses to add mappings where SELinux is enabled\n" if -e '/sys/fs/selinux/enforce'; + +my $work = tempdir(CLEANUP => 1); +my @added; + +#--- + +=head3 run + + Descriptions: Run a command and die with its output when it fails. + Arguments: The command and its arguments. + Returns: The standard output of the command. + +=cut + +#--- +sub run { + my (@command) = @_; + my ($out, $err, $rc) = capture { system(@command) }; + die "@command: rc=$rc\n$out$err" if $rc != 0; + return $out; +} + +my $build = "$work/build"; +make_path($build); +run('cp', glob("$FindBin::Bin/../../xCAT-selinux/xcat.*"), $build); +run('make', '-C', $build, '-f', '/usr/share/selinux/devel/Makefile', 'xcat.pp'); + +#--- + +=head3 install_module + + Descriptions: Install xcat.pp into the policy store, as %post does. + Arguments: None. + Returns: Nothing. + +=cut + +#--- +sub install_module { + run('semodule', '-i', "$build/xcat.pp"); +} + +#--- + +=head3 add_mapping + + Descriptions: Add one persistent file-context mapping, as the documented + repair does, and record it for removal. + Arguments: The type, the path expression, and the -f value or undef. + Returns: Nothing. + +=cut + +#--- +sub add_mapping { + my ($type, $expression, $ftype) = @_; + my @ftype = $ftype ? ('-f', $ftype) : (); + run('semanage', 'fcontext', '-a', '-t', $type, @ftype, $expression); + push @added, [ $expression, @ftype ]; +} + +END { + foreach my $mapping (reverse @added) { + my ($expression, @ftype) = @$mapping; + system('semanage', 'fcontext', '-d', @ftype, $expression); + } +} + +#--- + +=head3 lookup + + Descriptions: Ask the policy store for the default label of a path, which + is what restorecon applies. + Arguments: The path on the management node. + Returns: The type, or <> when restorecon leaves the path alone. + +=cut + +#--- +sub lookup { + my ($path, $fc) = @_; + my @spec = $fc ? ('-f', $fc) : (); + my $out = run('matchpathcon', @spec, $path); + return $1 if $out =~ /^\S+\s+[^:\s]+:[^:\s]+:(\w+):/; + return '<>' if $out =~ /^\S+\s+<>$/; + die "matchpathcon $path: unexpected output: $out"; +} + +#--- + +=head3 merged_contexts + + Descriptions: Write the file contexts of the store and its local mappings + into one file, so setfiles applies what restorecon would. + restorecon is a no-op where SELinux is disabled. + Arguments: None. + Returns: The path of the file. +=cut + +#--- +sub merged_contexts { + my $base = '/etc/selinux/targeted/contexts/files/file_contexts'; + my $out = "$work/merged.fc"; + # libselinux reads file_contexts first and file_contexts.local last, and + # between two expressions that both match, the later entry wins. Keep that + # order, or a local mapping loses to the packaged one. + open(my $fh, '>', $out) or die "$out: $!"; + foreach my $file ($base, "$base.local") { + next unless -f $file; + open(my $in, '<', $file) or die "$file: $!"; + print {$fh} <$in>; + close($in); + } + close($fh); + return $out; +} + +#--- + +=head3 label_of + + Descriptions: Read the security.selinux attribute of a file. + Arguments: The path on the management node. + Returns: The type in the attribute. + +=cut + +#--- +sub label_of { + my ($root, $path) = @_; + my $value = run('getfattr', '--only-values', '-n', 'security.selinux', "$root$path"); + return $value =~ /^[^:]+:[^:]+:(\w+):/ ? $1 : $value; +} + +#--- + +=head3 make_tree + + Descriptions: Create a tree under a scratch root and set the label of each + path from the given map. + Arguments: The scratch root, and a map of path to type. + Returns: Nothing. + +=cut + +#--- +sub make_tree { + my ($root, $labels) = @_; + foreach my $path (sort keys %$labels) { + my $file = "$root$path"; + if ($path =~ m{/$}) { + make_path($file); + } else { + (my $dir = $file) =~ s{/[^/]+$}{}; + make_path($dir); + open(my $fh, '>', $file) or die "$file: $!"; + close($fh); + } + $file =~ s{/$}{}; + run('setfattr', '-n', 'security.selinux', + '-v', "system_u:object_r:$labels->{$path}:s0", $file); + } +} + +install_module(); + +# The names genimage and packimage write in an image root, and the expression +# the repair maps for each one. Each expression names one regular file directly +# below the image root, so no path in a guest tree matches it. +my @published = qw(kernel hypervisor initrd-stateless.gz initrd-statelite.gz + rootimg.cpio.gz rootimg-statelite.gz rootimgtree.gz litefile.csv + common.filelist); +my @expressions = ('kernel', 'hypervisor', 'initrd[^/]*', 'rootimg\.[^/]*', + 'rootimg-statelite\.[^/]*', 'rootimgtree\.[^/]*', 'litefile\.csv', + 'common\.filelist'); + +# A guest file keeps the label of its own operating system. The tree root is a +# directory, so the -f f expressions cannot take it either. +my %guest_labels = ( + 'etc/shadow' => 'shadow_t', + 'etc/passwd' => 'etc_t', + 'usr/bin/sh' => 'bin_t', + '' => 'etc_t', +); + +#--- + +=head3 scenario + + Descriptions: Build an image root whose published artifacts carry the wrong + type and whose two guest trees carry valid types, run the + documented repair, and verify the result after a recursive + relabel and after a policy upgrade. + Arguments: A name, the configured publication directory, the image root, + and a sub that adds the mappings of the repair. + Returns: Nothing. + +=cut + +#--- +sub scenario { + my ($name, $installdir, $imgroot, $repair) = @_; + my $root = "$work/$name"; + my %labels; + + # Wrong on every published artifact. default_t is what a tree older than + # the package carries, and httpd_t has no rule to read it. + $labels{"$imgroot/$_"} = 'default_t' foreach @published; + + # Valid inside both guest trees. An image root can carry a rootimg + # component of its own, so collect the guest paths here rather than by + # matching the name rootimg anywhere in the path. + my @guest; + foreach my $tree ("$imgroot/rootimg", "$imgroot/rootimg-statelite") { + foreach my $path (sort keys %guest_labels) { + my $guest = $path eq '' ? $tree : "$tree/$path"; + $labels{$path eq '' ? "$tree/" : $guest} = $guest_labels{$path}; + push @guest, $guest; + } + } + make_tree($root, \%labels); + + my %before = map { (my $p = $_) =~ s{/$}{}; ($p => $labels{$_}) } keys %labels; + my @artifacts = map { "$imgroot/$_" } @published; + + $repair->(); + + # The repair is applied with restorecon, which reads the store. setfiles + # reads a file, so assert the two answer the same before relying on it. + my $fc = merged_contexts(); + foreach my $path (@artifacts, @guest) { + is(lookup($path, $fc), lookup($path), + "$name: the merged contexts answer for $path what the store answers"); + } + + foreach my $path (@artifacts) { + is(lookup($path), 'public_content_t', "$name: the repair maps $path"); + } + foreach my $path (@guest) { + is(lookup($path), '<>', "$name: the repair leaves $path out"); + } + + foreach my $step ('repair', 'host relabel', 'policy upgrade') { + install_module() if $step eq 'policy upgrade'; + $fc = merged_contexts(); + run('setfiles', '-F', '-r', $root, $fc, "$root$installdir"); + foreach my $path (@artifacts) { + is(label_of($root, $path), 'public_content_t', + "$name: after the $step $path is public_content_t"); + } + foreach my $path (@guest) { + is(label_of($root, $path), $before{$path}, + "$name: after the $step $path keeps $before{$path}"); + } + } +} + +# A rootimg component in the middle of an image root is ambiguous, so the +# packaged mappings leave every path in such a root alone, published artifacts +# included. The repair maps each published artifact of that one image root. +scenario( + 'standard installdir', + '/install', + '/install/netboot/rootimg/rhels9/x86_64/compute', + sub { + add_mapping('public_content_t', + "/install/netboot/rootimg/rhels9/x86_64/compute/$_", 'f') + foreach @expressions; + }); + +# site.installdir selects the publication directory, and the packaged mappings +# name /install. A site that moved it maps the configured directory itself, and +# keeps both guest trees out with <>. +scenario( + 'moved installdir', + '/srv/xcat-install', + '/srv/xcat-install/netboot/custom-image', + sub { + add_mapping('public_content_t', '/srv/xcat-install(/.*)?'); + add_mapping('<>', '/srv/xcat-install(/.*)?/rootimg(/.*)?'); + add_mapping('<>', '/srv/xcat-install(/.*)?/rootimg-statelite(/.*)?'); + }); + +done_testing(); diff --git a/xCAT-test/unit/selinux_docs.t b/xCAT-test/unit/selinux_docs.t index e180a5fe45..50c8a0fd3b 100644 --- a/xCAT-test/unit/selinux_docs.t +++ b/xCAT-test/unit/selinux_docs.t @@ -51,4 +51,21 @@ foreach my $page (@pages) { "$page does not say xCAT leaves the mode of a node alone"); } +# A repair of a published artifact is a persistent file-context mapping, applied +# with restorecon. chcon writes a type that no mapping selects, and a recursive +# chcon over an image root walks into both guest trees. +my $repair = 'docs/source/advanced/selinux/index.rst'; +unlike($text{$repair}, qr/chcon\s+-R/, "$repair documents no recursive chcon"); +like($text{$repair}, qr/semanage fcontext -a/, "$repair maps the artifact with semanage"); +like($text{$repair}, qr/restorecon -R/, "$repair applies the mapping with restorecon"); +like($text{$repair}, qr/installdir/, + "$repair takes the publication directory from site.installdir"); +foreach my $guest (qw(rootimg rootimg-statelite)) { + like($text{$repair}, qr/\Q$guest\E/, "$repair names the $guest tree"); +} + +my $fc = read_text("$root/xCAT-selinux/xcat.fc"); +unlike($fc, qr/chcon/, 'xcat.fc advises no chcon'); +like($fc, qr/semanage fcontext/, 'xcat.fc names the command that maps a path'); + done_testing(); From 78f6d65a7cee8d22abdcb2514eb7de0c22a9def2 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:25:33 -0300 Subject: [PATCH 88/91] fix(xcat-core): the documented repair of a published artifact relabels the guest trees The SELinux page told the operator to run chcon -R -t public_content_t over the image root to repair a published artifact that kept an older type. That command walks into rootimg and rootimg-statelite, so it replaces the labels of the guest operating system with public_content_t. The xcat.fc comment carried the same advice. chcon also writes a type that no mapping selects, so the next relabel of a path that has a mapping reverts it: the repair held only until then. The page now maps each published artifact with semanage fcontext and applies the mapping with restorecon. Each expression names one regular file directly below the image root, so no path in either guest tree matches one, and both trees keep the <> of the packaged mappings. The procedure reads the publication directory from site.installdir, and a site that moved it maps the configured directory and keeps both guest trees out of that mapping. The page says why a tree mapping over the image root is the same defect as the chcon. xCAT-test/native/selinux_image_repair.t passes 170 of 170 checks with the documented procedure. With the chcon of the previous page it fails 101, 36 of them guest labels. selinux_docs.t fails 7 of 26 on the parent commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 48 ++++++++++++++++++++++---- xCAT-selinux/xcat.fc | 4 +-- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 7189d199a2..95e20525c6 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -85,14 +85,50 @@ that ``restorecon`` already made ``public_content_t``, and a new file inherits the type of its directory, so the kernel is ``public_content_t`` and ``httpd`` serves it. Netboot works. -The cost is a path that already carries another type, from before the package -was installed or from a ``chcon``. It keeps that type, and ``restorecon`` over -``/install`` cannot repair it, with or without ``-F``: there is no context to -apply. Set it directly:: +The cost is a published artifact of such an image root that already carries +another type, from before the package was installed. ``restorecon`` over the +publication directory cannot repair it, with or without ``-F``, because the +path has no context to apply. Give it one. - chcon -R -t public_content_t /install/netboot/rootimg/rhels9/x86_64/compute +``site.installdir`` selects the publication directory. Read it, and map each +published artifact of that one image root:: -A later ``restorecon`` leaves that value alone, so the repair holds. + installdir=$(lsdef -t site -i installdir -c | sed 's/^.*=//; s:/*$::') + imgroot=$installdir/netboot/rootimg/rhels9/x86_64/compute + + for name in kernel hypervisor 'initrd[^/]*' 'rootimg\.[^/]*' \ + 'rootimg-statelite\.[^/]*' 'rootimgtree\.[^/]*' \ + 'litefile\.csv' 'common\.filelist'; do + semanage fcontext -a -t public_content_t -f f "$imgroot/$name" + done + restorecon -R -v "$imgroot" + +Each expression names one regular file directly below the image root, so no +path in ``$imgroot/rootimg`` or ``$imgroot/rootimg-statelite`` matches one. +Both guest trees keep the ``<>`` of the packaged mappings, and +``restorecon`` leaves every file in them alone. ``file_contexts.local`` is read +after the packaged file, and the last expression that matches a path wins, so +each mapping above wins against ``/install(/.*)?/rootimg(/.*)?``. + +Do not repair a label with ``chcon``, and do not map the image root as a tree. +``chcon`` writes a type that no mapping selects, so the next relabel of a path +that has a mapping reverts it, and a recursive ``chcon`` relabels both guest +trees as well. A tree mapping over the image root relabels them through +``restorecon`` instead. + +The packaged mappings name ``/install``. A site that moved ``site.installdir`` +maps the configured directory, and keeps both guest trees out of that mapping:: + + semanage fcontext -a -t public_content_t "$installdir(/.*)?" + semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg(/.*)?" + semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg-statelite(/.*)?" + restorecon -R -v "$installdir" + +A mapping is persistent, so a later recursive relabel and a policy upgrade both +keep the result. ``xCAT-test/native/selinux_image_repair.t`` starts with the +wrong type on every published artifact and valid types in both guest trees, +runs each procedure, and reads the labels back after a recursive relabel and +after a reinstall of the module. The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc index cb637372c6..b8ed67a361 100644 --- a/xCAT-selinux/xcat.fc +++ b/xCAT-selinux/xcat.fc @@ -37,8 +37,8 @@ # An entry of <> keeps whatever label the path has. It does not clear one. # genimage creates such a kernel under an image root that restorecon already # made public_content_t, so the kernel inherits that type and httpd serves it. -# A path that carries another type keeps it, and no restorecon repairs that: -# chcon -R -t public_content_t over the image root does. +# A path that carries another type keeps it. The repair is one semanage fcontext +# mapping for that one file, then restorecon. The SELinux page carries it. /install(/.*)?/rootimg(-statelite)?/kernel -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/hypervisor -- gen_context(system_u:object_r:public_content_t,s0) /install(/.*)?/rootimg(-statelite)?/initrd[^/]* -- gen_context(system_u:object_r:public_content_t,s0) From 7d66afe2f3cd38e8b48a57ad9f83f0b8b726af30 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:56:41 -0300 Subject: [PATCH 89/91] test(xcat-core): no case runs the documented repair as one sequence selinux_image_repair.t measured a moved publication directory and an image root with a rootimg component in the middle in separate fixtures, and it called the mappings of a scenario a repair without running the restorecon the page puts between them. Neither condition reaches the ordering defect on its own, and the relabel the procedure runs itself was never measured. The case now gives each scenario the relabel, so the scenario places it where the page does. It reads the guest labels straight after the procedure, because a label the procedure overwrote cannot be recovered by a mapping added afterwards. It then asserts the mapping and the label of each path after a recursive relabel and after a reinstall of the module. A third scenario runs the four documented steps on the layout that needs all of them: site.installdir is /srv/xcat-images, so no mapping covers the tree until the procedure adds one, and the image root carries a rootimg component in the middle, so the guest exclusion matches the published artifacts too. selinux_docs.t gains three checks on the order of the page: the guest exclusions come before the artifact mappings, the relabel comes after the last mapping, and there is one relabel. All three fail against the page at 78f6d65a7. With the command order of that page, the full sequence fails 47 of 381 checks: 16 guest labels, which go from shadow_t, etc_t and bin_t to var_t, and 15 artifact mappings, which resolve <> for the five expressions that carry a wildcard. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/native/selinux_image_repair.t | 57 ++++++++++++++++++++----- xCAT-test/unit/selinux_docs.t | 14 ++++++ 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/xCAT-test/native/selinux_image_repair.t b/xCAT-test/native/selinux_image_repair.t index fd985a2185..0128b73de7 100644 --- a/xCAT-test/native/selinux_image_repair.t +++ b/xCAT-test/native/selinux_image_repair.t @@ -242,7 +242,21 @@ sub scenario { my %before = map { (my $p = $_) =~ s{/$}{}; ($p => $labels{$_}) } keys %labels; my @artifacts = map { "$imgroot/$_" } @published; - $repair->(); + # The documented sequence runs restorecon itself, and where it runs decides + # what the operator gets. Give the procedure the relabel, so the order of + # the mappings and the relabel is what this measures. + my $relabel = sub { + my ($target) = @_; + run('setfiles', '-F', '-r', $root, merged_contexts(), "$root$target"); + }; + $repair->($relabel); + + # A guest label the procedure overwrote cannot be recovered by a mapping + # added afterwards, so read the guest trees before anything else. + foreach my $path (@guest) { + is(label_of($root, $path), $before{$path}, + "$name: after the repair $path keeps $before{$path}"); + } # The repair is applied with restorecon, which reads the store. setfiles # reads a file, so assert the two answer the same before relying on it. @@ -252,22 +266,19 @@ sub scenario { "$name: the merged contexts answer for $path what the store answers"); } - foreach my $path (@artifacts) { - is(lookup($path), 'public_content_t', "$name: the repair maps $path"); - } - foreach my $path (@guest) { - is(lookup($path), '<>', "$name: the repair leaves $path out"); - } - foreach my $step ('repair', 'host relabel', 'policy upgrade') { - install_module() if $step eq 'policy upgrade'; - $fc = merged_contexts(); - run('setfiles', '-F', '-r', $root, $fc, "$root$installdir"); + if ($step ne 'repair') { + install_module() if $step eq 'policy upgrade'; + $relabel->($installdir); + } foreach my $path (@artifacts) { + is(lookup($path), 'public_content_t', + "$name: after the $step the mapping of $path is public_content_t"); is(label_of($root, $path), 'public_content_t', "$name: after the $step $path is public_content_t"); } foreach my $path (@guest) { + is(lookup($path), '<>', "$name: after the $step $path is left out"); is(label_of($root, $path), $before{$path}, "$name: after the $step $path keeps $before{$path}"); } @@ -282,9 +293,11 @@ scenario( '/install', '/install/netboot/rootimg/rhels9/x86_64/compute', sub { + my ($relabel) = @_; add_mapping('public_content_t', "/install/netboot/rootimg/rhels9/x86_64/compute/$_", 'f') foreach @expressions; + $relabel->('/install/netboot/rootimg/rhels9/x86_64/compute'); }); # site.installdir selects the publication directory, and the packaged mappings @@ -295,9 +308,31 @@ scenario( '/srv/xcat-install', '/srv/xcat-install/netboot/custom-image', sub { + my ($relabel) = @_; add_mapping('public_content_t', '/srv/xcat-install(/.*)?'); add_mapping('<>', '/srv/xcat-install(/.*)?/rootimg(/.*)?'); add_mapping('<>', '/srv/xcat-install(/.*)?/rootimg-statelite(/.*)?'); + $relabel->('/srv/xcat-install'); }); +# The whole documented sequence, on the layout that needs every step of it: the +# publication directory is moved, so no mapping covers the tree until the +# procedure adds one, and the image root carries a rootimg component in the +# middle, so the guest exclusion matches the published artifacts as well. +# +# Order decides both answers. A relabel before the exclusions exist writes a +# generic type over the guest labels, and a mapping added afterwards only stops +# a later relabel from changing what is already wrong. An artifact mapping +# added before the exclusions loses to them, because the later expression wins. +my $moved = '/srv/xcat-images'; +my $midpath = "$moved/netboot/rootimg/rhels9/x86_64/compute"; +scenario('full sequence', $moved, $midpath, sub { + my ($relabel) = @_; + add_mapping('public_content_t', "$moved(/.*)?"); + add_mapping('<>', "$moved(/.*)?/rootimg(/.*)?"); + add_mapping('<>', "$moved(/.*)?/rootimg-statelite(/.*)?"); + add_mapping('public_content_t', "$midpath/$_", 'f') foreach @expressions; + $relabel->($moved); +}); + done_testing(); diff --git a/xCAT-test/unit/selinux_docs.t b/xCAT-test/unit/selinux_docs.t index 50c8a0fd3b..28fe44e96f 100644 --- a/xCAT-test/unit/selinux_docs.t +++ b/xCAT-test/unit/selinux_docs.t @@ -64,6 +64,20 @@ foreach my $guest (qw(rootimg rootimg-statelite)) { like($text{$repair}, qr/\Q$guest\E/, "$repair names the $guest tree"); } +# The order of the repair is what makes it work. A relabel before the guest +# exclusions writes a generic type over the guest labels, and an artifact +# mapping read before them loses to them. +my $exclusion = index($text{$repair}, "-t '<>'"); +my $artifact = index($text{$repair}, '-f f'); +my $relabel = index($text{$repair}, 'restorecon -R'); +my $last_map = rindex($text{$repair}, 'semanage fcontext -a'); +cmp_ok($exclusion, '>', 0, "$repair excludes the guest trees with <>"); +cmp_ok($artifact, '>', $exclusion, + "$repair maps a published artifact after the guest exclusions"); +cmp_ok($relabel, '>', $last_map, "$repair relabels after the last mapping"); +my $relabels = () = $text{$repair} =~ /restorecon -R/g; +is($relabels, 1, "$repair relabels once, and it relabels $relabels time(s)"); + my $fc = read_text("$root/xCAT-selinux/xcat.fc"); unlike($fc, qr/chcon/, 'xcat.fc advises no chcon'); like($fc, qr/semanage fcontext/, 'xcat.fc names the command that maps a path'); From e9f27f139b2089b9b2f2a31b10fdb4c19581506d Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:56:50 -0300 Subject: [PATCH 90/91] fix(xcat-core): the documented repair relabels before the guest exclusions exist The SELinux page carried the repair in two blocks. The first mapped the published artifacts and ran restorecon over the image root. The second mapped the publication directory and excluded both guest trees. An operator with site.installdir=/srv/xcat-install who reads the page in order therefore relabels before any mapping covers that tree, and rootimg/etc/shadow resolves to var_t. The exclusion added afterwards keeps the var_t it finds, because it only stops the next relabel from changing the label again. The order also cost the artifacts. file_contexts keeps the expressions in the order they are read and the last one that matches a path wins, so the exclusions of the second block beat the artifact mappings of the first. Where the image root carries a rootimg component in the middle, the exclusion matches the artifacts as well, and the five expressions with a wildcard, the initrds and the packed images, resolve <>. kernel and hypervisor carry no wildcard and win either way, which is why the defect showed on a subset. The page is now one sequence: the publication directory, both guest exclusions, the artifact mappings, then one restorecon. It says what each step orders and why. xCAT-test/native/selinux_image_repair.t passes 381 of 381 checks on this sequence and fails 47 on the order of the parent commit. selinux_docs.t fails 3 of 30 on the parent commit. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- docs/source/advanced/selinux/index.rst | 58 +++++++++++++++++--------- 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/docs/source/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst index 95e20525c6..d8f4df8234 100644 --- a/docs/source/advanced/selinux/index.rst +++ b/docs/source/advanced/selinux/index.rst @@ -90,25 +90,51 @@ another type, from before the package was installed. ``restorecon`` over the publication directory cannot repair it, with or without ``-F``, because the path has no context to apply. Give it one. -``site.installdir`` selects the publication directory. Read it, and map each -published artifact of that one image root:: +``site.installdir`` selects the publication directory. Add the mappings in this +order, and relabel once at the end:: installdir=$(lsdef -t site -i installdir -c | sed 's/^.*=//; s:/*$::') imgroot=$installdir/netboot/rootimg/rhels9/x86_64/compute + # 1. The publication directory, when site.installdir is not /install. The + # packaged mappings name /install and cover no other directory. + semanage fcontext -a -t public_content_t "$installdir(/.*)?" + + # 2. Both guest trees, before anything relabels them. + semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg(/.*)?" + semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg-statelite(/.*)?" + + # 3. The published artifacts of the one image root, after the exclusions. for name in kernel hypervisor 'initrd[^/]*' 'rootimg\.[^/]*' \ 'rootimg-statelite\.[^/]*' 'rootimgtree\.[^/]*' \ 'litefile\.csv' 'common\.filelist'; do semanage fcontext -a -t public_content_t -f f "$imgroot/$name" done - restorecon -R -v "$imgroot" -Each expression names one regular file directly below the image root, so no -path in ``$imgroot/rootimg`` or ``$imgroot/rootimg-statelite`` matches one. -Both guest trees keep the ``<>`` of the packaged mappings, and -``restorecon`` leaves every file in them alone. ``file_contexts.local`` is read -after the packaged file, and the last expression that matches a path wins, so -each mapping above wins against ``/install(/.*)?/rootimg(/.*)?``. + # 4. One relabel, with every mapping in place. + restorecon -R -v "$installdir" + +Steps 1 and 2 come first because a relabel before them writes a generic type +over the guest labels. With ``site.installdir=/srv/xcat-install`` and no mapping +for that tree, ``rootimg/etc/shadow`` resolves to ``var_t``. A mapping added +after such a relabel only stops the next one from changing what is already +wrong. + +Step 3 comes after step 2 because ``file_contexts`` keeps the expressions in the +order they are read, and the last one that matches a path wins. +``$installdir(/.*)?/rootimg(/.*)?`` matches ``$imgroot`` itself when the image +root carries a ``rootimg`` component in the middle, so it matches the published +artifacts too. Read after the exclusions, each artifact mapping wins against +them. Read before, the artifacts resolve to ``<>``. An expression with no +wildcard, such as ``kernel``, wins either way, so the defect shows on the +initrds and the packed images alone. + +Step 4 runs once. Each expression in step 3 names one regular file directly +below the image root, so no path in ``$imgroot/rootimg`` or +``$imgroot/rootimg-statelite`` matches one, and ``restorecon`` leaves every file +in both guest trees alone. Under the standard ``/install`` the packaged +mappings already carry steps 1 and 2, and ``file_contexts.local`` is read after +the packaged file, so step 3 still wins. Do not repair a label with ``chcon``, and do not map the image root as a tree. ``chcon`` writes a type that no mapping selects, so the next relabel of a path @@ -116,19 +142,13 @@ that has a mapping reverts it, and a recursive ``chcon`` relabels both guest trees as well. A tree mapping over the image root relabels them through ``restorecon`` instead. -The packaged mappings name ``/install``. A site that moved ``site.installdir`` -maps the configured directory, and keeps both guest trees out of that mapping:: - - semanage fcontext -a -t public_content_t "$installdir(/.*)?" - semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg(/.*)?" - semanage fcontext -a -t '<>' "$installdir(/.*)?/rootimg-statelite(/.*)?" - restorecon -R -v "$installdir" - A mapping is persistent, so a later recursive relabel and a policy upgrade both keep the result. ``xCAT-test/native/selinux_image_repair.t`` starts with the wrong type on every published artifact and valid types in both guest trees, -runs each procedure, and reads the labels back after a recursive relabel and -after a reinstall of the module. +runs the four steps in order, and reads the labels back after a recursive +relabel and after a reinstall of the module. It does that for a moved +``installdir`` whose image root also carries a ``rootimg`` component in the +middle, which is the layout that needs every step. The unit holds ``/opt/xcat`` as the default prefix, and ``%post`` writes ``/etc/xcat/xcatroot.env`` with the prefix of the installation, which the unit From 87f9e886d9ed0baeb5659f649547f78bb1ce84e6 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:45:54 -0300 Subject: [PATCH 91/91] fix(xcat-core): xCAT-selinux is built for openSUSE, which has no selinux-policy-devel xcat-core-build-opensuse #42 failed on three packages whose only error was "No matching package to install: selinux-policy-devel", and took the whole openSUSE family of xcat-ci #146 down with it. openSUSE Leap ships no selinux-policy-devel, so the policy module has nothing to compile against. package_skip_reason in build-utils/lib/XCAT/BuildUtils.pm tested the target against /\Aopeneuler-/, because openEuler was the one non-EL family buildrpms.pl targeted when the guard was written. openSUSE was enabled afterwards and matches no arm of that test, so the EL-only package was selected for it. The test is now on EL rather than on the families that are not EL, so a family added later skips an EL-only package instead of trying to build it. selinux_el_only_scope.t gains the two openSUSE targets. Without this change its two new assertions fail and the other 35 pass. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- build-utils/lib/XCAT/BuildUtils.pm | 20 ++++++++++++++++---- xCAT-test/unit/selinux_el_only_scope.t | 15 +++++++++++++-- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/build-utils/lib/XCAT/BuildUtils.pm b/build-utils/lib/XCAT/BuildUtils.pm index 36571f5fdf..512e70d087 100644 --- a/build-utils/lib/XCAT/BuildUtils.pm +++ b/build-utils/lib/XCAT/BuildUtils.pm @@ -813,17 +813,29 @@ sub cancel_build { # or chronyd_manage_pid_files(). m4 leaves an undefined interface name in its # output, and checkmodule stops on it. openEuler 24.03sp4 carries # selinux-policy 40.7 and does compile the module, and is excluded too, so no -# openEuler release ships a package the other releases cannot build. +# openEuler release ships a package the other releases cannot build. openSUSE +# Leap ships no selinux-policy-devel at all. my %EL_ONLY_PACKAGES = ( 'xCAT-selinux' => 'SELinux support is EL only', ); -# Why $pkg is not built for $target, or undef when the pair is built. openEuler -# is the one non-EL family buildrpms.pl targets. +# The EL build targets, named positively: alma+epel-- for the three EL +# releases, and the suffixed rocky target mock cross-builds riscv64 through. +my $EL_TARGET = qr/\A(?:alma|rocky|centos|rhel)(?:\+epel)?-/; + +# Why $pkg is not built for $target, or undef when the pair is built. The test is +# on EL rather than on the families that are not EL, so a family added later +# skips an EL-only package instead of trying to build it. openSUSE was added +# after this guard and matched neither arm of a /\Aopeneuler-/ test, so +# xcat-core-build-opensuse #42 spent three attempts on "No matching package to +# install: selinux-policy-devel" and failed the whole openSUSE family. sub package_skip_reason { my ($pkg, $target) = @_; my $reason = $EL_ONLY_PACKAGES{ $pkg // '' } or return undef; - return undef unless defined($target) && $target =~ /\Aopeneuler-/; + # No target names no platform. buildrpms.pl always has one; a caller that + # does not is asking about the package, not about a pair. + return undef unless defined($target) && length($target); + return undef if $target =~ $EL_TARGET; return $reason; } diff --git a/xCAT-test/unit/selinux_el_only_scope.t b/xCAT-test/unit/selinux_el_only_scope.t index 296c88d7d2..98f9ff22d9 100644 --- a/xCAT-test/unit/selinux_el_only_scope.t +++ b/xCAT-test/unit/selinux_el_only_scope.t @@ -23,6 +23,15 @@ my @openeuler_targets = qw( openeuler-24.03sp4-x86_64 openeuler-24.03-ppc64le ); +# openSUSE Leap ships no selinux-policy-devel at all, so the module has nothing +# to compile against. The guard this test was written with named openEuler, and +# openSUSE was enabled afterwards: xcat-core-build-opensuse #42 spent three +# attempts on "No matching package to install: selinux-policy-devel" and took +# the whole openSUSE family down with it. +my @opensuse_targets = qw( + opensuse-leap-15.6-x86_64 + opensuse-leap-42.3-x86_64 +); my @el_targets = qw( alma+epel-8-x86_64 alma+epel-9-x86_64 @@ -34,9 +43,9 @@ my $decides = XCAT::BuildUtils->can('package_skip_reason'); ok($decides, 'BuildUtils decides which packages a target builds'); SKIP: { - skip 'BuildUtils has no build-plan decision', 17 unless $decides; + skip 'BuildUtils has no build-plan decision', 20 unless $decides; - foreach my $target (@openeuler_targets) { + foreach my $target (@openeuler_targets, @opensuse_targets) { ok($decides->('xCAT-selinux', $target), "xCAT-selinux is not built for $target"); } @@ -51,6 +60,8 @@ SKIP: { xCAT-genesis-scripts xCAT-test xCAT-release)) { is($decides->($pkg, 'openeuler-22.03sp4-x86_64'), undef, "$pkg is built for openEuler"); + is($decides->($pkg, 'opensuse-leap-15.6-x86_64'), undef, + "$pkg is built for openSUSE"); } }