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 001/129] 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 002/129] 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 003/129] 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 004/129] 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 005/129] 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 006/129] 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 007/129] 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 008/129] 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 009/129] 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 010/129] 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 011/129] 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 012/129] 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 013/129] 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 014/129] 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 015/129] 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 016/129] 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 017/129] 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 018/129] 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 019/129] 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 020/129] 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 021/129] 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 022/129] 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 023/129] 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 024/129] 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 025/129] 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 026/129] 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 027/129] 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 028/129] 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 029/129] 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 030/129] 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 031/129] 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 032/129] 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 033/129] 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 034/129] 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 035/129] 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 036/129] 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 037/129] 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 038/129] 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 039/129] 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 040/129] 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 041/129] 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 042/129] 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 043/129] 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 044/129] 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 045/129] 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 046/129] 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 047/129] 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 048/129] 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 049/129] 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 050/129] 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 051/129] 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 052/129] 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 053/129] 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 054/129] 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 055/129] 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 056/129] 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 057/129] 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 058/129] 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 059/129] 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 060/129] 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 061/129] 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 062/129] 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 063/129] 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 064/129] 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 40805772bca05c11ceb440eaacfa00706269c9fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:47:41 -0300 Subject: [PATCH 065/129] fix(build): refresh RPM metadata after signing RPM signing can change bytes without changing the file size or whole-second modification time used by the metadata cache. Rebuild binary and source indexes after signing so their checksums describe the final RPMs. Keep incremental indexing for unsigned builds. --- buildrpms.pl | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/buildrpms.pl b/buildrpms.pl index 3cdec4d62e..eff22a94d2 100755 --- a/buildrpms.pl +++ b/buildrpms.pl @@ -676,9 +676,10 @@ sub setup_local_repos { # # Nothing this project ships reads the sqlite metadata. dnf on el8+ and zypper both read the XML. sub createrepo_dir { - my ($dir, $extra) = @_; + my ($dir, $extra, $fresh) = @_; $extra //= ''; - sh_or_die(qq(createrepo_c --update ) + my $update = $fresh ? '' : '--update'; + sh_or_die(qq(createrepo_c $update ) . qq(--revision "$SOURCE_DATE_EPOCH" --set-timestamp-to-revision $extra "$dir"), "Failed to createrepo_c $dir\n"); } @@ -689,7 +690,7 @@ sub createrepo_dir { # top-level strays; then index the binaries EXCLUDING the SRPMS/ subdir so no # src.rpm enters the binary repomd, and index the SRPMS repo separately. sub index_repo { - my ($repodir) = @_; + my ($repodir, $fresh) = @_; my $alias = "$repodir/xCAT-release-latest.noarch.rpm"; # The stable bootstrap filename is a direct-download convenience, not a @@ -705,9 +706,9 @@ sub index_repo { # replace good metadata with metadata for an empty repo -- publishing a repo that # resolves nothing. Leave it exactly as the last binary build left it and index # only the srpms. - createrepo_dir($repodir, "--excludes 'SRPMS/*' --excludes '*.src.rpm'") + createrepo_dir($repodir, "--excludes 'SRPMS/*' --excludes '*.src.rpm'", $fresh) unless $opts{source_only}; - createrepo_dir("$repodir/SRPMS") if -d "$repodir/SRPMS"; + createrepo_dir("$repodir/SRPMS", '', $fresh) if -d "$repodir/SRPMS"; } sub update_repo { @@ -755,8 +756,8 @@ sub sign_repo_dir { "Failed to sign SRPMs in $repodir/SRPMS"); } - # Regenerate both indexes (binary + SRPMS) after signing, before signing repomd. - index_repo($repodir); + # Signing can change RPM bytes without changing the size or timestamp used by the metadata cache. + index_repo($repodir, 1); for my $rd ("$repodir/repodata", (-d "$repodir/SRPMS/repodata" ? ("$repodir/SRPMS/repodata") : ())) { From d90c9e6f53f5bba37a1640500e5853c0de8e5beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:48:39 -0300 Subject: [PATCH 066/129] test(build): verify signed repository package checksums --- xCAT-test/native/README.md | 11 ++-- .../native/fixtures/rpmsign-preserve-mtime.sh | 23 ++++++++ xCAT-test/native/release_repository.t | 59 +++++++++++++++---- 3 files changed, 75 insertions(+), 18 deletions(-) create mode 100644 xCAT-test/native/fixtures/rpmsign-preserve-mtime.sh diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 71401eaa8c..d3089e6ff3 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -56,11 +56,12 @@ prove xCAT-test/native/probe_package_payload.t \ They need RPM build/query tools, cpio, createrepo_c, zstd, rsync, GnuPG, Python 3 with RPM bindings, user/mount namespaces, and the Perl modules Capture::Tiny, -File::Slurper, Parallel::ForkManager and XML::LibXML. The probe command also -needs `which`. The release test uses an ephemeral signing key and removes its -agent. These checks inspect real packages and repository output; they do not -qualify package installation on every target architecture. On EL8, install both -`python36` and `python3-rpm` to provide the interpreter and its RPM bindings. +Digest::SHA, File::Slurper, Parallel::ForkManager and XML::LibXML. The probe +command also needs `which`. The release test uses an ephemeral signing key and +removes its agent. These checks inspect real packages and repository output; +they do not qualify package installation on every target architecture. On EL8, +install both `python36` and `python3-rpm` to provide the interpreter and its RPM +bindings. The Debian probe permission test has a separate pull-request CI step. It needs Debian build tools, BATS, bubblewrap, fakeroot, reprepro and diff --git a/xCAT-test/native/fixtures/rpmsign-preserve-mtime.sh b/xCAT-test/native/fixtures/rpmsign-preserve-mtime.sh new file mode 100644 index 0000000000..1366afe4d6 --- /dev/null +++ b/xCAT-test/native/fixtures/rpmsign-preserve-mtime.sh @@ -0,0 +1,23 @@ +#!/bin/sh +set -eu + +# Preserve timestamps so checksum coverage does not depend on signing within one clock tick. +timestamps=$(mktemp -d) +trap 'rm -rf -- "$timestamps"' EXIT +index=0 +for package do + if [ -f "$package" ]; then + touch -r "$package" "$timestamps/$index" + fi + index=$((index + 1)) +done + +"$XCAT_TEST_RPMSIGN" "$@" + +index=0 +for package do + if [ -f "$timestamps/$index" ]; then + touch -r "$timestamps/$index" "$package" + fi + index=$((index + 1)) +done diff --git a/xCAT-test/native/release_repository.t b/xCAT-test/native/release_repository.t index dc131a98e5..a1e072eb57 100644 --- a/xCAT-test/native/release_repository.t +++ b/xCAT-test/native/release_repository.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use Digest::SHA qw(sha256_hex); use File::Basename qw(dirname); use File::Copy qw(copy); use File::Path qw(make_path); @@ -55,13 +56,26 @@ copy("$root/RPMS/noarch/$rpm", "$root/input/$rpm") or die $!; copy("$root/SRPMS/$srpm", "$root/input/SRPMS/$srpm") or die $!; copy("$root/RPMS/noarch/$rpm", "$root/input/xCAT-release-latest.noarch.rpm") or die $!; +my $rpmsign = command($root, 'sh', '-c', 'command -v rpmsign'); +chomp $rpmsign; +make_path("$root/bin"); +copy(repo_path('xCAT-test/native/fixtures/rpmsign-preserve-mtime.sh'), "$root/bin/rpmsign") or die $!; +chmod 0755, "$root/bin/rpmsign" or die $!; +local $ENV{XCAT_TEST_RPMSIGN} = $rpmsign; +local $ENV{PATH} = "$root/bin:$ENV{PATH}"; + for my $signed (0, 1) { for my $attempt (1, 2) { + my $before = $signed && $attempt == 1 ? package_stats("$root/input") : undef; command("$root/work", $^X, 'buildrpms.pl', '--merge-core-repos', '--target', 'alma+epel-10-x86_64', '--release', '1', '--output-dir', "$root/output", '--input-core-repos', "$root/input", $signed ? ('--gpg-sign', '--gpg-key-name', 'package@example.test') : ()); - check_repository("$root/output", $signed, "merge signed=$signed run=$attempt"); + check_repository("$root/output", $signed, "merge signed=$signed run=$attempt", $before); + if ($signed) { + copy("$root/output/$rpm", "$root/input/$rpm") or die $!; + copy("$root/output/SRPMS/$srpm", "$root/input/SRPMS/$srpm") or die $!; + } } } @@ -74,12 +88,15 @@ command($root, 'cp', '-a', repo_path('xCAT-release'), "$root/work/xCAT-release") write_text("$root/mock/xCAT-release-$target.cfg", "# cached build\n"); write_text("$root/os-release", "ID=almalinux\nVERSION_ID=10\n"); local $ENV{BUILD_FIXTURE} = $root; -command("$root/work", 'unshare', '--user', '--map-root-user', '--mount', - 'bash', repo_path('xCAT-test/native/fixtures/buildrpms-namespace.sh'), - 'sh', '-c', 'trap \'gpgconf --homedir "$GNUPGHOME" --kill gpg-agent\' EXIT; "$@"', 'sign-test', - $^X, 'buildrpms.pl', '--package', 'xCAT-release', '--target', $target, - '--release', '1', '--nproc', '1', '--gpg-sign', '--gpg-key-name', 'package@example.test'); -check_repository($cached, 1, 'cached build finalization'); +for my $attempt (1, 2) { + my $before = $attempt == 1 ? package_stats($cached) : undef; + command("$root/work", 'unshare', '--user', '--map-root-user', '--mount', + 'bash', repo_path('xCAT-test/native/fixtures/buildrpms-namespace.sh'), + 'sh', '-c', 'trap \'gpgconf --homedir "$GNUPGHOME" --kill gpg-agent\' EXIT; "$@"', 'sign-test', + $^X, 'buildrpms.pl', '--package', 'xCAT-release', '--target', $target, + '--release', '1', '--nproc', '1', '--gpg-sign', '--gpg-key-name', 'package@example.test'); + check_repository($cached, 1, "cached build finalization run=$attempt", $before); +} write_text("$root/work/schedule.pl", <<'PERL'); BEGIN { @@ -134,17 +151,31 @@ sub primary_packages { return XML::LibXML->load_xml(string => $xml)->findnodes('//*[local-name()="package"]'); } +sub package_stats { + my ($directory) = @_; + return {map { $_ => [(stat("$directory/$_"))[7, 9]] } ($rpm, "SRPMS/$srpm")}; +} + sub check_repository { - my ($directory, $signed, $label) = @_; + my ($directory, $signed, $label, $before) = @_; + is_deeply(package_stats($directory), $before, "$label signing preserves package sizes and mtimes") + if $before; my $alias = "$directory/xCAT-release-latest.noarch.rpm"; ok(-f $alias, "$label publishes the alias") or die('missing bootstrap alias'); is(read_binary($alias), read_binary("$directory/$rpm"), "$label alias has final RPM bytes"); is((stat($alias))[2] & 0777, 0644, "$label alias is readable"); - my @packages = primary_packages($directory); - is(scalar(@packages), 1, "$label indexes the release package once"); - for my $package (@packages) { - my ($location) = $package->findnodes('./*[local-name()="location"]'); - is($location->getAttribute('href'), $rpm, "$label indexes the versioned filename only"); + for my $entry ([$directory, $rpm], ["$directory/SRPMS", $srpm]) { + my ($repo, $filename) = @$entry; + my @indexed = primary_packages($repo); + is(scalar(@indexed), 1, "$label indexes one $filename"); + for my $package (@indexed) { + my ($location) = $package->findnodes('./*[local-name()="location"]'); + is($location->getAttribute('href'), $filename, "$label locates $filename"); + my ($checksum) = $package->findnodes('./*[local-name()="checksum"]'); + is($checksum->getAttribute('type'), 'sha256', "$label uses SHA256 for $filename"); + is($checksum->textContent, sha256_hex(read_binary("$repo/$filename")), + "$label metadata matches final $filename bytes"); + } } if ($signed) { for my $repo ($directory, "$directory/SRPMS") { @@ -153,5 +184,7 @@ sub check_repository { my $signature = command($root, 'rpm', '-qp', '--qf', '%{RSAHEADER:pgpsig}', $alias); like($signature, qr/RSA.*Key ID/i, "$label alias carries the package signature"); isnt(read_binary($alias), read_binary("$root/RPMS/noarch/$rpm"), "$label signing changed the unsigned RPM"); + isnt(read_binary("$directory/SRPMS/$srpm"), read_binary("$root/SRPMS/$srpm"), + "$label signing changed the unsigned SRPM"); } } 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 067/129] 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 068/129] 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 069/129] 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 070/129] 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 071/129] 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 072/129] 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 33fee7bb0d98efedc3fa83621ccfa4324e492191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:39:28 -0300 Subject: [PATCH 073/129] test(netboot): resolve the shell mount target in profile tests Older bubblewrap releases reject a symlink mount destination. Bind Bash over the resolved shell path without changing the profile cases. --- xCAT-test/native/netboot_profile_riscv64.t | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/xCAT-test/native/netboot_profile_riscv64.t b/xCAT-test/native/netboot_profile_riscv64.t index be5109d4c9..9d92e00e01 100644 --- a/xCAT-test/native/netboot_profile_riscv64.t +++ b/xCAT-test/native/netboot_profile_riscv64.t @@ -4,6 +4,8 @@ use warnings; ## no critic (Modules::RequireFilenameMatchesPackage) use FindBin; +use Cwd qw(abs_path); +use File::Basename qw(basename); use lib "$FindBin::Bin/../lib"; use lib "$FindBin::Bin/../../perl-xCAT"; use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; @@ -80,7 +82,7 @@ for my $family (@families) { for my $pass (1, 2) { # EL uses Bash as /bin/sh for these postinstall scripts. my ($status, $output) = sandbox_run($root, - {read_only => {repo_path('.') => repo_path('.'), '/bin/bash' => '/bin/sh'}}, + {read_only => {repo_path('.') => repo_path('.'), '/bin/bash' => '/bin/' . basename(abs_path('/bin/sh'))}}, $postinstall, '/target', $osver, 'riscv64', $profile); is($status, 0, "pass $pass executes the selected script") or diag($output); is(read_text("$root/etc/fstab"), "host fstab\n", "pass $pass leaves the host fstab unchanged"); 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 074/129] 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 ce335ba3b3c8b10106808c3ced5ecd077dd05cc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:39:47 -0300 Subject: [PATCH 075/129] fix(netboot): correct SELinux assignments in postinstall profiles Match the complete enforcing or permissive setting. Preserve comments and whitespace, and do not change unrelated lines or create a missing policy file. --- .../share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall | 2 +- .../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 +- 11 files changed, 11 insertions(+), 11 deletions(-) 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..c5fcc45dfa 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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.ppc64le.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall index dd2576c8f7..9028a7b75b 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..c5fcc45dfa 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..fa1737a632 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..1787b10290 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..9028a7b75b 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..c5fcc45dfa 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..9028a7b75b 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..c5fcc45dfa 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..a0707a17b5 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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..c69a051426 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/^\([[:blank:]]*SELINUX=\)\(enforcing\|permissive\)\([[:blank:]]*\(#.*\)\{0,1\}\)$/\1disabled\3/' "$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 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 076/129] 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 402f398bb17504034ade8e8b4042fb41d3b1ead0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:41:31 -0300 Subject: [PATCH 077/129] test(netboot): cover SELinux settings across postinstall profiles Execute all affected owners and their aliases in isolated image roots. Check policy contents and metadata, missing files, repeated runs and host sentinels. Run the cases in Ubuntu and EL CI. --- .github/workflows/xcat_test.yml | 5 +- xCAT-test/native/README.md | 12 ++- .../native/netboot_profile_postinstall.t | 99 +++++++++++++++++++ xCAT-test/native/netboot_profile_riscv64.t | 2 - 4 files changed, 112 insertions(+), 6 deletions(-) create mode 100644 xCAT-test/native/netboot_profile_postinstall.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 629fc208f0..f95d697dd3 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -102,7 +102,7 @@ jobs: run: | log=$(mktemp) trap 'rm -f -- "$log"' EXIT - prove -v xCAT-test/native/install_profile_riscv64.t xCAT-test/native/netboot_profile_riscv64.t xCAT-test/native/builddebs_riscv64.t xCAT-test/native/ubuntu_subiquity_template.t | tee "$log" + prove -v xCAT-test/native/install_profile_riscv64.t xCAT-test/native/netboot_profile_riscv64.t xCAT-test/native/netboot_profile_postinstall.t xCAT-test/native/builddebs_riscv64.t xCAT-test/native/ubuntu_subiquity_template.t | tee "$log" ! grep -qi skipped "$log" rpm_lifecycle_test: runs-on: ubuntu-24.04 @@ -131,3 +131,6 @@ jobs: - name: Test FIPS package artifacts if: ${{ !cancelled() }} run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/fips_package_payload.t' + - name: Test netboot postinstall profiles + if: ${{ !cancelled() }} + run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/netboot_profile_postinstall.t' diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 71401eaa8c..000481f3ca 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -374,6 +374,7 @@ user with Bubblewrap and unprivileged user namespaces enabled: ``` prove xCAT-test/native/install_profile_riscv64.t \ xCAT-test/native/netboot_profile_riscv64.t \ + xCAT-test/native/netboot_profile_postinstall.t \ xCAT-test/native/builddebs_riscv64.t \ xCAT-test/native/ubuntu_subiquity_template.t ``` @@ -386,13 +387,18 @@ The Debian case needs debhelper, devscripts, fakeroot, and reprepro, and skips on non-Debian hosts. Each case creates its own temporary files and database. The temporary directory must allow execution; set TMPDIR if /tmp is noexec. Sandbox commands require GNU timeout and have a 45-second limit. -Pull-request CI runs these cases and rejects whole-file skips. The permissive -SELinux case records an existing postinstall defect as TODO, without changing -production behavior. +Pull-request CI runs these cases and rejects whole-file skips. The netboot case executes the selected postinstall file directly. Its private /bin/sh uses Bash, as on EL, including when the test host uses another shell. +`netboot_profile_postinstall.t` runs the affected EL postinstall owners and +their distro and service aliases. It checks the resulting SELinux settings, +missing files, comments, repeated execution, permissions, ownership and host +sentinels. It uses the same sandbox and Perl dependencies. CI runs it on +Ubuntu, EL8 and EL10. It executes host tools against private image roots; +it does not boot the target architecture or verify kernel SELinux state. + The Subiquity case replaces downloads and external commands, and uses a loopback install-monitor peer. It does not install an operating system. Architecture names in these fixtures do not qualify native firmware or boot diff --git a/xCAT-test/native/netboot_profile_postinstall.t b/xCAT-test/native/netboot_profile_postinstall.t new file mode 100644 index 0000000000..aa1a8f2dc9 --- /dev/null +++ b/xCAT-test/native/netboot_profile_postinstall.t @@ -0,0 +1,99 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use FindBin; +use lib "$FindBin::Bin/../lib"; +use Cwd qw(abs_path); +use File::Basename qw(basename); +use File::Find qw(find); +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use Test::More; +use XCAT::Test::File qw(repo_path); +use XCAT::Test::Sandbox qw(sandbox_root sandbox_run); + +plan skip_all => 'postinstall execution requires Linux' unless $^O eq 'linux'; +my $netboot = repo_path('xCAT-server/share/xcat/netboot'); +my @owners = qw( + rh/compute.rhels7.ppc64.postinstall + rh/compute.rhels7.x86_64.postinstall + rh/compute.rhels8.ppc64le.postinstall + rh/compute.rhels8.x86_64.postinstall + rh/compute.rhels9.ppc64le.postinstall + rh/compute.rhels9.x86_64.postinstall + rh/compute.rhels10.aarch64.postinstall + rh/compute.rhels10.ppc64le.postinstall + rh/compute.rhels10.x86_64.postinstall + rh/service.postinstall + rocky/compute.rocky10.riscv64.postinstall +); +my %owners; +for my $owner (@owners) { + ok(-x "$netboot/$owner", "$owner is executable"); + $owners{abs_path("$netboot/$owner")} = 1; +} +my @aliases; +find({no_chdir => 1, wanted => sub { + return unless -l $_ && /[.]postinstall$/; + my $target = abs_path($_); + push @aliases, substr($_, length($netboot) + 1) if defined $target && $owners{$target}; +}}, $netboot); +ok(@aliases, 'finds profile aliases for the affected owners'); + +my $unchanged = "# SELINUX=enforcing or permissive\nSELINUXTYPE=targeted\n" . + "OTHER_SELINUX=permissive\n#SELINUX=permissive\n"; +my @cases = ( + ['enforcing', "SELINUX=enforcing\n", "SELINUX=disabled\n"], + ['permissive', "SELINUX=permissive\n", "SELINUX=disabled\n"], + ['disabled', "SELINUX=disabled\n", "SELINUX=disabled\n"], + ['absent', undef, undef], + ['no assignment', '', ''], + ['whitespace and comments', "\tSELINUX=permissive \t# image policy\n", + "\tSELINUX=disabled \t# image policy\n"], + ['enforcing comment', "SELINUX=enforcing # image policy\n", + "SELINUX=disabled # image policy\n"], +); + +for my $relative (@owners, sort @aliases) { + my @selected = -l "$netboot/$relative" ? ($cases[1]) : @cases; + for my $case (@selected) { + my ($label, $input, $expected) = @$case; + subtest "$relative: $label" => sub { + my $root = sandbox_root(); + my $image = "$root/target"; + make_path("$image/etc/selinux", "$root/etc/selinux"); + my $host_policy = "SELINUX=enforcing\n# host policy\n"; + write_text("$root/etc/selinux/config", $host_policy); + write_text("$root/etc/fstab", "host fstab\n"); + write_text("$root/etc/inittab", "host inittab\n"); + my $config = "$image/etc/selinux/config"; + if (defined $input) { + write_text($config, $input . $unchanged); + chmod 0640, $config or die "chmod $config: $!"; + } + my @metadata = defined $input ? (stat($config))[2, 4, 5] : (); + my ($profile, $osver, $arch) = split /[.]/, basename($relative); + for my $pass (1, 2) { + my ($status, $output) = sandbox_run($root, + {read_only => {repo_path('.') => repo_path('.'), '/bin/bash' => '/bin/' . basename(abs_path('/bin/sh'))}}, + "$netboot/$relative", '/target', $osver, $arch // '', $profile); + is($status, 0, "pass $pass executes the profile") or diag($output); + is($output, '', "pass $pass has no shell errors"); + is(read_text("$root/etc/selinux/config"), $host_policy, 'host policy is unchanged'); + is(read_text("$root/etc/fstab"), "host fstab\n", 'host fstab is unchanged'); + is(read_text("$root/etc/inittab"), "host inittab\n", 'host inittab is unchanged'); + if (defined $input) { + is(read_text($config), $expected . $unchanged, + "pass $pass changes only the active SELinux mode"); + is_deeply([(stat($config))[2, 4, 5]], \@metadata, + 'policy permissions and ownership are preserved'); + } else { + ok(!-e $config, 'absent policy remains absent'); + } + } + }; + } +} + +done_testing(); diff --git a/xCAT-test/native/netboot_profile_riscv64.t b/xCAT-test/native/netboot_profile_riscv64.t index 9d92e00e01..d993577a22 100644 --- a/xCAT-test/native/netboot_profile_riscv64.t +++ b/xCAT-test/native/netboot_profile_riscv64.t @@ -90,8 +90,6 @@ 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"); } From 88915f34cf2f52e9968eef23ce515f3ba44c5078 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:42:30 -0300 Subject: [PATCH 078/129] fix(netboot): use POSIX firewalld checks in postinstall profiles Use separate test commands under /bin/sh. Remove regular files and symlinks, including dangling links, while retaining absent entries and directories. --- .../xcat/netboot/rh/compute.rhels10.aarch64.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels10.ppc64le.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels10.x86_64.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels8.ppc64le.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels8.x86_64.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels9.ppc64le.postinstall | 8 ++++---- .../xcat/netboot/rh/compute.rhels9.x86_64.postinstall | 8 ++++---- .../netboot/rocky/compute.rocky10.riscv64.postinstall | 8 ++++---- 8 files changed, 32 insertions(+), 32 deletions(-) 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 c5fcc45dfa..be42313772 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall @@ -42,14 +42,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 9028a7b75b..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall @@ -43,14 +43,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 c5fcc45dfa..be42313772 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 @@ -42,14 +42,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 9028a7b75b..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall @@ -43,14 +43,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 c5fcc45dfa..be42313772 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 @@ -42,14 +42,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 9028a7b75b..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall @@ -43,14 +43,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 c5fcc45dfa..be42313772 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 @@ -42,14 +42,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi 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 c69a051426..1e7ea3d54e 100755 --- a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall +++ b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall @@ -42,14 +42,14 @@ 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" -if [[ -f "$FIREWALLD" || -L "$FIREWALLD" ]] +if [ -f "$FIREWALLD" ] || [ -L "$FIREWALLD" ] then - rm -f $FIREWALLD + rm -f "$FIREWALLD" fi FIREWALLD1="$installroot/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service" -if [[ -f "$FIREWALLD1" || -L "$FIREWALLD1" ]] +if [ -f "$FIREWALLD1" ] || [ -L "$FIREWALLD1" ] then - rm -f $FIREWALLD1 + rm -f "$FIREWALLD1" fi From 8c6ba3b2c028c90c2ddfc16a5651e4068384537f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:44:10 -0300 Subject: [PATCH 079/129] test(netboot): exercise firewalld cleanup with Bash and dash Execute each profile through /bin/sh. Check both firewalld entries as regular files, valid links, dangling links, directories and missing paths. Preserve unit targets, unrelated links and the older profiles without this cleanup. --- .github/workflows/xcat_test.yml | 2 +- xCAT-test/native/README.md | 3 + .../native/netboot_profile_postinstall.t | 228 +++++++++++++----- 3 files changed, 169 insertions(+), 64 deletions(-) diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index f95d697dd3..99a69a413c 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -123,7 +123,7 @@ 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 perl-DBI perl-DBD-SQLite perl-JSON perl-XML-Simple rpm-build bubblewrap systemd chkconfig initscripts tar gzip bzip2 which diffutils httpd curl procps-ng openssl + dnf --enablerepo=${{ matrix.repository }} install -y perl perl-Capture-Tiny perl-File-Slurper perl-Test-Simple perl-DBI perl-DBD-SQLite perl-JSON perl-XML-Simple rpm-build bubblewrap dash systemd chkconfig initscripts tar gzip bzip2 which diffutils httpd curl procps-ng openssl - name: Enable lifecycle test namespaces run: sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - name: Test RPM package lifecycle diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 000481f3ca..e05949b662 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -398,6 +398,9 @@ missing files, comments, repeated execution, permissions, ownership and host sentinels. It uses the same sandbox and Perl dependencies. CI runs it on Ubuntu, EL8 and EL10. It executes host tools against private image roots; it does not boot the target architecture or verify kernel SELinux state. +Both Bash and dash are required. The firewalld cases cover regular files, +valid and dangling symlinks, absent entries and directories under both shells. +The unit files, unrelated links and host entries must remain unchanged. The Subiquity case replaces downloads and external commands, and uses a loopback install-monitor peer. It does not install an operating system. diff --git a/xCAT-test/native/netboot_profile_postinstall.t b/xCAT-test/native/netboot_profile_postinstall.t index aa1a8f2dc9..b481b4ecea 100644 --- a/xCAT-test/native/netboot_profile_postinstall.t +++ b/xCAT-test/native/netboot_profile_postinstall.t @@ -4,18 +4,19 @@ use warnings; use FindBin; use lib "$FindBin::Bin/../lib"; -use Cwd qw(abs_path); -use File::Basename qw(basename); -use File::Find qw(find); -use File::Path qw(make_path); -use File::Slurper qw(read_text write_text); +use Cwd qw(abs_path); +use File::Basename qw(basename dirname); +use File::Find qw(find); +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use File::Spec; use Test::More; -use XCAT::Test::File qw(repo_path); +use XCAT::Test::File qw(repo_path); use XCAT::Test::Sandbox qw(sandbox_root sandbox_run); plan skip_all => 'postinstall execution requires Linux' unless $^O eq 'linux'; my $netboot = repo_path('xCAT-server/share/xcat/netboot'); -my @owners = qw( +my @owners = qw( rh/compute.rhels7.ppc64.postinstall rh/compute.rhels7.x86_64.postinstall rh/compute.rhels8.ppc64le.postinstall @@ -29,70 +30,171 @@ my @owners = qw( rocky/compute.rocky10.riscv64.postinstall ); my %owners; + for my $owner (@owners) { - ok(-x "$netboot/$owner", "$owner is executable"); - $owners{abs_path("$netboot/$owner")} = 1; + ok( -x "$netboot/$owner", "$owner is executable" ); + $owners{ abs_path("$netboot/$owner") } = 1; } my @aliases; -find({no_chdir => 1, wanted => sub { - return unless -l $_ && /[.]postinstall$/; - my $target = abs_path($_); - push @aliases, substr($_, length($netboot) + 1) if defined $target && $owners{$target}; -}}, $netboot); -ok(@aliases, 'finds profile aliases for the affected owners'); +find( + { + no_chdir => 1, + wanted => sub { + return unless -l $_ && /[.]postinstall$/; + my $target = abs_path($_); + push @aliases, substr( $_, length($netboot) + 1 ) if defined $target && $owners{$target}; + } + }, + $netboot +); +ok( @aliases, 'finds profile aliases for the affected owners' ); +my %firewalld = map { abs_path("$netboot/$_") => 1 } qw( + rh/compute.rhels8.ppc64le.postinstall + rh/compute.rhels8.x86_64.postinstall + rh/compute.rhels9.ppc64le.postinstall + rh/compute.rhels9.x86_64.postinstall + rh/compute.rhels10.aarch64.postinstall + rh/compute.rhels10.ppc64le.postinstall + rh/compute.rhels10.x86_64.postinstall + rocky/compute.rocky10.riscv64.postinstall +); +my @shells = qw(/bin/bash /bin/dash); -my $unchanged = "# SELINUX=enforcing or permissive\nSELINUXTYPE=targeted\n" . - "OTHER_SELINUX=permissive\n#SELINUX=permissive\n"; +sub shell_options { + my ($shell) = @_; + return { read_only => { repo_path('.') => repo_path('.'), $shell => '/bin/' . basename( abs_path('/bin/sh') ) } }; +} + +for my $shell (@shells) { + BAIL_OUT("Install $shell to run this test") unless -x $shell; + my $root = sandbox_root(); + write_text( "$root/bin/shell-probe", "#!/bin/sh\nprintf '%s\\n' \"\${BASH_VERSION:+bash}\"\n" ); + chmod 0755, "$root/bin/shell-probe" or die "chmod shell probe: $!"; + my ( $status, $output ) = sandbox_run( $root, shell_options($shell), '/fixture/bin/shell-probe' ); + my $expected = $shell eq '/bin/bash' ? "bash\n" : "\n"; + is( $status, 0, "$shell probe executes through its shebang" ) or diag($output); + is( $output, $expected, "/bin/sh runs the selected $shell" ); + BAIL_OUT("The sandbox did not select $shell") if $status || $output ne $expected; +} + +sub run_profile { + my ( $root, $relative, $shell ) = @_; + my ( $profile, $osver, $arch ) = split /[.]/, basename($relative); + return sandbox_run( $root, shell_options($shell), "$netboot/$relative", '/target', $osver, $arch // '', $profile ); +} + +my $unchanged = + "# SELINUX=enforcing or permissive\nSELINUXTYPE=targeted\n" . "OTHER_SELINUX=permissive\n#SELINUX=permissive\n"; my @cases = ( - ['enforcing', "SELINUX=enforcing\n", "SELINUX=disabled\n"], - ['permissive', "SELINUX=permissive\n", "SELINUX=disabled\n"], - ['disabled', "SELINUX=disabled\n", "SELINUX=disabled\n"], - ['absent', undef, undef], - ['no assignment', '', ''], - ['whitespace and comments', "\tSELINUX=permissive \t# image policy\n", - "\tSELINUX=disabled \t# image policy\n"], - ['enforcing comment', "SELINUX=enforcing # image policy\n", - "SELINUX=disabled # image policy\n"], + [ 'enforcing', "SELINUX=enforcing\n", "SELINUX=disabled\n" ], + [ 'permissive', "SELINUX=permissive\n", "SELINUX=disabled\n" ], + [ 'disabled', "SELINUX=disabled\n", "SELINUX=disabled\n" ], + [ 'absent', undef, undef ], + [ 'no assignment', '', '' ], + [ 'whitespace and comments', "\tSELINUX=permissive \t# image policy\n", "\tSELINUX=disabled \t# image policy\n" ], + [ 'enforcing comment', "SELINUX=enforcing # image policy\n", "SELINUX=disabled # image policy\n" ], ); -for my $relative (@owners, sort @aliases) { - my @selected = -l "$netboot/$relative" ? ($cases[1]) : @cases; - for my $case (@selected) { - my ($label, $input, $expected) = @$case; - subtest "$relative: $label" => sub { - my $root = sandbox_root(); - my $image = "$root/target"; - make_path("$image/etc/selinux", "$root/etc/selinux"); - my $host_policy = "SELINUX=enforcing\n# host policy\n"; - write_text("$root/etc/selinux/config", $host_policy); - write_text("$root/etc/fstab", "host fstab\n"); - write_text("$root/etc/inittab", "host inittab\n"); - my $config = "$image/etc/selinux/config"; - if (defined $input) { - write_text($config, $input . $unchanged); - chmod 0640, $config or die "chmod $config: $!"; - } - my @metadata = defined $input ? (stat($config))[2, 4, 5] : (); - my ($profile, $osver, $arch) = split /[.]/, basename($relative); - for my $pass (1, 2) { - my ($status, $output) = sandbox_run($root, - {read_only => {repo_path('.') => repo_path('.'), '/bin/bash' => '/bin/' . basename(abs_path('/bin/sh'))}}, - "$netboot/$relative", '/target', $osver, $arch // '', $profile); - is($status, 0, "pass $pass executes the profile") or diag($output); - is($output, '', "pass $pass has no shell errors"); - is(read_text("$root/etc/selinux/config"), $host_policy, 'host policy is unchanged'); - is(read_text("$root/etc/fstab"), "host fstab\n", 'host fstab is unchanged'); - is(read_text("$root/etc/inittab"), "host inittab\n", 'host inittab is unchanged'); - if (defined $input) { - is(read_text($config), $expected . $unchanged, - "pass $pass changes only the active SELinux mode"); - is_deeply([(stat($config))[2, 4, 5]], \@metadata, - 'policy permissions and ownership are preserved'); - } else { - ok(!-e $config, 'absent policy remains absent'); +for my $shell (@shells) { + for my $relative ( @owners, sort @aliases ) { + my @selected = -l "$netboot/$relative" ? ( $cases[1] ) : @cases; + for my $case (@selected) { + my ( $label, $input, $expected ) = @$case; + subtest "$relative: $shell SELinux $label" => sub { + my $root = sandbox_root(); + my $image = "$root/target"; + make_path( "$image/etc/selinux", "$root/etc/selinux" ); + my $host_policy = "SELINUX=enforcing\n# host policy\n"; + write_text( "$root/etc/selinux/config", $host_policy ); + write_text( "$root/etc/fstab", "host fstab\n" ); + write_text( "$root/etc/inittab", "host inittab\n" ); + my $config = "$image/etc/selinux/config"; + + if ( defined $input ) { + write_text( $config, $input . $unchanged ); + chmod 0640, $config or die "chmod $config: $!"; } - } - }; + my @metadata = defined $input ? ( stat($config) )[ 2, 4, 5 ] : (); + for my $pass ( 1, 2 ) { + my ( $status, $output ) = run_profile( $root, $relative, $shell ); + is( $status, 0, "pass $pass executes the profile" ) or diag($output); + is( $output, '', "pass $pass has no shell errors" ); + is( read_text("$root/etc/selinux/config"), $host_policy, 'host policy is unchanged' ); + is( read_text("$root/etc/fstab"), "host fstab\n", 'host fstab is unchanged' ); + is( read_text("$root/etc/inittab"), "host inittab\n", 'host inittab is unchanged' ); + if ( defined $input ) { + is( + read_text($config), + $expected . $unchanged, + "pass $pass changes only the active SELinux mode" + ); + is_deeply( [ ( stat($config) )[ 2, 4, 5 ] ], + \@metadata, 'policy permissions and ownership are preserved' ); + } + else { + ok( !-e $config, 'absent policy remains absent' ); + } + } + }; + } + + my @kinds = -l "$netboot/$relative" ? ('dangling') : qw(regular symlink dangling absent directory); + for my $kind (@kinds) { + subtest "$relative: $shell firewalld $kind" => sub { + my $root = sandbox_root(); + my $image = "$root/target"; + my $unit = "$image/usr/lib/systemd/system/firewalld.service"; + make_path( dirname($unit) ); + write_text( $unit, "[Service]\nExecStart=/usr/bin/true\n" ); + my @links = qw(etc/systemd/system/multi-user.target.wants/firewalld.service + etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service); + my %targets; + + for my $relative_link (@links) { + my $link = "$image/$relative_link"; + make_path( dirname($link), dirname("$root/$relative_link") ); + write_text( "$root/$relative_link", "host firewalld\n" ); + $targets{$link} = + File::Spec->abs2rel( $unit . ( $kind eq 'dangling' ? '.missing' : '' ), dirname($link) ); + if ( $kind eq 'regular' ) { + write_text( $link, "image firewalld\n" ); + } + elsif ( $kind eq 'symlink' || $kind eq 'dangling' ) { + symlink( $targets{$link}, $link ) or die "symlink $link: $!"; + } + elsif ( $kind eq 'directory' ) { + make_path($link); + write_text( "$link/keep", "directory contents\n" ); + } + symlink( $targets{$link}, "$link.unrelated" ) or die "symlink: $!"; + } + for my $pass ( 1, 2 ) { + my ( $status, $output ) = run_profile( $root, $relative, $shell ); + is( $status, 0, "pass $pass executes the profile" ) or diag($output); + is( $output, '', 'both shell conditions execute without errors' ); + for my $relative_link (@links) { + my $link = "$image/$relative_link"; + if ( ( $firewalld{ abs_path("$netboot/$relative") } && $kind ne 'directory' ) + || $kind eq 'absent' ) + { + ok( !-e $link && !-l $link, 'firewalld entry is absent' ); + } + elsif ( $kind eq 'regular' ) { + is( read_text($link), "image firewalld\n", 'older profile retains the entry' ); + } + elsif ( $kind eq 'directory' ) { + is( read_text("$link/keep"), "directory contents\n", 'directory contents are retained' ); + } + else { + is( readlink($link), $targets{$link}, 'older profile retains the link' ); + } + is( readlink("$link.unrelated"), $targets{$link}, 'unrelated link is unchanged' ); + is( read_text("$root/$relative_link"), "host firewalld\n", 'host entry is unchanged' ); + } + is( read_text($unit), "[Service]\nExecStart=/usr/bin/true\n", 'unit target is unchanged' ); + } + }; + } } } 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 080/129] 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 081/129] 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 082/129] 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 083/129] 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 084/129] 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 085/129] 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 086/129] 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 087/129] 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 088/129] 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 089/129] 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 34ea500af702d7828c0225467c7067af0aab01c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:09:17 -0300 Subject: [PATCH 090/129] fix(syncfiles): retain the client name when node lookup fails Keep the original client name for the rejection diagnostic. Use the resolved node only for dispatch, without changing identity or copy-command handling. --- xCAT-server/lib/xcat/plugins/syncfiles.pm | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/xCAT-server/lib/xcat/plugins/syncfiles.pm b/xCAT-server/lib/xcat/plugins/syncfiles.pm index 66a7e0b4c1..ddabf4dc8d 100644 --- a/xCAT-server/lib/xcat/plugins/syncfiles.pm +++ b/xCAT-server/lib/xcat/plugins/syncfiles.pm @@ -73,14 +73,15 @@ sub process_request $::RCP=$options{'node-rcp'}; } - if ($client) { ($client) = noderange($client) } - unless ($client) { #Not able to do identify the host in question + my $node; + if ($client) { ($node) = noderange($client) } + unless ($node) { #Not able to do identify the host in question xCAT::MsgUtils->message("S", "Received syncfiles from $client, which couldn't be correlated to a node (domain mismatch?)"); return; } require xCAT::Postage; - &syncfiles($client, $callback, $subreq); + &syncfiles($node, $callback, $subreq); } From 7f77e90308959394b35dc4f56fe8f30bef153d17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:42:13 -0300 Subject: [PATCH 091/129] test(syncfiles): check unresolved client names and rejection Check the original hostname in the unresolved-node diagnostic. Keep blank and missing-client rejection covered without sending a copy request. --- xCAT-test/unit/syncfiles_xdcp_identity.t | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/xCAT-test/unit/syncfiles_xdcp_identity.t b/xCAT-test/unit/syncfiles_xdcp_identity.t index e281e88ddc..7db1906fe9 100644 --- a/xCAT-test/unit/syncfiles_xdcp_identity.t +++ b/xCAT-test/unit/syncfiles_xdcp_identity.t @@ -183,9 +183,25 @@ push @cases, args => [], synclist => { node1 => '/install/custom/sync-a' }, expected => [], - messages => [ qr/couldn't be correlated to a node/ ], + messages => [ qr/\AReceived syncfiles from unknown\.example\.test, which couldn't be correlated to a node \(domain mismatch\?\)\z/ ], }; +for my $client ( 'other.example.test', '', undef ) { + my $name = defined($client) ? $client : ''; + my $label = !defined($client) ? 'missing' : length($client) ? $client : 'blank'; + push @cases, { + name => "unresolved client '$label' retains its diagnostic and sends no request", + request => { + command => ['syncfiles'], + arg => [], + ( defined($client) ? ( _xcat_clienthost => [$client] ) : () ), + }, + synclist => { node1 => '/install/custom/sync-a' }, + expected => [], + messages => [ qr/\AReceived syncfiles from \Q$name\E, which couldn't be correlated to a node \(domain mismatch\?\)\z/ ], + }; +} + for my $case (@cases) { subtest $case->{name} => sub { local $RCP; From 090deae902154d74d61d516615006160ccec2171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:42:14 -0300 Subject: [PATCH 092/129] test(syncfiles): exercise copy consumer identity precedence Drive the real xdsh and DSHCLI parser from syncfiles and updatenode. Capture only the external copy boundary and preserve inherited identity behavior. --- xCAT-test/unit/syncfiles_consumer_identity.t | 124 +++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 xCAT-test/unit/syncfiles_consumer_identity.t diff --git a/xCAT-test/unit/syncfiles_consumer_identity.t b/xCAT-test/unit/syncfiles_consumer_identity.t new file mode 100644 index 0000000000..d49fad012a --- /dev/null +++ b/xCAT-test/unit/syncfiles_consumer_identity.t @@ -0,0 +1,124 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +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(write_text); +use File::Temp qw(tempdir); +use Storable qw(dclone); +use Test::More; +use XCAT::Test::File qw(repo_path); + +my $work = tempdir(CLEANUP => 1); +make_path("$work/db"); +local $ENV{XCATROOT} = $work; +local $ENV{XCATCFG} = "SQLite:$work/db"; +for my $mapping ( + [ xCAT_plugin => 'xCAT-server/lib/xcat/plugins' ], + [ xCAT_monitoring => 'xCAT-server/lib/xcat/monitoring' ], +) { + symlink(repo_path($mapping->[1]), "$work/$mapping->[0]") or die $!; +} +unshift @INC, $work; +require xCAT_plugin::syncfiles; +require xCAT_plugin::xdsh; +require xCAT_plugin::updatenode; + +my $source = "$work/payload"; +my $list = "$work/synclist"; +write_text($source, "identity fixture\n"); +write_text($list, "$source -> /tmp/syncfiles-identity/payload\n"); + +sub exercise { + my ($producer, $case) = @_; + local %ENV = %ENV; + delete @ENV{grep { /\A(?:DSH_|DCP_|RSYNC)/ } keys %ENV}; + @ENV{keys %{$case->{inherited}}} = values %{$case->{inherited}}; + no warnings qw(once redefine); + local $::RCP; + local $::USER; + local $::fanout; + local $::timeout; + local $::REPORTSTATUS = 'N'; + local @::SUCCESSFULLNODES; + local @::FAILEDNODES; + local @ARGV; + local *xCAT::Utils::isServiceNode = sub { return 0; }; + local *xCAT::Utils::isMN = sub { return 0; }; + local *xCAT::TableUtils::get_site_attribute = sub { return; }; + local *xCAT::SvrUtils::getsynclistfile = sub { return {node1 => $list}; }; + local *xCAT_plugin::syncfiles::noderange = sub { return 'node1'; }; + my (@executions, @responses, @requests); + local *xCAT::DSHCLI::execute_dcp = sub { + my ($class, $options) = @_; + push @executions, { + options => dclone($options), + from => $ENV{DSH_FROM_USERID}, + to => $ENV{DSH_TO_USERID}, + }; + return 0; + }; + my $callback = sub { push @responses, dclone($_[0]); }; + my $dispatch = sub { + my ($request, $response) = @_; + push @requests, dclone($request); + xCAT_plugin::xdsh::process_request($request, $response, sub { die 'Unexpected nested request'; }); + }; + my $request = { + command => [$producer], node => ['node1'], arg => [], + username => ['operator'], _xcat_clienthost => ['node1.example.test'], + environment => $case->{environment} || [], + SNFileSyncing => ['no'], FileSyncing => ['yes'], + }; + if ($producer eq 'syncfiles') { + xCAT_plugin::syncfiles::process_request($request, $callback, $dispatch); + } else { + xCAT_plugin::updatenode::updatenodesyncfiles($request, $dispatch, $callback); + } + is(scalar @executions, 1, 'one parsed copy reaches the execution boundary'); + is(scalar @requests, 1, 'one producer request reaches the real xdsh plugin'); + my $copy = $executions[0] || {options => {}}; + is($copy->{from}, $case->{from}, 'consumer preserves the expected sending identity'); + is($copy->{to}, $case->{to}, 'consumer preserves the expected receiving identity'); + is($copy->{options}->{user}, $case->{from}, 'xdcp selects the sending identity for its copy user'); + is($copy->{options}->{nodes}, 'node1', 'copy targets the resolved node'); + is_deeply( + $copy->{options}->{destDir_srcFile}, + {node1 => {'/tmp/syncfiles-identity' => {same_dest_name => [$source]}}}, + 'the real synclist parser supplies the payload and destination', + ); + is_deeply($requests[0]->{username}, [$producer eq 'syncfiles' ? 'root' : 'operator'], + 'the producer retains its request identity contract'); + my @errors = grep { + $_->{error} || grep { $_ } ref($_->{errorcode}) eq 'ARRAY' + ? @{$_->{errorcode}} : ($_->{errorcode} || 0) + } @responses; + is_deeply(\@errors, [], 'the request has no consumer error'); + return; +} + +for my $case ( + {name => 'unset', inherited => {}, from => 'root', to => 'root'}, + {name => 'empty', inherited => {DSH_FROM_USERID => '', DSH_TO_USERID => ''}, from => 'root', to => 'root'}, + {name => 'sending identity only', inherited => {DSH_FROM_USERID => 'sender'}, from => 'sender', to => 'root'}, + {name => 'receiving identity only', inherited => {DSH_TO_USERID => 'receiver'}, from => 'root', to => 'receiver'}, + {name => 'both inherited', inherited => {DSH_FROM_USERID => 'sender', DSH_TO_USERID => 'receiver'}, from => 'sender', to => 'receiver'}, +) { + subtest "syncfiles: $case->{name}" => sub { exercise('syncfiles', $case); }; +} + +for my $case ( + {name => 'certificate identity', inherited => {}, from => 'operator', to => 'operator'}, + {name => 'certificate overrides inherited sender', inherited => {DSH_FROM_USERID => 'sender', DSH_TO_USERID => 'receiver'}, from => 'operator', to => 'receiver'}, + {name => 'explicit sending identity', inherited => {}, environment => ['DSH_FROM_USERID=sender'], from => 'sender', to => 'operator'}, + {name => 'first explicit sender wins', inherited => {}, environment => ['DSH_FROM_USERID=sender', 'DSH_FROM_USERID=other'], from => 'sender', to => 'operator'}, + {name => 'empty explicit sender falls back at consumer', inherited => {DSH_FROM_USERID => 'sender'}, environment => ['DSH_FROM_USERID='], from => 'operator', to => 'operator'}, +) { + subtest "updatenode: $case->{name}" => sub { exercise('updatenode', $case); }; +} + +done_testing(); From ff2ec0d4acaa480fe6b71caca81f18af6954fb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:42:14 -0300 Subject: [PATCH 093/129] test(syncfiles): verify authenticated hierarchy delivery Exercise certificate policy and real SSH copies in a disposable MN/SN/node fixture. This test is opt-in and skips in ordinary CI without XCAT_SYNCFILES_LIVE_CONFIG. --- .../autotest/testcase/integration/cases0 | 2 +- .../integration/fixtures/syncfiles-request.pl | 29 +++ xCAT-test/integration/syncfiles_delivery.t | 173 ++++++++++++++++++ 3 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 xCAT-test/integration/fixtures/syncfiles-request.pl create mode 100644 xCAT-test/integration/syncfiles_delivery.t diff --git a/xCAT-test/autotest/testcase/integration/cases0 b/xCAT-test/autotest/testcase/integration/cases0 index 907e458372..aba39450ed 100644 --- a/xCAT-test/autotest/testcase/integration/cases0 +++ b/xCAT-test/autotest/testcase/integration/cases0 @@ -4,7 +4,7 @@ os:Linux label:mn_only,ci_test,integration cmd:prove -I/opt/xcat/lib/perl -I/opt/xcat/lib/perl/xCAT -r /opt/xcat/share/xcat/tools/autotest/integration check:rc==0 -check:output=~Files=10, +check:output=~Files=11, end start:xcatd_dispatch_redaction diff --git a/xCAT-test/integration/fixtures/syncfiles-request.pl b/xCAT-test/integration/fixtures/syncfiles-request.pl new file mode 100644 index 0000000000..92a5c5672b --- /dev/null +++ b/xCAT-test/integration/fixtures/syncfiles-request.pl @@ -0,0 +1,29 @@ +use strict; +use warnings; +use File::Slurper qw(read_text); +use JSON::PP qw(decode_json encode_json); +use xCAT::Client; + +my ($input) = @ARGV; +my $case = decode_json(read_text($input)); +my @responses; +my $callback = sub { push @responses, $_[0]; }; +delete $ENV{XCATBYPASS}; +local $SIG{ALRM} = sub { die "Syncfiles request timed out\n"; }; +alarm 60; +if ($case->{consumer}) { + require xCAT_plugin::syncfiles; + require xCAT_plugin::xdsh; + delete @ENV{qw(DSH_FROM_USERID DSH_TO_USERID)}; + @ENV{keys %{$case->{inherited}}} = values %{$case->{inherited}}; + xCAT_plugin::syncfiles::process_request($case->{request}, $callback, sub { + my ($request, $response) = @_; + xCAT_plugin::xdsh::preprocess_request($request, $response, sub { die 'Unexpected remote dispatch'; }); + }); +} else { + $ENV{XCATHOST} = $case->{endpoint}; + xCAT::Client::submit_request($case->{request}, $callback, + $case->{credential}, $case->{credential}, $case->{ca}); +} +alarm 0; +print encode_json(\@responses), "\n"; diff --git a/xCAT-test/integration/syncfiles_delivery.t b/xCAT-test/integration/syncfiles_delivery.t new file mode 100644 index 0000000000..ff0ca9763d --- /dev/null +++ b/xCAT-test/integration/syncfiles_delivery.t @@ -0,0 +1,173 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib '/opt/xcat/lib/perl'; +use File::Path qw(remove_tree); +use File::Slurper qw(read_text write_text); +use JSON::PP qw(decode_json encode_json); +use Test::More; + +plan skip_all => 'set XCAT_SYNCFILES_LIVE_CONFIG for a disposable MN/SN/node lab' + unless $ENV{XCAT_SYNCFILES_LIVE_CONFIG}; +require Capture::Tiny; +die 'Run as root on the disposable management node' unless $> == 0; +my $config = decode_json(read_text($ENV{XCAT_SYNCFILES_LIVE_CONFIG})); +my ($node, $service, $work, $cache) = @{$config}{qw(node service work cache)}; +die 'Unsafe fixture path' unless $work =~ m{\A/tmp/xcat-syncfiles-[A-Za-z0-9]+\z}; +die 'Unsafe cache path' unless $cache =~ m{\A/[A-Za-z0-9/_-]+\z} && $cache ne '/'; +for ($node, $service, $config->{management}) { die 'Unsafe host name' unless /\A[A-Za-z0-9][A-Za-z0-9.-]*\z/; } +die 'Fixture hosts must be distinct' if $node eq $service || $node eq $config->{management} || $service eq $config->{management}; +for my $key (qw(operator denied ca)) { + die "Unsafe $key credential path" unless $config->{$key} =~ m{\A/[A-Za-z0-9/_.-]+\z}; +} +require xCAT::SvrUtils; +my $lists = xCAT::SvrUtils->getsynclistfile([$node]); +die 'The fixture node must use only the fixture synclist' + unless $lists->{$node} eq "$work/synclist"; + +sub command { + my (@args) = @_; + my ($out, $err, $status) = Capture::Tiny::capture(sub { system('timeout', '90', @args) }); + die "Command failed (@args): $status\n$out$err" if $status; + return $out; +} +sub remote { + my ($host, @args) = @_; + return command('ssh', '-oBatchMode=yes', "root\@$host", @args); +} +sub copy_to { + my ($host, $file, $target) = @_; + command('scp', '-q', $file, "root\@$host:$target"); + return; +} +my %created; +END { + my $status = $?; + my $failed = 0; + for my $host (grep { $_ ne 'local' } keys %created) { + eval { remote($host, 'rm', '-rf', '--', $work, "$cache$work"); 1 } + or do { warn "Fixture cleanup failed on $host: $@"; $failed = 1; }; + } + if ($created{local}) { + remove_tree($work, {error => \my $errors}); + if (@$errors) { warn "Local fixture cleanup failed\n"; $failed = 1; } + } + $? = $status || $failed; +} +die 'Fixture path already exists locally' if -e $work; +for my $host ($node, $service) { + remote($host, 'test', '!', '-e', $work); + remote($host, 'test', '!', '-e', "$cache$work"); +} +mkdir($work, 0700) or die "Cannot create $work: $!"; +$created{local} = 1; +for my $host ($node, $service) { + remote($host, 'mkdir', '-m', '0755', $work); + $created{$host} = 1; + copy_to($host, "$FindBin::Bin/fixtures/syncfiles-request.pl", "$work/request.pl"); +} +my $payload = "$work/payload"; +my $destination = "$work/delivered/payload"; +write_text("$work/synclist", "$payload -> $destination\n"); + +sub request { + my ($host, $case) = @_; + write_text("$work/request.json", encode_json($case)); + copy_to($host, "$work/request.json", "$work/request.json"); + my $out = remote($host, 'perl', '-I/opt/xcat/lib/perl', "$work/request.pl", "$work/request.json"); + return decode_json($out); +} +sub errors { + my ($responses) = @_; + my @errors; + for my $response (@$responses) { + my $codes = $response->{errorcode}; + $codes = [$codes] unless ref($codes) eq 'ARRAY'; + push @errors, $response if $response->{error} || + grep { defined($_) && $_ ne '0' && length($_) } @$codes; + } + return \@errors; +} +sub authenticated { + my ($endpoint, $principal, $request) = @_; + return request($node, { + endpoint => "$endpoint:3001", credential => $config->{$principal}, + ca => $config->{ca}, request => $request, + }); +} +sub delivered { + my ($text, $user) = @_; + is(remote($node, 'cat', $destination), $text, 'destination has the new payload'); + is(remote($node, 'stat', '-c', '%U', $destination), "$user\n", 'destination ownership matches the copy identity'); + return; +} +sub prepare_destination { + my ($user) = @_; + remote($node, 'mkdir', '-p', "$work/delivered"); + remote($node, 'rm', '-f', $destination); + remote($node, 'chown', $user, "$work/delivered"); + return; +} + +subtest 'authenticated node request traverses the MN/SN hierarchy' => sub { + write_text($payload, "hierarchy payload\n"); + prepare_destination('root'); + my $responses = authenticated($config->{management}, 'operator', {command => ['syncfiles'], arg => [], username => ['denied']}); + is_deeply(errors($responses), [], 'the authorized certificate is accepted despite the supplied username'); + delivered("hierarchy payload\n", 'root'); + is(remote($service, 'cat', "$cache$payload"), "hierarchy payload\n", 'the service node receives the staged payload'); +}; + +subtest 'authenticated node request consumes the service-node cache' => sub { + write_text($payload, "service cache payload\n"); + copy_to($service, $payload, "$cache$payload"); + prepare_destination('root'); + my $responses = authenticated($service, 'operator', {command => ['syncfiles'], arg => []}); + is_deeply(errors($responses), [], 'the service node accepts the certificate'); + delivered("service cache payload\n", 'root'); +}; + +subtest 'unauthorized certificate cannot trigger a copy' => sub { + write_text($payload, "must not be delivered\n"); + copy_to($service, $payload, "$cache$payload"); + my $responses = authenticated($service, 'denied', {command => ['syncfiles'], arg => [], username => ['root']}); + my @denials = map { @{$_->{error} || []} } @{errors($responses)}; + ok(scalar(grep { $_ eq 'Permission denied for request' } @denials), + 'authorization rejects the certificate despite the supplied root username'); + delivered("service cache payload\n", 'root'); +}; + +for my $case ( + ['unset', {}, 'root'], + ['empty', {DSH_FROM_USERID => '', DSH_TO_USERID => ''}, 'root'], + ['sender only', {DSH_FROM_USERID => 'sender'}, 'sender'], + ['receiver only', {DSH_TO_USERID => 'receiver'}, 'root'], + ['both', {DSH_FROM_USERID => 'sender', DSH_TO_USERID => 'receiver'}, 'sender'], +) { + my ($name, $inherited, $user) = @$case; + subtest "real copy consumer with $name inherited" => sub { + my $text = "consumer $name\n"; + write_text($payload, $text); + copy_to($service, $payload, "$cache$payload"); + prepare_destination($user); + my $responses = request($service, { + consumer => 1, inherited => $inherited, + request => {command => ['syncfiles'], arg => [], _xcat_clienthost => [$node]}, + }); + is_deeply(errors($responses), [], 'the real copy consumer reports no error'); + delivered($text, $user); + }; +} + +subtest 'updatenode preserves the authenticated non-root identity across the hierarchy' => sub { + write_text($payload, "updatenode payload\n"); + prepare_destination('operator'); + my $responses = authenticated($config->{management}, 'operator', { + command => ['updatenode'], noderange => [$node], arg => ['-F'], username => ['root'], + }); + is_deeply(errors($responses), [], 'updatenode completes without an earlier error being hidden'); + delivered("updatenode payload\n", 'operator'); +}; + +done_testing(); From 66a8b7786bbe064f9ff1b7fd0c0b7f0645123144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:42:14 -0300 Subject: [PATCH 094/129] docs(syncfiles): describe the isolated delivery fixture Document the restricted certificate policy, required tools and cleanup limits. Distinguish the fixture from the default certificate-free postscript path. --- xCAT-test/integration/README.md | 79 ++++++++++++++++++++++++++++++++- xCAT-test/unit/README.md | 5 +++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/xCAT-test/integration/README.md b/xCAT-test/integration/README.md index eec8664c99..151e9e1f77 100644 --- a/xCAT-test/integration/README.md +++ b/xCAT-test/integration/README.md @@ -27,8 +27,8 @@ against it. Note the `-I` flags: unlike the unit tests these run from the installed location, so they pick up xCAT modules from `/opt/xcat/lib/perl` rather than from a source tree. -The case checks `rc==0` and `output=~Files=10,`. The file count checks that `prove` -found all ten files, which catches a packaging regression or a test renamed away from +The case checks `rc==0` and `output=~Files=11,`. The file count checks that `prove` +found all eleven files, which catches a packaging regression or a test renamed away from `.t` without updating the count. It does not prove that environment-gated cases ran; inspect the TAP output for skips. **Add to that number when you add a test.** A missing directory is already caught by `rc==0` -- `prove -r` on a path that does not exist exits @@ -55,6 +55,7 @@ A test belongs in `integration/` when it needs something the checkout cannot pro | `html_form_runtime_dependency.t` | the installed `HTML::Form` module | | `openeuler_package_postscripts.t` | Linux root, private mount namespaces and DNF; tests complete package postscripts with command doubles and an isolated repository directory | | `openeuler_postscript_repositories.t` | Linux root, private mount namespaces, DNF and RPM signing tools; tests actual signed repository transactions in isolated install roots | +| `syncfiles_delivery.t` | a disposable management node, service node and compute node, certificate policies and SSH copy access; opt-in | | `wsapi_apache_access.t` | an Apache binary and its modules; reads `xcat-ws.conf` from the source tree, so `github_action_xcat_test.pl` runs it from the checkout and the installed copy skips | | `xcatd_dispatch_redaction.sh` | a live `xcatd`, syslog delivery to `/var/log/xcat/cluster.log`, and root | @@ -96,6 +97,80 @@ plan skip_all => 'set XCAT_KEA_LIVE_SMOKE=1 to run live Kea daemon smoke test' It starts real Kea daemons, so it stays off unless asked for. Do not enable it on a node whose DHCP service is in use. +## Syncfiles delivery lab + +Run `syncfiles_delivery.t` only in a disposable three-node lab. It sends real +`syncfiles` and `updatenode -F` requests, and runs real SSH/rsync copies. Do not +point it at a shared or production cluster. + +Prepare the lab before enabling the test: + +- Install xCAT on the management and service nodes, and the xCAT Perl client + modules on the compute node. Install Perl `File::Slurper`, `Capture::Tiny`, + `JSON::PP`, `timeout`, SSH/SFTP and rsync. The management and service nodes + must have the normal `updatenode` postscript files and reachability tools. +- Configure name resolution and route the compute node through the service node + in `noderes.servicenode` and `noderes.xcatmaster`. Give the compute node a + dedicated osimage with exactly one synclist: `/synclist`. +- Configure the service-node cache prefix in the test to match + `site.SNsyncfiledir` (default `/var/xcat/syncfiles`). Keep the daemon environment + free of `DSH_*`, `DCP_*` and `RSYNC*` overrides. +- Use a lab CA and valid client certificates for `operator` and `denied`. + Allow `operator` to run `syncfiles`, `updatenode` and `xdcp`. Leave `denied` + unauthorized. On both the management and service nodes, remove the default + unnamed `syncfiles` allow rule and any other rule that allows `denied`. + This certificate-only fixture intentionally differs from the default policy, + which allows the certificate-free `startsyncfiles` postscript request. + Configure the normal trusted MN/SN certificate relationship. + Store the client credentials and CA on the compute node; the test does not + create certificates or change policy. +- Create the `operator`, `sender` and `receiver` Unix accounts. Give the + management node root SSH access to the service and compute nodes, and give + the service node SSH copy access to the compute node as `root`, `operator` + and `sender`. Use lab-only keys and pinned host keys. Do not enable password + authentication for this test. + +Create a JSON configuration on the management node. For example: + +```json +{ + "management": "mn", + "service": "sn", + "node": "cn", + "work": "/tmp/xcat-syncfiles-fixture1", + "cache": "/var/xcat/syncfiles", + "operator": "/root/lab-certs/operator.pem", + "denied": "/root/lab-certs/denied.pem", + "ca": "/root/lab-certs/ca.pem" +} +``` + +Each client PEM contains its certificate and private key. Keep the credentials +private. The three host names must be distinct. The work path must be a new +directory directly under `/tmp`, named `xcat-syncfiles-` followed by letters or +digits. The test refuses existing work and cache paths, removes its request and +payload directories on exit, and fails if that cleanup fails. xCAT can retain +cache parent directories and generated `/tmp/rsync_*` command files outside +those directories. Remove the disposable nodes and credentials after testing. + +Run as root on the management node: + +```sh +XCAT_SYNCFILES_LIVE_CONFIG=/root/syncfiles-lab.json \ + prove -v xCAT-test/integration/syncfiles_delivery.t +``` + +The certificate cases check authorization under that restricted policy, MN/SN +staging, delivered bytes and file ownership. `syncfiles` requests root copies +regardless of the authenticated user; `updatenode` retains the authenticated +user unless its environment overrides the sender. The inherited-environment +cases call the real copy consumer on the service node without TLS; they test +copy identity precedence, not authentication. The unit test +`syncfiles_consumer_identity.t` checks both parsed identity variables and rejects +changes that overwrite nonempty inherited values. + +This fixture does not cover the default certificate-free `startsyncfiles` path. + ## What does not belong here Anything that only needs the checkout. Those go in [`../unit`](../unit/README.md) and diff --git a/xCAT-test/unit/README.md b/xCAT-test/unit/README.md index 2a5b5ed111..abd70e1771 100644 --- a/xCAT-test/unit/README.md +++ b/xCAT-test/unit/README.md @@ -38,6 +38,11 @@ skip. The CI takes a copy of the checkout before the build for this reason; see ## Running commands from Perl tests +`syncfiles_consumer_identity.t` also requires `/usr/bin/rsync` on Linux. The +real copy parser checks that executable before the test intercepts copy +execution. Install rsync with the test dependencies; this test does not run it +or connect to another node. The CI management-node install already includes it. + Use `XCAT::Test::Process` when a test needs a command's exit code and combined standard output and standard error: 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 095/129] 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 096/129] 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 097/129] 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 098/129] 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 cc206d5f1ced3f2f6632d2c93e74a09233451e59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:12:14 -0300 Subject: [PATCH 099/129] fix(route): retain the device for IPv6 link-local gateways Scope generic Linux route lookup and updates to the supplied interface for link-local next hops. Retain the device in SLES routes, legacy Red Hat route6 records and Debian interface commands. Remove matching saved records without matching neighboring interface names, and migrate older unscoped records when adding routes. Keep global gateways, connected routes and NetworkManager policy unchanged. --- xCAT/postscripts/routeop | 77 ++++++++++++++++++++++++++++++++-------- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/xCAT/postscripts/routeop b/xCAT/postscripts/routeop index 5add370d08..626a45aa52 100755 --- a/xCAT/postscripts/routeop +++ b/xCAT/postscripts/routeop @@ -143,7 +143,7 @@ route_exists() # ipv6 if is_ipv6_route "$route_net" then - result=`ip -6 route show $route_net/$route_mask` + result=`ip -6 route show $route_net/$route_mask ${gateway_device:+via $route_gw dev $gateway_device}` if [ $? -ne 0 ] || [ -z "$result" ] then ret=0 @@ -449,6 +449,15 @@ nmcli_persistent_route() fi } +remove_route_record() +{ + local filename=$1 + local pattern + [ -f "$filename" ] || return 0 + pattern=$(printf '%s\n' "$2" | sed 's/[][\\.^$*#]/\\&/g') + sed -i "\#^[[:space:]]*${pattern}[[:space:]]*\$#d" "$filename" +} + # handle the route replace operation that adding the setting to configuration file replace_persistent_route() { @@ -491,8 +500,8 @@ replace_persistent_route() route="$net/$mask :: - $ifname" route1="$net\/$mask :: - $ifname"; else - route="$net/$mask $gw - -" - route1="$net\/$mask $gw - -"; + route="$net/$mask $gw - ${gateway_device:--}" + route1="$net\/$mask $gw - ${gateway_device:--}"; fi else # for ipv4 @@ -549,8 +558,8 @@ replace_persistent_route() route="$net/$mask dev $ifname" route1="$net\/$mask dev $ifname" else - route="$net/$mask via $gw" - route1="$net\/$mask via $gw" + route="$net/$mask via $gw${gateway_device:+ dev $gateway_device}" + route1="$net\/$mask via $gw${gateway_device:+ dev $gateway_device}" fi else # ipv4 @@ -696,8 +705,8 @@ add_persistent_route() route="$net/$mask :: - $ifname" route1="$net\/$mask :: - $ifname"; else - route="$net/$mask $gw - -" - route1="$net\/$mask $gw - -"; + route="$net/$mask $gw - ${gateway_device:--}" + route1="$net\/$mask $gw - ${gateway_device:--}"; fi else if [ "$gw" = "" -o "$gw" = "0.0.0.0" ] ; then @@ -728,8 +737,13 @@ add_persistent_route() fi fi fi + local match_flags= + if is_ipv6_route "$net" && [ -n "$gateway_device" ]; then + remove_route_record "$filename" "$net/$mask $gw - -" || return $? + match_flags=-Fx + fi if [ -f $filename ]; then - grep "$route" $filename 2>&1 1>/dev/null + grep $match_flags "$route" $filename 2>&1 1>/dev/null if [ $? -ne 0 ]; then #route does not exist grep "$xcat_config_start" $filename 2>&1 1>/dev/null if [ $? -ne 0 ]; then #no xCAT section @@ -782,6 +796,11 @@ add_persistent_route() fi fi + if [ -n "$gateway_device" ] && [ "$v6flag" -eq 1 ]; then + remove_route_record "$filename" "up route -A inet6 add $net/$mask gw $gw" || return $? + remove_route_record "$filename" "down route -A inet6 del $net/$mask gw $gw" || return $? + remove_route_record "$filename" "post-up ip -6 route replace $net/$mask via $gw" || return $? + fi grep "$matchstr" $filename 2>&1 1>/dev/null if [ $? -ne 0 ];then foundflag=0 @@ -796,8 +815,8 @@ add_persistent_route() echo " up route -A inet6 add $net/$mask dev $ifname" >> $tempfile echo " down route -A inet6 del $net/$mask dev $ifname" >> $tempfile else - echo " up route -A inet6 add $net/$mask gw $gw" >> $tempfile - echo " down route -A inet6 del $net/$mask gw $gw" >> $tempfile + echo " up route -A inet6 add $net/$mask gw $gw${gateway_device:+ dev $gateway_device}" >> $tempfile + echo " down route -A inet6 del $net/$mask gw $gw${gateway_device:+ dev $gateway_device}" >> $tempfile fi else if [ "$gw" = "" -o "$gw" = "0.0.0.0" ] ; then @@ -824,8 +843,8 @@ add_persistent_route() echo " up route -A inet6 add $net/$mask dev $ifname" >> $tempfile echo " down route -A inet6 del $net/$mask dev $ifname" >> $tempfile else - echo " up route -A inet6 add $net/$mask gw $gw" >> $tempfile - echo " down route -A inet6 del $net/$mask gw $gw" >> $tempfile + echo " up route -A inet6 add $net/$mask gw $gw${gateway_device:+ dev $gateway_device}" >> $tempfile + echo " down route -A inet6 del $net/$mask gw $gw${gateway_device:+ dev $gateway_device}" >> $tempfile fi else if [ "$gw" = "" -o "$gw" = "0.0.0.0" ] ; then @@ -924,6 +943,11 @@ rm_persistent_route() sles) #echo "sles" filename="/etc/sysconfig/network/routes"; + if is_ipv6_route "$net" && [ -n "$gateway_device" ]; then + remove_route_record "$filename" "$net/$mask $gw - $gateway_device" || return $? + remove_route_record "$filename" "$net/$mask $gw - -" + return $? + fi # ipv6 net if is_ipv6_route "$net" then @@ -984,6 +1008,15 @@ rm_persistent_route() fi fi + if [ -n "$gateway_device" ] && [ "$v6flag" -eq 1 ]; then + local device_suffix + for device_suffix in " dev $gateway_device" ""; do + remove_route_record "$filename" "up route -A inet6 add $net/$mask gw $gw$device_suffix" || return $? + remove_route_record "$filename" "down route -A inet6 del $net/$mask gw $gw$device_suffix" || return $? + remove_route_record "$filename" "post-up ip -6 route replace $net/$mask via $gw$device_suffix" || return $? + done + return 0 + fi grep "$matchstr" $filename if [ $? -eq 0 ];then sed -i -e "/$matchstr/d" $filename @@ -998,6 +1031,13 @@ rm_persistent_route() nmcli_persistent_route delete "$net" "$mask" "$gw" "$ifname" return $? fi + if is_ipv6_route "$net" && [ -n "$gateway_device" ]; then + filename="/etc/sysconfig/network-scripts/route6-$ifname" + remove_route_record "$filename" "$net/$mask via $gw dev $gateway_device" || return $? + remove_route_record "$filename" "$net/$mask via $gw" || return $? + remove_route_record /etc/sysconfig/static-routes-ipv6 "$ifname $net/$mask $gw" + return $? + fi #ipv6 if is_ipv6_route "$net" then @@ -1048,6 +1088,13 @@ rm_persistent_route() +gateway_device= +if [ "$(uname -s)" = "Linux" ]; then + case "$gw" in + [fF][eE][89aAbB][[:xdigit:]]:*) gateway_device=$ifname ;; + esac +fi + if command -v xcat_is_openeuler >/dev/null 2>&1 && xcat_is_openeuler "$OSVER"; then case "$op" in add|delete|replace) @@ -1071,7 +1118,7 @@ if [ "$op" = "add" ]; then if [ "$gw" = "" -o "$gw" = "::" ] ; then cmd="ip -6 route add $net/$mask dev $ifname" else - cmd="ip -6 route add $net/$mask via $gw" + cmd="ip -6 route add $net/$mask via $gw${gateway_device:+ dev $gateway_device}" fi else # AIX TODO @@ -1127,7 +1174,7 @@ elif [ "$op" = "delete" ]; then if [ "$gw" = "" -o "$gw" = "::" ] ; then cmd="ip -6 route delete $net/$mask dev $ifname" else - cmd="ip -6 route delete $net/$mask via $gw" + cmd="ip -6 route delete $net/$mask via $gw${gateway_device:+ dev $gateway_device}" fi else # AIX TODO @@ -1183,7 +1230,7 @@ elif [ "$op" = "replace" ]; then if [ "$net" = "default" ]; then cmd="ip -6 route replace default via $gw" else - cmd="ip -6 route replace $net/$mask via $gw" + cmd="ip -6 route replace $net/$mask via $gw${gateway_device:+ dev $gateway_device}" fi fi fi From d42f3e3150df63d4c5989a23cfcd61f2215df1d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:12:14 -0300 Subject: [PATCH 100/129] test(route): exercise link-local gateways in network namespaces Run routeop against real kernel routes. Cover repeated add, replacement, deletion, another device, expanded addresses and failure preservation. Check SLES, legacy Red Hat and Debian persistent records, including unscoped records and neighboring interface names. Keep global-gateway and connected-route controls. --- xCAT-test/bats/README.md | 5 + xCAT-test/bats/routeop_linklocal.bats | 179 ++++++++++++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 xCAT-test/bats/routeop_linklocal.bats diff --git a/xCAT-test/bats/README.md b/xCAT-test/bats/README.md index 4e70ec6f2c..de452fe90e 100644 --- a/xCAT-test/bats/README.md +++ b/xCAT-test/bats/README.md @@ -28,6 +28,11 @@ fixtures. They require Bubblewrap, Bash, GNU core utilities, grep, sed, and permission to create user namespaces. The CI workflow installs Bubblewrap and enables those namespaces. +`routeop_linklocal.bats` also needs iproute2 and kernel support for dummy +network interfaces. It maps root and grants `CAP_NET_ADMIN` only inside a +new user and network namespace. It runs as an ordinary user and changes +real kernel routes only in that private network namespace. + Missing prerequisites fail these tests without stopping unrelated test files. Non-Linux hosts report a skip. Set `TMPDIR` to a writable, executable filesystem if the default temporary directory is mounted with `noexec`. diff --git a/xCAT-test/bats/routeop_linklocal.bats b/xCAT-test/bats/routeop_linklocal.bats new file mode 100644 index 0000000000..8be31330a8 --- /dev/null +++ b/xCAT-test/bats/routeop_linklocal.bats @@ -0,0 +1,179 @@ +#!/usr/bin/env bats + +load 'helpers/script_sandbox' + +setup() +{ + setup_script_sandbox cat dirname grep sed tr uname logger awk cut head rm touch mkdir mv + local ip_binary + ip_binary=$(PATH=/usr/sbin:/sbin:/usr/bin:/bin type -P ip) || return 1 + cp -L "$ip_binary" "$fixture/bin/ip" + mkdir -p "$fixture/etc/sysconfig/network" + printf '%s\n' SLE VERSION=15 >"$fixture/etc/SUSE-brand" + sandbox+=(--ro-bind "$(repo_path xCAT/postscripts)" /tmp/postscripts + --setenv OSVER sles15 --uid 0 --gid 0 --cap-add CAP_NET_ADMIN) + cat >"$fixture/bin/route-test" <<'SH' +#!/bin/bash +set -eu +ip link set lo up +for dev in test0 test1; do + ip link add "$dev" type dummy + ip link set "$dev" up + ip -6 address add fe80::2/64 dev "$dev" nodad + ip -6 address add 2001:db8:1::2/64 dev "$dev" nodad +done +exec /bin/bash -eu -c "$1" +SH + chmod +x "$fixture/bin/route-test" +} + +run_routes() +{ + run "${sandbox[@]}" /bin/bash /bin/route-test "$1" + [ "$status" -eq 0 ] +} + +@test 'routeop installs and repeats a link-local gateway route on its device' { + run_routes ' + for pass in 1 2; do + /tmp/postscripts/routeop add 2001:db8:2:: 64 fe80::1 test0 + ip -6 route show 2001:db8:2::/64 | + grep -q "2001:db8:2::/64 via fe80::1 dev test0" + done + test "$(grep -c "^2001:db8:2::/64 fe80::1 - test0$" /etc/sysconfig/network/routes)" = 1 + ' +} + +@test 'routeop does not confuse a link-local route on another device' { + run_routes ' + ip -6 route add 2001:db8:2::/64 via fe80::1 dev test1 metric 2000 + /tmp/postscripts/routeop add 2001:db8:2:: 64 fe80::1 test0 + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::1 dev test0" + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::1 dev test1" + ' +} + +@test 'routeop replaces and deletes the scoped gateway without deleting a neighbor' { + run_routes ' + /tmp/postscripts/routeop replace 2001:db8:2:: 64 fe80::1 test0 + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::1 dev test0" + /tmp/postscripts/routeop replace 2001:db8:2:: 64 fe80::3 test0 + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::3 dev test0" + grep -qx "2001:db8:2::/64 fe80::3 - test0" /etc/sysconfig/network/routes + ip -6 route add 2001:db8:2::/64 via fe80::3 dev test1 metric 512 + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::3 test0 + test -z "$(ip -6 route show 2001:db8:2::/64 via fe80::3 dev test0)" + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::3 dev test1" + test -z "$(sed "/^[[:space:]]*$/d" /etc/sysconfig/network/routes)" + ' +} + +@test 'routeop scopes expanded and upper-case link-local gateways' { + run_routes ' + /tmp/postscripts/routeop replace 2001:db8:2:: 64 FE80:0000:0000:0000:0000:0000:0000:0001 test0 + ip -6 route show 2001:db8:2::/64 | grep -q "2001:db8:2::/64 via fe80::1 dev test0" + grep -qx "2001:db8:2::/64 FE80:0000:0000:0000:0000:0000:0000:0001 - test0" /etc/sysconfig/network/routes + ' +} + +@test 'routeop leaves persistence unchanged when a scoped replacement fails' { + run_routes ' + echo "2001:db8:2::/64 fe80::1 - test0" >/etc/sysconfig/network/routes + if /tmp/postscripts/routeop replace 2001:db8:2:: 64 fe80::3 missing0; then exit 1; fi + grep -qx "2001:db8:2::/64 fe80::1 - test0" /etc/sysconfig/network/routes + test -z "$(ip -6 route show 2001:db8:2::/64)" + ' +} + +@test 'routeop retains global-gateway and connected-route behavior' { + run_routes ' + /tmp/postscripts/routeop replace 2001:db8:2:: 64 2001:db8:1::1 test0 + ip -6 route show 2001:db8:2::/64 | grep -q "via 2001:db8:1::1" + grep -qx "2001:db8:2::/64 2001:db8:1::1 - -" /etc/sysconfig/network/routes + /tmp/postscripts/routeop replace 2001:db8:3:: 64 :: test0 + ip -6 route show 2001:db8:3::/64 | grep -q "dev test0" + grep -qx "2001:db8:3::/64 :: - test0" /etc/sysconfig/network/routes + ' +} + +@test 'routeop deletes exact SLES records and older unscoped entries' { + run_routes ' + printf "%s\n" "2001:db8:2::/64 fe80::1 - test0" \ + "2001:db8:2::/64 fe80::1 - test01" \ + "2001:db8:3::/64 fe80::1 - -" >/etc/sysconfig/network/routes + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0 + /tmp/postscripts/routeop delete 2001:db8:3:: 64 fe80::1 test0 + test "$(cat /etc/sysconfig/network/routes)" = "2001:db8:2::/64 fe80::1 - test01" + ' +} + +@test 'routeop replaces an unscoped SLES entry without matching another device' { + run_routes ' + printf "%s\n" "2001:db8:2::/64 fe80::1 - -" \ + "2001:db8:2::/64 fe80::1 - test01" >/etc/sysconfig/network/routes + /tmp/postscripts/routeop add 2001:db8:2:: 64 fe80::1 test0 + test "$(grep -c "^2001:db8:2::/64 fe80::1 - test0$" /etc/sysconfig/network/routes)" = 1 + grep -qx "2001:db8:2::/64 fe80::1 - test01" /etc/sysconfig/network/routes + test "$(grep -c " - -$" /etc/sysconfig/network/routes)" = 0 + ' +} + +@test 'routeop treats dotted interface names literally in saved routes' { + run_routes ' + ip link add test0.1 type dummy + ip link set test0.1 up + printf "%s\n" "2001:db8:2::/64 fe80::1 - test0x1" >/etc/sysconfig/network/routes + /tmp/postscripts/routeop add 2001:db8:2:: 64 fe80::1 test0.1 + grep -Fqx "2001:db8:2::/64 fe80::1 - test0.1" /etc/sysconfig/network/routes + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0.1 + test "$(sed "/^#/d;/^$/d" /etc/sysconfig/network/routes)" = "2001:db8:2::/64 fe80::1 - test0x1" + ' +} + +@test 'routeop retains the device in legacy Red Hat route6 files' { + run_routes ' + rm /etc/SUSE-brand + touch /etc/redhat-release + mkdir -p /etc/sysconfig/network-scripts + export OSVER=rhels8 + /tmp/postscripts/routeop replace 2001:db8:2:: 64 fe80::1 test0 + test "$(cat /etc/sysconfig/network-scripts/route6-test0)" = "2001:db8:2::/64 via fe80::1 dev test0" + ip -6 route show 2001:db8:2::/64 | grep -q "via fe80::1 dev test0" + printf "%s\n" "test0 2001:db8:2::/64 fe80::1" "test01 2001:db8:2::/64 fe80::1" >/etc/sysconfig/static-routes-ipv6 + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0 + test ! -s /etc/sysconfig/network-scripts/route6-test0 + test "$(cat /etc/sysconfig/static-routes-ipv6)" = "test01 2001:db8:2::/64 fe80::1" + test -z "$(ip -6 route show 2001:db8:2::/64)" + echo "2001:db8:2::/64 via fe80::1" >/etc/sysconfig/network-scripts/route6-test0 + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0 + test ! -s /etc/sysconfig/network-scripts/route6-test0 + ' +} + +@test 'routeop scopes Debian interface up and down gateway commands' { + run_routes ' + rm /etc/SUSE-brand + touch /etc/debian_version + mkdir -p /etc/network/interfaces.d + printf "%s\n" "#XCAT_CONFIG" "source /etc/network/interfaces.d/*" >/etc/network/interfaces + export OSVER=ubuntu24.04 + for layout in last middle; do + printf "%s\n" "auto test0" "iface test0 inet manual" >/etc/network/interfaces.d/test0 + printf "%s\n" " up route -A inet6 add 2001:db8:2::/64 gw fe80::1" \ + " down route -A inet6 del 2001:db8:2::/64 gw fe80::1" \ + "post-up ip -6 route replace 2001:db8:2::/64 via fe80::1" >>/etc/network/interfaces.d/test0 + if [ "$layout" = middle ]; then echo "iface test1 inet manual" >>/etc/network/interfaces.d/test0; fi + /tmp/postscripts/routeop add 2001:db8:2:: 64 fe80::1 test0 + grep -Fxq " up route -A inet6 add 2001:db8:2::/64 gw fe80::1 dev test0" /etc/network/interfaces.d/test0 + grep -Fxq " down route -A inet6 del 2001:db8:2::/64 gw fe80::1 dev test0" /etc/network/interfaces.d/test0 + if grep -Fxq "post-up ip -6 route replace 2001:db8:2::/64 via fe80::1" /etc/network/interfaces.d/test0; then exit 1; fi + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0 + test "$(grep -c "2001:db8:2::" /etc/network/interfaces.d/test0)" = 0 + /tmp/postscripts/routeop replace 2001:db8:2:: 64 fe80::1 test0 + grep -Fxq "post-up ip -6 route replace 2001:db8:2::/64 via fe80::1 dev test0" /etc/network/interfaces.d/test0 + ip -6 route show 2001:db8:2::/64 | grep -q "via fe80::1 dev test0" + /tmp/postscripts/routeop delete 2001:db8:2:: 64 fe80::1 test0 + test "$(grep -c "2001:db8:2::" /etc/network/interfaces.d/test0)" = 0 + done + ' +} From 60beaecead4e8b1008dcb2fc0a202f57bd58c1c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:18:03 -0300 Subject: [PATCH 101/129] fix(syslog): create the local log directory before setting its owner Create missing Debian-family log directories before assigning their owner. Use mode 0750 for syslog-owned directories. In the legacy reference-owner path, copy the parent directory mode so group-writing daemons retain access. Preserve existing directory modes, log files and forwarding policy. Stop with an error before restarting syslog if the directory cannot be created. Keep existing ownership-command failures nonfatal. --- xCAT/postscripts/syslog | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/xCAT/postscripts/syslog b/xCAT/postscripts/syslog index b0acfedd35..7840b3b763 100755 --- a/xCAT/postscripts/syslog +++ b/xCAT/postscripts/syslog @@ -83,6 +83,14 @@ is_lsb_ubuntu () # failure (not Ubuntu), which is the correct outcome. } +set_log_directory_owner() +{ + local mode=$1 + shift + mkdir -p -m "$mode" /var/log/xcat || exit $? + chown "$@" /var/log/xcat +} + config_Rsyslog_C3() { isReceiving=0 @@ -127,7 +135,7 @@ config_Rsyslog_C3() touch /var/log/messages chown syslog:adm /var/log/messages sed -i 's/\$PrivDropToGroup syslog/\$PrivDropToGroup adm/' $2 - chown syslog:adm /var/log/xcat + set_log_directory_owner 0750 syslog:adm fi else sed -i 's/^\(\*\..*\)/\#\1/; @@ -286,7 +294,7 @@ config_rsyslog_V8() if ( pmatch $OSVER "ubuntu*" ) || ( is_lsb_ubuntu ) || ( pmatch $OSVER "debian*" ); then chown syslog:adm /var/log/messages sed -i 's/\$PrivDropToGroup syslog/\$PrivDropToGroup adm/' $conf_file - chown syslog:adm /var/log/xcat + set_log_directory_owner 0750 syslog:adm fi # Mark the start of xCAT section @@ -523,7 +531,7 @@ else touch /var/log/messages if ( pmatch $OSVER "ubuntu*" ) || ( is_lsb_ubuntu ) || ( pmatch $OSVER "debian*" ); then chown --reference=/var/log /var/log/messages - chown --reference=/var/log /var/log/xcat + set_log_directory_owner "$(stat -c %a /var/log)" --reference=/var/log fi if [ $ng -eq 0 ]; then if [ ! -f $conf_file.XCATORIG ]; then From ea4738a5cee041d3876050de6760afe3ccfe6983 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:18:03 -0300 Subject: [PATCH 102/129] test(syslog): verify directory setup and native log delivery Execute the complete postscript and check the daemon UID before real UDP log delivery. Cover fresh and repeated MN/SN setup, restricted directories, legacy ownership and modes, and a blocked directory path. Keep the upgrade wrapper and forwarding cases as compatibility controls. Select older configuration branches through their version-report boundary; use the installed daemon, without claiming old-daemon qualification. Run the isolated native cases in CI. --- .github/workflows/xcat_test.yml | 1 + xCAT-test/native/syslog_log_directory.bats | 197 +++++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 xCAT-test/native/syslog_log_directory.bats diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 629fc208f0..93af942c58 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -49,6 +49,7 @@ jobs: sudo cp -R xCAT-test xCAT-server perl-xCAT xCAT "$workdir/" status=0 sudo sh -c 'cd "$1" && bats xCAT-test/native/getinstdisk_selection.bats' sh "$workdir" || status=1 + sudo sh -c 'cd "$1" && bats xCAT-test/native/syslog_log_directory.bats' sh "$workdir" || status=1 sudo sh -c 'cd "$1" && prove -v xCAT-test/native/getinstdisk_installer.t xCAT-test/native/enablekdump_per_node.t xCAT-test/native/sudoer_password_source.t xCAT-test/native/remoteshell_credentials.t' sh "$workdir" || status=1 exit "$status" - name: Prepare xCAT syslog directory diff --git a/xCAT-test/native/syslog_log_directory.bats b/xCAT-test/native/syslog_log_directory.bats new file mode 100644 index 0000000000..c58dba70fb --- /dev/null +++ b/xCAT-test/native/syslog_log_directory.bats @@ -0,0 +1,197 @@ +#!/usr/bin/env bats + +load '../bats/helpers/script_sandbox' + +setup() +{ + [ "$(id -u)" -eq 0 ] || skip 'native syslog ownership checks require root' + setup_script_sandbox cat cp dirname grep egrep sed tr uname awk cut head touch mkdir \ + chown chmod stat id sleep logger rm date mktemp + local index daemon + # Keep real account IDs so rsyslog can drop its privileges. + for index in "${!sandbox[@]}"; do + if [ "${sandbox[$index]}" = --unshare-all ]; then + sandbox[$index]=--unshare-pid + fi + done + sandbox+=(--unshare-net --unshare-ipc --unshare-uts + --ro-bind "$(repo_path xCAT/postscripts)" /tmp/postscripts + --ro-bind "$(repo_path xCAT/xcat-upgrade-functions.sh)" /tmp/upgrade.sh) + daemon=$(PATH=/usr/sbin:/sbin:/usr/bin:/bin type -P rsyslogd) || return 1 + cp -L "$daemon" "$fixture/bin/rsyslogd-real" + daemon=$(PATH=/usr/sbin:/sbin:/usr/bin:/bin type -P ip) || return 1 + cp -L "$daemon" "$fixture/bin/ip" + cp /etc/passwd /etc/group /etc/nsswitch.conf "$fixture/etc/" + id syslog >/dev/null || return 1 + mkdir -p "$fixture/etc/rsyslog.d" "$fixture/etc/default" \ + "$fixture/etc/systemd/system" "$fixture/var/log" "$fixture/var/lib/rsyslog" + touch "$fixture/etc/systemd/system/rsyslog.service" + cat >"$fixture/etc/rsyslog.conf" <<'CONF' +$PrivDropToUser syslog +$PrivDropToGroup syslog +module(load="imudp") +input(type="imudp" address="127.0.0.1" port="1514") +local4.* /var/log/xcat/cluster.log +$IncludeConfig /etc/rsyslog.d/*.conf +CONF + cat >"$fixture/bin/rsyslogd" <<'SH' +#!/bin/sh +if [ "$1" = -v ] && [ "$SYSLOG_TEST_VERSION" != 8 ]; then + echo "rsyslogd $SYSLOG_TEST_VERSION.0" +else + exec /bin/rsyslogd-real "$@" +fi +SH + cat >"$fixture/bin/systemctl" <<'SH' +#!/bin/bash +set -eu +[ "$*" = 'restart rsyslog' ] +if [ -s /run/rsyslog.pid ]; then + previous=$(cat /run/rsyslog.pid) + kill "$previous" + for ((i=0; i<100; i++)); do + [ -d "/proc/$previous" ] || break + sleep .02 + done + [ ! -d "/proc/$previous" ] + rm -f /run/rsyslog.pid +fi +/bin/rsyslogd-real -n -i /run/rsyslog.pid -f /etc/rsyslog.conf >>/run/daemon.log 2>&1 "$fixture/bin/check-delivery" <<'SH' +#!/bin/bash +set -eu +uid=$(id -u syslog) +expected="^Uid:[[:space:]]+$uid[[:space:]]+$uid[[:space:]]+$uid[[:space:]]+$uid$" +for ((i=0; i<100; i++)); do + if grep -Eq "$expected" /proc/$(cat /run/rsyslog.pid)/status; then break; fi + sleep .02 +done +grep -Eq "$expected" /proc/$(cat /run/rsyslog.pid)/status +logger -n 127.0.0.1 -P 1514 -d -p local4.info "$1" +for ((i=0; i<100; i++)); do + if grep -q "$1" /var/log/xcat/cluster.log; then break; fi + sleep .02 +done +grep -q "$1" /var/log/xcat/cluster.log +SH + cat >"$fixture/bin/log-test" <<'SH' +#!/bin/bash +set -eu +ip link set lo up +rm -f /run/rsyslog.pid +if [ "$SYSLOG_TEST_ROLE" = mn ]; then touch /etc/xCATMN; fi +if [ "$SYSLOG_TEST_VERSION" = 3 ]; then + echo 'SYSLOGD_OPTIONS="-c 3"' >/etc/default/rsyslog +fi +case "$SYSLOG_TEST_DIRECTORY" in + absent) ;; + blocked) touch /var/log/xcat ;; + *) + mkdir -m "$SYSLOG_TEST_DIRECTORY" /var/log/xcat + echo preserved >/var/log/xcat/old.log + chmod 0600 /var/log/xcat/old.log + ;; +esac +exec /bin/bash -eu -c "$1" +SH + chmod +x "$fixture/bin/rsyslogd" "$fixture/bin/systemctl" \ + "$fixture/bin/log-test" "$fixture/bin/check-delivery" +} + +run_syslog() +{ + local role=$1 directory=$2 version=$3 osver=$4 code=$5 + run "${sandbox[@]}" --setenv OSVER "$osver" --setenv SYSLOG '' \ + --setenv NTYPE service --setenv SVLOGLOCAL "$([ "$role" = forward ] && echo 0 || echo 1)" \ + --setenv MASTER 127.0.0.1:1515 --setenv SYSLOG_TEST_ROLE "$role" \ + --setenv SYSLOG_TEST_DIRECTORY "$directory" --setenv SYSLOG_TEST_VERSION "$version" \ + /bin/bash /bin/log-test "$code" + if [ "$status" -ne 0 ]; then + cat "$fixture/run/daemon.log" >&2 + return 1 + fi +} + +@test 'syslog creates a local log directory and delivers as syslog on MN and SN' { + local role osver + for role in mn sn; do + for osver in ubuntu24.04 debian12; do + run_syslog "$role" absent 8 "$osver" ' + for pass in 1 2; do + /tmp/postscripts/syslog + test "$(stat -c %U:%G:%a /var/log/xcat)" = syslog:adm:750 + check-delivery "directory-test-$pass" + done + ' + rm -rf "$fixture/var/log/xcat" + rm -f "$fixture/etc/xCATMN" + done + done +} + +@test 'syslog preserves existing directory modes and log file ownership' { + local mode + for mode in 0700 0750; do + run_syslog mn "$mode" 8 ubuntu24.04 ' + before=$(stat -c %u:%g:%a /var/log/xcat/old.log) + /tmp/postscripts/syslog + test "$(stat -c %a /var/log/xcat)" = "${SYSLOG_TEST_DIRECTORY#0}" + test "$(stat -c %U:%G /var/log/xcat)" = syslog:adm + test "$(stat -c %u:%g:%a /var/log/xcat/old.log)" = "$before" + test "$(cat /var/log/xcat/old.log)" = preserved + check-delivery restricted-directory-test + ' + rm -rf "$fixture/var/log/xcat" + done +} + +@test 'syslog prepares the log directory after the real upgrade wrapper' { + run_syslog mn absent 8 ubuntu24.04 ' + . /tmp/upgrade.sh + xcat_run_upgrade /tmp/postscripts/syslog + test "$(stat -c %U:%G /var/log/xcat)" = syslog:adm + test -s /var/log/xcat/upgrade.log + check-delivery upgrade-directory-test + ' +} + +@test 'syslog retains rsyslog compatibility-mode directory ownership' { + run_syslog mn absent 3 ubuntu24.04 ' + /tmp/postscripts/syslog + test "$(stat -c %U:%G:%a /var/log/xcat)" = syslog:adm:750 + check-delivery compatibility-directory-test + ' +} + +@test 'syslog retains the legacy reference-directory ownership' { + run_syslog mn absent 5 ubuntu24.04 ' + chown root:syslog /var/log + chmod 0775 /var/log + /tmp/postscripts/syslog + test "$(stat -c %u:%g /var/log/xcat)" = "$(stat -c %u:%g /var/log)" + test "$(stat -c %a /var/log/xcat)" = 775 + check-delivery legacy-directory-test + ' +} + +@test 'syslog does not create a local directory on forwarding nodes' { + run_syslog forward absent 8 ubuntu24.04 ' + /tmp/postscripts/syslog + test ! -e /var/log/xcat + grep -qx "\*\.\* @127.0.0.1:1515" /etc/rsyslog.d/remote.conf + ' +} + +@test 'syslog reports failure when the directory path is a file' { + run_syslog mn blocked 8 ubuntu24.04 ' + if /tmp/postscripts/syslog; then exit 1; fi + test -f /var/log/xcat + test ! -e /run/rsyslog.pid + ' +} From 103076c8522d2d1c59517d00910d0c97f139aab8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:08:42 -0300 Subject: [PATCH 103/129] fix(debian): skip service actions inside proc-mounted chroots --- perl-xCAT/debian/postrm | 3 ++- xCAT-server/debian/prerm | 4 +++- xCATsn/debian/postinst | 3 ++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/perl-xCAT/debian/postrm b/perl-xCAT/debian/postrm index 6b983d64c7..b5617e6d6a 100644 --- a/perl-xCAT/debian/postrm +++ b/perl-xCAT/debian/postrm @@ -21,7 +21,8 @@ set -e case "$1" in upgrade) - if [ -x /opt/xcat/sbin/restartxcatd ] && [ -f "/proc/cmdline" ]; then + if [ -x /opt/xcat/sbin/restartxcatd ] && [ -f /proc/cmdline ] && + [ "$(stat -c '%d:%i' /)" = "$(stat -c '%d:%i' /proc/1/root/. 2>/dev/null)" ]; then . /etc/profile.d/xcat.sh XCATROOT=/opt/xcat /opt/xcat/sbin/restartxcatd -r fi diff --git a/xCAT-server/debian/prerm b/xCAT-server/debian/prerm index d0b466a4f9..9228fcc2f6 100644 --- a/xCAT-server/debian/prerm +++ b/xCAT-server/debian/prerm @@ -21,7 +21,8 @@ xcatd_init_compat=/opt/xcat/share/xcat/scripts/xcatd-init-compat case "$1" in remove) - if [ -f "/proc/cmdline" ]; then # prevent running it during install into chroot image + if [ -f /proc/cmdline ] && + [ "$(stat -c '%d:%i' /)" = "$(stat -c '%d:%i' /proc/1/root/. 2>/dev/null)" ]; then if "$xcatd_init_compat" can-use-systemctl; then systemctl stop xcatd.service systemctl disable --now xcat-uftp-listener.service >/dev/null 2>&1 || true @@ -32,6 +33,7 @@ case "$1" in if "$xcatd_init_compat" uses-systemd --explicit-target; then if command -v systemctl >/dev/null 2>&1; then systemctl disable xcatd.service + systemctl disable xcat-uftp-listener.service >/dev/null 2>&1 || true fi else if command -v update-rc.d >/dev/null 2>&1; then diff --git a/xCATsn/debian/postinst b/xCATsn/debian/postinst index f674fb7eb8..7621b07495 100644 --- a/xCATsn/debian/postinst +++ b/xCATsn/debian/postinst @@ -64,7 +64,8 @@ case "$1" in a2enmod -q headers >/dev/null 2>&1 || : fi - if [ -f "/proc/cmdline" ]; then # prevent running it during install into chroot image + if [ -f /proc/cmdline ] && + [ "$(stat -c '%d:%i' /)" = "$(stat -c '%d:%i' /proc/1/root/. 2>/dev/null)" ]; then if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then systemctl start xcatd.service elif [ -x /etc/init.d/xcatd ]; then From b6f9294a792ef623dcad7b2eff2a4f424f05d1c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:11:34 -0300 Subject: [PATCH 104/129] test(debian): exercise service callers in proc-mounted chroots --- .github/workflows/xcat_test.yml | 2 +- xCAT-test/native/debian_chroot_services.t | 147 ++++++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 xCAT-test/native/debian_chroot_services.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 629fc208f0..a7086fc57f 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -15,7 +15,7 @@ jobs: - name: Install lifecycle test dependencies run: sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --no-install-suggests ucf debconf-utils systemd libxml-simple-perl apache2 curl - name: Test Debian package lifecycle - run: prove -v xCAT-test/native/xcatd_debian_lifecycle.t xCAT-test/native/xcatd_restart_callers.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t + run: prove -v xCAT-test/native/xcatd_debian_lifecycle.t xCAT-test/native/xcatd_restart_callers.t xCAT-test/native/debian_chroot_services.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t - name: Test optional statelite host keys if: ${{ !cancelled() }} run: prove -v xCAT-test/native/statelite_optional_hostkey.t diff --git a/xCAT-test/native/debian_chroot_services.t b/xCAT-test/native/debian_chroot_services.t new file mode 100644 index 0000000000..10362f1581 --- /dev/null +++ b/xCAT-test/native/debian_chroot_services.t @@ -0,0 +1,147 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use Test::More; +use File::Path qw(make_path); +use XCAT::Test::Lifecycle; + +plan skip_all => 'Run as an ordinary user on Debian or Ubuntu' + unless $^O eq 'linux' && $< != 0 && -f '/etc/debian_version'; +my %packages = map { $_ => XCAT::Test::Lifecycle::build_deb($_) } + qw(xCAT-server xCATsn); + +sub succeeds { + my ($label, @result) = @_; + is($result[0], 0, $label) or diag "$result[1]$result[2]"; +} + +for my $mode (qw(without-proc live proc-chroot systemd-chroot)) { + subtest $mode => sub { + my $root = XCAT::Test::Lifecycle->new; + $root->{live} = $mode ne 'without-proc'; + $root->{chroot} = $mode =~ /chroot/ ? 1 : 0; + my $active = $mode eq 'live'; + { + local $root->{deb} = $packages{'xCAT-server'}; + succeeds('unpack the server payload', $root->run('dpkg-deb', '-x', '/package.deb', '/unpacked')); + } + make_path(map { $root->path($_) } qw(/opt/xcat/lib /opt/xcat/sbin /opt/xcat/share/xcat /etc/apache2/conf-enabled)); + succeeds('stage packaged helpers', $root->run('cp', '-a', + '/unpacked/opt/xcat/share/xcat/scripts', '/opt/xcat/share/xcat/')); + succeeds('stage the packaged fast-restart command', $root->run('cp', + '/unpacked/opt/xcat/sbin/restartxcatd', '/opt/xcat/sbin/')); + symlink '/source/perl-xCAT', $root->path('/opt/xcat/lib/perl') or die "link Perl modules: $!"; + $root->write('/etc/os-release', $mode eq 'systemd-chroot' + ? "ID=ubuntu\nVERSION_ID=24.04\n" : "ID=ubuntu\nVERSION_ID=14.04\n"); + make_path($root->path('/run/systemd/system')) if $mode eq 'systemd-chroot'; + succeeds('install the packaged legacy init script', $root->run('cp', + '/opt/xcat/share/xcat/scripts/xcatd', '/etc/init.d/xcatd')); + if ($mode eq 'systemd-chroot') { + for my $service (qw(xcatd xcat-uftp-listener)) { + succeeds("stage the $service unit", $root->run('cp', + "/unpacked/lib/systemd/system/$service.service", '/usr/lib/systemd/system/')); + succeeds("enable $service in the image", $root->run('systemctl', 'enable', "$service.service")); + ok(-l $root->path("/etc/systemd/system/multi-user.target.wants/$service.service"), + "$service starts with an enabled link"); + } + } else { + succeeds('register xcatd in the image', $root->run('update-rc.d', 'xcatd', 'defaults')); + my @enabled = glob $root->path('/etc/rc?.d/S??xcatd'); + ok(@enabled, 'xcatd starts with enabled runlevels'); + } + $root->write('/etc/profile.d/xcat.sh', + "export XCATROOT=/opt/xcat\nexport PATH=/opt/xcat/sbin:/usr/sbin:/usr/bin:/sbin:/bin\n"); + unlink $root->path('/usr/sbin/policy-rc.d') or die "unlink policy fixture: $!" + if -l $root->path('/usr/sbin/policy-rc.d'); + $root->write('/usr/sbin/policy-rc.d', <<'SH', oct('755')); +#!/bin/sh +printf '%s\n' "$*" >> /policy-calls +exit 101 +SH + $root->record_command('/opt/xcat/sbin/xcatd'); + $root->record_command('/etc/init.d/apache2'); + $root->write('/etc/init.d/apache2', $root->read('/etc/init.d/apache2') . <<'SH', oct('755')); +### BEGIN INIT INFO +# Provides: apache2 +# Required-Start: $network +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Apache command boundary +### END INIT INFO +SH + succeeds('register the Apache dependency', $root->run('update-rc.d', 'apache2', 'defaults')); + $root->write('/calls', ''); + if ($root->{chroot}) { + succeeds('proc is mounted inside a different process root', $root->run('/bin/sh', '-c', + q{test -f /proc/cmdline && test "$(stat -c '%d:%i' /)" != "$(stat -c '%d:%i' /proc/1/root/.)"})); + } + if ($mode ne 'systemd-chroot') { + succeeds('native service policy denies an explicit start', + $root->run('invoke-rc.d', 'xcatd', 'start')); + is($root->read('/calls'), '', 'the policy control cannot reach the daemon'); + like($root->read('/policy-calls'), qr/xcatd.*start/, 'the native dispatcher consulted policy'); + } + succeeds('configure the service-node package', + $root->deb_script($packages{'xCATsn'}, 'postinst', 'configure')); + is($root->read('/calls'), $active + ? "xcatd <-p> \napache2 \n" : '', + 'only the live root starts xcatd and reloads Apache'); + $root->write('/calls', ''); + succeeds('upgrade the Perl package through the real fast-restart command', + $root->run('/bin/sh', '/source/perl-xCAT/debian/postrm', 'upgrade', '2.20.0')); + is($root->read('/calls'), $active ? "xcatd <-p> \n" : '', + 'only the live root reaches xcatd through restartxcatd'); + + $root->write('/sentinel.pl', <<'PERL'); +use strict; +use warnings; +$0 = 'xcatd: lifecycle sentinel'; +$SIG{TERM} = sub { open(my $fh, '>', '/stopped') or die $!; print {$fh} "TERM\n"; close($fh); exit 0; }; +open(my $pid, '>', '/var/run/xcatd.pid') or die $!; +print {$pid} "$$\n"; +close($pid) or die $!; +sleep 1 while 1; +PERL + local $root->{deb} = $packages{'xCAT-server'}; + succeeds('unpack the server control scripts', + $root->run('dpkg-deb', '-e', '/package.deb', '/tmp/server-control')); + succeeds('remove the server while an isolated process is running', + $root->run('/bin/sh', '-c', <<'SH', 'remove', $active ? 'live' : 'image')); +set -eu +mkdir -p /var/run +perl /sentinel.pl & +daemon=$! +trap 'kill -KILL "$daemon" 2>/dev/null || :; wait "$daemon" 2>/dev/null || :' EXIT +attempt=0 +until test -s /var/run/xcatd.pid; do + attempt=$((attempt + 1)) + test "$attempt" -lt 100 || exit 20 + sleep .05 +done +/bin/sh /tmp/server-control/prerm remove +if [ "$1" = live ]; then + test -f /stopped + test ! -f /var/run/xcatd.pid +else + kill -0 "$daemon" + test ! -f /stopped + test -f /var/run/xcatd.pid +fi +SH + is(-e $root->path('/stopped') ? $root->read('/stopped') : '', + $active ? "TERM\n" : '', 'only live-root removal signals the process'); + if ($mode eq 'systemd-chroot') { + for my $service (qw(xcatd xcat-uftp-listener)) { + ok(!-l $root->path("/etc/systemd/system/multi-user.target.wants/$service.service"), + "removal disables $service without starting the image"); + } + } else { + my @links = glob $root->path('/etc/rc?.d/S??xcatd'); + is_deeply(\@links, [], 'removal still disables offline service registration'); + } + }; +} +done_testing; From a7d7b85c7cfeded02134ebe3b83d99872fcfc652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:13:26 -0300 Subject: [PATCH 105/129] test(build): limit the upgrade log allocation fault --- xCAT-test/native/package_upgrade_logging.t | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/xCAT-test/native/package_upgrade_logging.t b/xCAT-test/native/package_upgrade_logging.t index e387c4a685..b6e233ee26 100644 --- a/xCAT-test/native/package_upgrade_logging.t +++ b/xCAT-test/native/package_upgrade_logging.t @@ -57,7 +57,13 @@ SHELL my $failed = $case eq 'command-failure' || $case eq 'warning-failure'; $root->write('/command-status', "17\n") if $failed; if ($case eq 'temporary-failure') { - $root->write('/test-bin/mktemp', "#!/bin/sh\necho 'temporary allocation failed' >&2\nexit 19\n", 0755); + $root->write('/test-bin/mktemp', <<'SH', oct('755')); +#!/bin/sh +case "$1" in + /tmp/xcat-upgrade.*) echo 'temporary allocation failed' >&2; exit 19 ;; +esac +exec /usr/bin/mktemp "$@" +SH } for my $service (qw(installservice udpservice mainservice)) { $root->write("/tmp/xcat/$service.pid", "$service pid\n"); From 2f22c0d4586b7ecd8dc7ff9f90aa6fb8d87c0969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:13:26 -0300 Subject: [PATCH 106/129] fix(debian): retain management configuration context until success --- xCAT/debian/postinst | 25 +++++++++++++++++++++++-- xCAT/debian/postrm | 20 ++++++++++++++++++++ xCAT/debian/preinst | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 2 deletions(-) create mode 100755 xCAT/debian/postrm create mode 100755 xCAT/debian/preinst diff --git a/xCAT/debian/postinst b/xCAT/debian/postinst index bbb179eded..bba19ba253 100644 --- a/xCAT/debian/postinst +++ b/xCAT/debian/postinst @@ -20,11 +20,28 @@ set -e case "$1" in configure) + state_dir=/var/lib/xcat/configure-state + if [ -L "$state_dir" ] || [ -L "$state_dir/context" ] || + { [ -e "$state_dir" ] && [ ! -d "$state_dir" ]; }; then + echo "Invalid xCAT configuration state: $state_dir" >&2 + exit 1 + fi + if [ -f "$state_dir/context" ]; then + context=$(cat "$state_dir/context") + case "$context" in + fresh|upgrade) ;; + *) echo "Invalid xCAT configuration context in $state_dir/context: $context" >&2; exit 1 ;; + esac + elif [ -f /tmp/xCAT_upgrade.tmp ]; then + context=upgrade + else + context=fresh + fi # Make dir for the current pid mkdir -p /var/run/xcat cp -f /opt/xcat/share/xcat/scripts/xHRM /install/postscripts/ . /etc/profile.d/xcat.sh - if [ -f /tmp/xCAT_upgrade.tmp ] + if [ "$context" = upgrade ] then if [ -r "/tmp/xcat/installservice.pid" ]; then mv /tmp/xcat/installservice.pid /var/run/xcat/installservice.pid @@ -36,7 +53,6 @@ case "$1" in mv /tmp/xcat/mainservice.pid /var/run/xcat/mainservice.pid fi xcat_run_upgrade xcatconfig -u -V - rm /tmp/xCAT_upgrade.tmp else xcatconfig -i fi @@ -75,4 +91,9 @@ esac #DEBHELPER# +if [ "$1" = configure ]; then + rm -f "$state_dir/context" /tmp/xCAT_upgrade.tmp + rmdir "$state_dir" 2>/dev/null || : +fi + exit 0 diff --git a/xCAT/debian/postrm b/xCAT/debian/postrm new file mode 100755 index 0000000000..65ea2b2b66 --- /dev/null +++ b/xCAT/debian/postrm @@ -0,0 +1,20 @@ +#!/bin/sh +set -e + +case "$1" in + remove|purge|abort-install|disappear) + state_dir=/var/lib/xcat/configure-state + if [ -L "$state_dir" ]; then + echo "Invalid xCAT configuration state directory: $state_dir" >&2 + exit 1 + fi + rm -f "$state_dir/context" "$state_dir"/context.* /tmp/xCAT_upgrade.tmp + rmdir "$state_dir" 2>/dev/null || : + ;; + upgrade|failed-upgrade|abort-upgrade) ;; + *) echo "postrm called with unknown argument: $1" >&2; exit 1 ;; +esac + +#DEBHELPER# + +exit 0 diff --git a/xCAT/debian/preinst b/xCAT/debian/preinst new file mode 100755 index 0000000000..5231f71e49 --- /dev/null +++ b/xCAT/debian/preinst @@ -0,0 +1,42 @@ +#!/bin/sh +set -e + +state_dir=/var/lib/xcat/configure-state + +case "$1" in + install) context=fresh ;; + upgrade) context=upgrade ;; + abort-upgrade) context= ;; + *) echo "preinst called with unknown argument: $1" >&2; exit 1 ;; +esac + +if [ -n "$context" ]; then + if [ -L "$state_dir" ] || [ -L "$state_dir/context" ] || + { [ -e "$state_dir" ] && [ ! -d "$state_dir" ]; }; then + echo "Invalid xCAT configuration state directory: $state_dir" >&2 + exit 1 + fi + # dpkg skips prerm when the previous package was only unpacked. + if [ "$context" = upgrade ] && [ ! -f /tmp/xCAT_upgrade.tmp ]; then + if [ -f "$state_dir/context" ]; then + context=$(cat "$state_dir/context") + case "$context" in + fresh|upgrade) ;; + *) echo "Invalid xCAT configuration context in $state_dir/context: $context" >&2; exit 1 ;; + esac + else + context=fresh + fi + fi + mkdir -p -m 700 "$state_dir" + chmod 700 "$state_dir" + temporary=$(mktemp "$state_dir/context.XXXXXX") + trap 'rm -f "$temporary"' EXIT + trap 'exit 1' HUP INT TERM + printf '%s\n' "$context" > "$temporary" + mv -f "$temporary" "$state_dir/context" +fi + +#DEBHELPER# + +exit 0 From 11e6e642c4f8c65dbc258c173de9677a46826430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:13:26 -0300 Subject: [PATCH 107/129] test(debian): cover interrupted management package transactions --- .github/workflows/xcat_test.yml | 2 +- xCAT-test/native/debian_management_recovery.t | 183 ++++++++++++++++++ 2 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 xCAT-test/native/debian_management_recovery.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index a7086fc57f..cfce7c8295 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -15,7 +15,7 @@ jobs: - name: Install lifecycle test dependencies run: sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --no-install-suggests ucf debconf-utils systemd libxml-simple-perl apache2 curl - name: Test Debian package lifecycle - run: prove -v xCAT-test/native/xcatd_debian_lifecycle.t xCAT-test/native/xcatd_restart_callers.t xCAT-test/native/debian_chroot_services.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t + run: prove -v xCAT-test/native/xcatd_debian_lifecycle.t xCAT-test/native/xcatd_restart_callers.t xCAT-test/native/debian_chroot_services.t xCAT-test/native/debian_management_recovery.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t - name: Test optional statelite host keys if: ${{ !cancelled() }} run: prove -v xCAT-test/native/statelite_optional_hostkey.t diff --git a/xCAT-test/native/debian_management_recovery.t b/xCAT-test/native/debian_management_recovery.t new file mode 100644 index 0000000000..8498e5c616 --- /dev/null +++ b/xCAT-test/native/debian_management_recovery.t @@ -0,0 +1,183 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use Test::More; +use File::Temp qw(tempdir); +use File::Slurper qw(read_binary write_binary); +use XCAT::Test::Lifecycle; + +plan skip_all => 'Run as an ordinary user on Debian or Ubuntu' + unless $^O eq 'linux' && $< != 0 && -f '/etc/debian_version'; +my $deb = XCAT::Test::Lifecycle::build_deb('xCAT'); +my $fault = tempdir(CLEANUP => 1); +XCAT::Test::Lifecycle::checked('dpkg-deb', '-R', $deb, "$fault/package"); +write_binary("$fault/package/DEBIAN/preinst", "#!/bin/sh\nexit 17\n"); +chmod 0755, "$fault/package/DEBIAN/preinst" or die "chmod failing preinst: $!"; +XCAT::Test::Lifecycle::checked('dpkg-deb', '--root-owner-group', '-b', "$fault/package", "$fault/failure.deb"); +for my $script (qw(preinst postinst postrm)) { + unlink "$fault/package/DEBIAN/$script" or die "remove legacy fixture script: $!" + if -f "$fault/package/DEBIAN/$script"; +} +my $control = read_binary("$fault/package/DEBIAN/control"); +$control =~ s/^Version:.*$/Version: 2.0/m or die 'legacy fixture has no Version'; +write_binary("$fault/package/DEBIAN/control", $control); +XCAT::Test::Lifecycle::checked('dpkg-deb', '--root-owner-group', '-b', "$fault/package", "$fault/legacy.deb"); + +sub succeeds { + my ($label, @result) = @_; + is($result[0], 0, $label) or diag "$result[1]$result[2]"; +} + +sub management_root { + my $root = XCAT::Test::Lifecycle->new; + $root->write('/opt/xcat/share/xcat/scripts/xHRM', ''); + $root->write('/opt/xcat/sbin/xcatconfig', <<'SH', oct('755')); +#!/bin/sh +printf '%s\n' "$*" >> /config-calls +if [ -f /config-fail ]; then exit 17; fi +SH + $root->write('/etc/init.d/apache2', <<'SH', oct('755')); +#!/bin/sh +if [ -f /apache-fail ]; then exit 19; fi +SH + $root->write('/config-calls', ''); + return $root; +} + +for my $case (qw(fresh-retry fresh-reinstall fresh-abort-retry fresh-legacy-return removed-fresh-retry removed-fresh-abort removed-fresh-legacy-return upgrade-retry apache-retry cleared-tmp + failed-remove failed-purge abort-remove abort-retry)) { + subtest $case => sub { + my $root = management_root(); + if ($case !~ /^fresh/) { + succeeds('install the previous package', $root->install_deb( + $case eq 'removed-fresh-legacy-return' ? "$fault/legacy.deb" : $deb)); + } + if ($case =~ /^removed-fresh/) { + succeeds('remove the configured package but keep its conffiles', + $root->run('dpkg', '--force-depends', '--remove', 'xcat')); + } + my $fresh_install = $case =~ /^(?:fresh|removed-fresh)/; + my $remove_after_failure = $case =~ /^(?:failed|abort)-(?:remove|purge)$/; + $root->write('/config-calls', ''); + $root->write($case eq 'apache-retry' ? '/apache-fail' : '/config-fail', '') + unless $case =~ /^abort/; + my ($status, $out, $err) = $root->install_deb($case =~ /^abort/ ? "$fault/failure.deb" : $deb); + isnt($status, 0, 'the injected transaction failure reaches dpkg'); + like($err, $case =~ /^abort/ ? qr/pre-installation script.*exit status 17/ + : $case eq 'apache-retry' ? qr/post-installation script.*exit status 19/ + : qr/post-installation script.*exit status 17/, 'failure comes from the intended boundary'); + is($root->read('/config-calls'), $case =~ /^abort/ ? '' + : $fresh_install ? "-i\n" : "-u -V\n", 'the first attempt uses the intended configuration mode'); + unlink $root->path('/config-fail') if -f $root->path('/config-fail'); + unlink $root->path('/apache-fail') if -f $root->path('/apache-fail'); + if ($case eq 'fresh-abort-retry' || $case eq 'removed-fresh-abort') { + my ($aborted, $out, $err) = $root->install_deb("$fault/failure.deb"); + isnt($aborted, 0, 'a later unpack can also fail before fresh configuration succeeds'); + like($err, qr/pre-installation script.*exit status 17/, 'the later failure reaches the intended preinst'); + } + if ($case =~ /legacy-return$/) { + succeeds('configure an older package without context hooks', $root->install_deb("$fault/legacy.deb")); + } + if ($case eq 'cleared-tmp') { + unlink $root->path('/tmp/xCAT_upgrade.tmp') or die "clear temporary marker: $!"; + } + $root->write('/config-calls', ''); + for my $service (qw(installservice udpservice mainservice)) { + $root->write("/tmp/xcat/$service.pid", "$service\n"); + } + my $fresh = $case eq 'fresh-retry' || $remove_after_failure; + if ($remove_after_failure) { + succeeds('remove the failed transaction', $root->run('dpkg', '--force-depends', + $case eq 'failed-purge' ? '--purge' : '--remove', 'xcat')); + succeeds('reinstall after removal', $root->install_deb($deb)); + } elsif ($case =~ /reinstall|abort|legacy-return|removed-fresh/) { + succeeds('retry the package transaction', $root->install_deb($deb)); + } else { + succeeds('retry configuration through dpkg', + $root->run('dpkg', '--force-depends', '--configure', 'xcat')); + } + is($root->read('/config-calls'), $fresh ? "-i\n" : "-u -V\n", + 'configure retry retains context and a new transaction follows dpkg mode'); + for my $service (qw(installservice udpservice mainservice)) { + my $directory = $fresh ? '/tmp/xcat' : '/var/run/xcat'; + my $file = "$directory/$service.pid"; + is(-f $root->path($file) ? $root->read($file) : undef, + "$service\n", 'PID relocation follows the recovered mode'); + } + ok(!-e $root->path('/var/lib/xcat/configure-state'), 'successful configuration clears persistent transaction state'); + ok(!-e $root->path('/tmp/xCAT_upgrade.tmp'), 'successful configuration clears the legacy marker'); + succeeds('the package is configured', $root->run('/bin/sh', '-c', + q{test "$(dpkg-query -W -f='${Status}' xcat)" = 'install ok installed'})); + }; +} + +for my $case (qw(unpacked-reinstall unpacked-abort legacy-unpacked-reinstall upgrade-unpacked-marker-loss)) { + subtest $case => sub { + my $root = management_root(); + my $upgrade = $case eq 'upgrade-unpacked-marker-loss'; + succeeds('configure the package before an unpacked upgrade', $root->install_deb($deb)) if $upgrade; + $root->write('/config-calls', ''); + local $root->{deb} = $case eq 'legacy-unpacked-reinstall' ? "$fault/legacy.deb" : $deb; + succeeds('unpack without configuring the package', + $root->run('dpkg', '--force-depends', '--unpack', '/package.deb')); + is($root->read('/config-calls'), '', 'unpack does not run configuration'); + if ($upgrade) { + unlink $root->path('/tmp/xCAT_upgrade.tmp') or die "clear temporary marker: $!"; + } + if ($case eq 'unpacked-abort') { + my ($status, $out, $err) = $root->install_deb("$fault/failure.deb"); + isnt($status, 0, 'an unpacked retry can fail'); + like($err, qr/pre-installation script.*exit status 17/, 'the retry fails at the intended preinst'); + } + for my $service (qw(installservice udpservice mainservice)) { + $root->write("/tmp/xcat/$service.pid", "$service\n"); + } + if ($case eq 'unpacked-abort') { + succeeds('configure after the aborted unpacked retry', + $root->run('dpkg', '--force-depends', '--configure', 'xcat')); + } else { + succeeds('repeat the unpacked transaction and configure', $root->install_deb($deb)); + } + is($root->read('/config-calls'), $upgrade ? "-u -V\n" : "-i\n", + 'never-configured packages stay fresh and unpacked upgrades retain context'); + for my $service (qw(installservice udpservice mainservice)) { + my $directory = $upgrade ? '/var/run/xcat' : '/tmp/xcat'; + my $file = "$directory/$service.pid"; + is(-f $root->path($file) ? $root->read($file) : undef, + "$service\n", 'PID relocation follows the pending configuration'); + } + ok(!-e $root->path('/var/lib/xcat/configure-state'), 'configuration clears persistent transaction state'); + ok(!-e $root->path('/tmp/xCAT_upgrade.tmp'), 'configuration clears the legacy marker'); + }; +} + +for my $parent_mode (undef, oct('750')) { + subtest defined $parent_mode ? 'existing state parent' : 'new state parent' => sub { + my $root = XCAT::Test::Lifecycle->new; + if (defined $parent_mode) { + $root->write('/var/lib/xcat/retained', 'unrelated state'); + chmod $parent_mode, $root->path('/var/lib/xcat') or die "chmod parent: $!"; + } + local $root->{deb} = $deb; + succeeds('unpack the management control scripts', $root->run('dpkg-deb', '-e', '/package.deb', '/tmp/control')); + succeeds('record a fresh transaction with a normal umask', $root->run('/bin/sh', '-c', + 'umask 022; /bin/sh /tmp/control/preinst install')); + is((stat($root->path('/var/lib/xcat')))[2] & oct('7777'), $parent_mode // oct('755'), + 'the shared parent retains its intended permissions'); + is((stat($root->path('/var/lib/xcat/configure-state')))[2] & oct('7777'), oct('700'), + 'transaction directory is private'); + is((stat($root->path('/var/lib/xcat/configure-state/context')))[2] & oct('7777'), oct('600'), + 'transaction context is private'); + $root->write('/var/lib/xcat/configure-state/context', "invalid\n"); + my ($status, $out, $err) = $root->deb_script($deb, 'postinst', 'configure', '2.0'); + isnt($status, 0, 'invalid context stops configuration'); + like($err, qr{Invalid xCAT configuration context in /var/lib/xcat/configure-state/context}, + 'the diagnostic identifies the invalid file'); + $root->write('/tmp/xCAT_upgrade.tmp', ''); + succeeds('a new upgrade replaces stale context', $root->deb_script($deb, 'preinst', 'upgrade', '2.0')); + }; +} + +done_testing; 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 108/129] 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 109/129] 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 f5a029c4481290f0fde6c05a966911403f36c87a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:33:55 -0300 Subject: [PATCH 110/129] test(xcat-core): assert openSUSE builds and installs without legacy Genesis Nothing holds the openSUSE Genesis scope down. xCAT-genesis-base is built for every target the dep pipeline names, and xCAT-genesis-scripts requires the payload on every family. The test reads the build-plan decision and the payload requirement in the spec. It fails on this commit: the build plan keeps xCAT-genesis-base for openSUSE, and the requirement carries no condition. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/opensuse_no_legacy_genesis.t | 75 +++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 xCAT-test/unit/opensuse_no_legacy_genesis.t diff --git a/xCAT-test/unit/opensuse_no_legacy_genesis.t b/xCAT-test/unit/opensuse_no_legacy_genesis.t new file mode 100644 index 0000000000..0447d49bbc --- /dev/null +++ b/xCAT-test/unit/opensuse_no_legacy_genesis.t @@ -0,0 +1,75 @@ +#!/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 (); + +# openSUSE ships no legacy Genesis. Operator decision, 2026-10-22, the same decision taken for +# openEuler on 2026-10-01. +# +# Two artifacts carry it. The build plan decides the (package, target) pairs buildrpms.pl +# builds, and xCAT-genesis-scripts carries the payload requirement that makes an install fail +# when the payload is absent. +# +# Measured 2026-10-22: sles/devel/xcat-dep has no common/ tree (repomd.xml 404, against 200 for +# the EL one), so no OpenEmbedded payload is published for the family either. Nothing in the +# openSUSE graph can satisfy the payload name. +my @opensuse_targets = qw( + opensuse-leap-15.6-x86_64 + opensuse-leap-42.3-x86_64 + opensuse-leap-15.6-ppc64le +); +my @payload_targets = qw( + alma+epel-8-x86_64 + alma+epel-9-x86_64 + alma+epel-10-x86_64 + alma+epel-10-ppc64le + openeuler-22.03sp4-x86_64 +); + +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 (@opensuse_targets) { + ok($decides->('xCAT-genesis-base', $target), + "xCAT-genesis-base is not built for $target"); + } + + foreach my $target (@payload_targets) { + is($decides->('xCAT-genesis-base', $target), undef, + "xCAT-genesis-base is built for $target"); + } + + # The gate names one package. openSUSE keeps every other package, including the scripts + # half of Genesis: xCAT requires it, and dropping it would be a second decision. + foreach my $pkg (qw(perl-xCAT xCAT xCATsn xCAT-client xCAT-server xCAT-probe + xCAT-genesis-scripts xCAT-test xCAT-release)) { + is($decides->($pkg, 'opensuse-leap-15.6-x86_64'), undef, + "$pkg is built for openSUSE"); + } +} + +# zypper install xCAT reaches this requirement through xCAT-genesis-scripts. An openSUSE core +# that states it cannot install at all, because no repository the family reads carries the +# payload. +my $root = "$FindBin::Bin/../.."; +my @lines = read_lines("$root/xCAT-genesis-scripts/xCAT-genesis-scripts.spec"); +my ($index) = grep { + $lines[$_] =~ /^Requires:\s*xCAT-genesis-base-%\{tarch\}\s*>=\s*2:2\.18\.0\s*$/ +} 0 .. $#lines; +ok(defined $index, 'xCAT-genesis-scripts requires the legacy Genesis payload'); + +my $if = defined $index ? $lines[$index - 1] : ''; +like($if, qr/^%if\b/, '... behind a condition'); +like($if, qr/\Q0%{?suse_version}\E/, '... that reads suse_version'); +like($if, qr/^%if\s*!/, '... and excludes openSUSE rather than selecting it'); + +done_testing(); From c9ec8b427966159849a42a964cb22b328af61478 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:44:31 -0300 Subject: [PATCH 111/129] fix(xcat-core): openSUSE builds a Genesis payload its manifest cannot describe xcat-dep-build-opensuse15-x86_64 fails its xCAT-genesis-base step. BuildRequires resolve, and verify-genesis-payload then reports 566 missing zoneinfo/posix paths, etc/redhat-release, and 45 EL paths and tool names -- net-tools-deprecated, kmod-compat, iputils, systemd-sysvinit, timezone, nc, mkdosfs and the lvm symlinks. The manifest is written for EL, so the package cannot be built on openSUSE. openSUSE ships no legacy Genesis, so it does not need to be. package_skip_reason names the pairs a target does not build and why, buildrpms.pl prints each skipped pair, and a plan that skips everything returns 0 rather than failing: the dep pipeline asks for xCAT-genesis-base alone, so on openSUSE its whole plan is empty and an empty plan is the plan. Dropping the package alone would make xCAT unresolvable there. xCAT-genesis-scripts.spec requires xCAT-genesis-base-%{tarch} unconditionally and xCAT requires xCAT-genesis-scripts, so zypper install xCAT would fail on a missing package -- later than the build and looking like something else. That Requires now stands behind %if ! 0%{?suse_version}; the Leap chroot's /usr/lib/rpm/suse/macros sets %suse_version 1500, and no EL or openEuler target defines it. xCAT-test/unit/opensuse_no_legacy_genesis.t covers the skip, the empty plan and the conditional Requires. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- build-utils/lib/XCAT/BuildUtils.pm | 27 +++++++++++++++++++ buildrpms.pl | 14 +++++++++- .../xCAT-genesis-scripts.spec | 7 +++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/build-utils/lib/XCAT/BuildUtils.pm b/build-utils/lib/XCAT/BuildUtils.pm index c5268a109c..684231c62d 100644 --- a/build-utils/lib/XCAT/BuildUtils.pm +++ b/build-utils/lib/XCAT/BuildUtils.pm @@ -49,6 +49,7 @@ our @EXPORT_OK = qw( genesis_log_errors genesis_log_deny_rules deb_belongs_to_dist genesis_dists genesis_dist_reason fips_policy_artifacts fips_policy_plan sync_fips_policy + package_skip_reason ); # Both builders echo the commands they run under --verbose. Set once, after @@ -806,6 +807,32 @@ sub cancel_build { sub DESTROY { shift->release } } +# The packages a target does not build, and why. Each rule names the package and +# the target-name prefixes that do not build it. +# +# openSUSE ships no legacy Genesis. Operator decision, 2026-10-22. The payload manifest +# verify-genesis-payload checks is written for EL: on opensuse-leap-15.6-x86_64 it reports 566 +# missing zoneinfo/posix paths, etc/redhat-release and 45 EL paths and tool names, so the package +# cannot be built there and under that decision does not need to be. +my @PACKAGE_SKIPS = ( + { package => 'xCAT-genesis-base', + prefixes => ['opensuse-'], + reason => 'openSUSE ships no legacy Genesis', + }, +); + +# Why $pkg is not built for $target, or undef when the pair is built. +sub package_skip_reason { + my ($pkg, $target) = @_; + return undef unless defined($pkg) && defined($target); + for my $skip (@PACKAGE_SKIPS) { + next unless $pkg eq $skip->{package}; + return $skip->{reason} + if grep { index($target, $_) == 0 } @{ $skip->{prefixes} }; + } + return undef; +} + sub openeuler_build_target { my ($os, $arch) = @_; return undef unless lc($os->{ID} // '') eq 'openeuler'; diff --git a/buildrpms.pl b/buildrpms.pl index 3cdec4d62e..5ad53288aa 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); @@ -1027,7 +1028,18 @@ 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; + } + # An empty plan is the plan, not a failure. The dep pipeline asks for + # xCAT-genesis-base alone, and no openSUSE target builds it. + if (!@rpms) { + print "Nothing to build: every requested package is out of scope for the" + . " requested targets\n"; + return; + } 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-genesis-scripts/xCAT-genesis-scripts.spec b/xCAT-genesis-scripts/xCAT-genesis-scripts.spec index 6ec302e6fb..629b66785e 100644 --- a/xCAT-genesis-scripts/xCAT-genesis-scripts.spec +++ b/xCAT-genesis-scripts/xCAT-genesis-scripts.spec @@ -48,7 +48,14 @@ Source1: xCAT-genesis-scripts.tar.bz2 # so floor it at the 2.18.0 baseline: any 2.18.0-or-newer genesis-base snap satisfies it, # and core version bumps no longer force a genesis-base re-publish. (RPM ignores release # when the dependency omits it.) +# +# openSUSE is excluded. Operator decision, 2026-10-22: openSUSE ships no legacy Genesis, so +# no openSUSE target builds xCAT-genesis-base. No OpenEmbedded payload is published for the +# family either, so nothing an openSUSE management node reads can satisfy this name, and +# stating it stops zypper install xCAT. +%if ! 0%{?suse_version} Requires: xCAT-genesis-base-%{tarch} >= 2:2.18.0 +%endif Buildroot: %{_localstatedir}/tmp/xCAT-genesis Packager: IBM Corp. 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 112/129] 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 113/129] 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 169f3d54eb4de9e78cc7b30e4561b16bac501084 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:11:35 -0300 Subject: [PATCH 114/129] fix(grub2): give aarch64 nodes a boot file name ending in .efi Some aarch64 UEFI firmware ignores a DHCP boot file name that does not end in .efi and requests grubaa64.efi from the TFTP root instead. xCAT names grub2-, so these nodes stop with a TFTP error before grub2 runs. For an aarch64 node, nodeset now links grub2-.efi to grub2.aarch64 beside grub2-. Both DHCP backends name the .efi link once it exists in the node's TFTP directory (noderes.tftpdir, or the site one). A node set by an older xCAT keeps grub2- until its next nodeset, so makedhcp after an upgrade does not name a missing file. With site.sharedtftp off, every server that runs nodeset for the node creates both links. This relies on service nodes running the same xCAT version as the management node, which xCAT requires. The old link stays for DHCP configurations that makedhcp did not write. The boot and offline states remove both links. Other architectures keep grub2-. --- perl-xCAT/xCAT/DHCP/BootPolicy.pm | 15 +++++++++++++++ xCAT-server/lib/xcat/plugins/dhcp.pm | 14 +++++++++----- xCAT-server/lib/xcat/plugins/grub2.pm | 16 ++++++++++++---- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/perl-xCAT/xCAT/DHCP/BootPolicy.pm b/perl-xCAT/xCAT/DHCP/BootPolicy.pm index bf47dbb4f1..3d730ab155 100644 --- a/perl-xCAT/xCAT/DHCP/BootPolicy.pm +++ b/perl-xCAT/xCAT/DHCP/BootPolicy.pm @@ -890,6 +890,21 @@ sub x86_san_loader_present { return ( -f "$tftpdir/undionly.kpxe" || -f "$tftpdir/$loader->{bios}" ) ? 1 : 0; } +# Some aarch64 UEFI firmware ignores a boot file name without the .efi suffix and requests grubaa64.efi. +my %GRUB2_NODE_LOADER_SUFFIX = ( aarch64 => '.efi' ); + +# The file in boot/grub2 that DHCP names as the boot file of a grub2 node. With tftpdir, the name is +# grub2- until nodeset creates the suffixed link there: a node set by an older xCAT has only that. +sub grub2_node_loader { + my ( $class, %opts ) = @_; + + my $loader = "grub2-$opts{node}"; + my $suffix = $GRUB2_NODE_LOADER_SUFFIX{ $opts{arch} // '' } // ''; + return $loader if $suffix eq ''; + return $loader if defined $opts{tftpdir} && !-e "$opts{tftpdir}/boot/grub2/$loader$suffix"; + return "$loader$suffix"; +} + # The ISC host statements that choose the boot file of a node with netboot ipxe, xnba or pxe. They # reach dhcpd through omshell, so their quotes are escaped. sub isc_node_boot_statements { diff --git a/xCAT-server/lib/xcat/plugins/dhcp.pm b/xCAT-server/lib/xcat/plugins/dhcp.pm index 5ab5d04a41..815dcf2dc9 100644 --- a/xCAT-server/lib/xcat/plugins/dhcp.pm +++ b/xCAT-server/lib/xcat/plugins/dhcp.pm @@ -1251,7 +1251,9 @@ sub addnode } elsif ($nrent and $nrent->{netboot} and $nrent->{netboot} eq 'yaboot') { $lstatements = 'filename = \"/yb/node/yaboot-' . $node . '\";' . $lstatements; } elsif ($nrent and $nrent->{netboot} and $nrent->{netboot} =~ /^grub2[-]?.*$/) { - $lstatements = 'filename = \"/boot/grub2/grub2-' . $node . '\";' . $lstatements; + my $loader = xCAT::DHCP::BootPolicy->grub2_node_loader(node => $node, arch => $ntent && $ntent->{arch}, + tftpdir => ($nrent->{tftpdir} || $tftpdir)); + $lstatements = 'filename = \"/boot/grub2/' . $loader . '\";' . $lstatements; } elsif ($nrent and $nrent->{netboot} and $nrent->{netboot} eq 'petitboot') { $lstatements = 'option conf-file \"http://' . $nxtsrv . $portsuffix . '/tftpboot/petitboot/' . $node . '\";' . $lstatements; } elsif ($nrent and $nrent->{netboot} and $nrent->{netboot} eq 'onie') { @@ -2621,11 +2623,11 @@ sub process_request } else { $chainents = undef; } - $nrhash = $nrtab->getNodesAttribs($req->{node}, [ 'tftpserver', 'netboot', 'proxydhcp', 'xcatmaster', 'servicenode']); + $nrhash = $nrtab->getNodesAttribs($req->{node}, [ 'tftpserver', 'netboot', 'proxydhcp', 'xcatmaster', 'servicenode', 'tftpdir']); my $nodetypetab; $nodetypetab = xCAT::Table->new('nodetype', -create => 0); if ($nodetypetab) { - $nodetypeents = $nodetypetab->getNodesAttribs($req->{node}, [qw(os provmethod)]); + $nodetypeents = $nodetypetab->getNodesAttribs($req->{node}, [qw(os provmethod arch)]); } my $iscsitab = xCAT::Table->new('iscsi', -create => 0); if ($iscsitab) { @@ -3708,7 +3710,7 @@ sub kea_build_node_reservations my $mactab = xCAT::Table->new('mac'); $chainents = $chaintab ? $chaintab->getNodesAttribs($nodes, ['currstate']) : undef; - $nrhash = $nrtab->getNodesAttribs($nodes, [ 'tftpserver', 'netboot', 'proxydhcp', 'xcatmaster', 'servicenode' ]); + $nrhash = $nrtab->getNodesAttribs($nodes, [ 'tftpserver', 'netboot', 'proxydhcp', 'xcatmaster', 'servicenode', 'tftpdir' ]); $nodetypeents = $nodetypetab ? $nodetypetab->getNodesAttribs($nodes, [qw(os provmethod arch)]) : undef; $iscsients = $iscsitab ? $iscsitab->getNodesAttribs($nodes, [qw(server target lun iname)]) : undef; $machash = $mactab ? $mactab->getNodesAttribs($nodes, ['mac']) : undef; @@ -4408,7 +4410,9 @@ sub kea_boot_for_node } elsif ($netboot and $netboot eq 'yaboot') { $boot{'boot-file-name'} = "/yb/node/yaboot-$node"; } elsif ($netboot and $netboot =~ /^grub2[-]?.*$/) { - $boot{'boot-file-name'} = "/boot/grub2/grub2-$node"; + $boot{'boot-file-name'} = '/boot/grub2/' + . xCAT::DHCP::BootPolicy->grub2_node_loader( node => $node, arch => $ntent && $ntent->{arch}, + tftpdir => ( $nrent->{tftpdir} || $tftpdir ) ); } elsif ($netboot and $netboot eq 'nimol') { $boot{'boot-file-name'} = "/vios/nodes/$node"; } elsif ($netboot and $netboot eq 'petitboot') { diff --git a/xCAT-server/lib/xcat/plugins/grub2.pm b/xCAT-server/lib/xcat/plugins/grub2.pm index 17e48e3b4d..ba048ff348 100644 --- a/xCAT-server/lib/xcat/plugins/grub2.pm +++ b/xCAT-server/lib/xcat/plugins/grub2.pm @@ -5,6 +5,7 @@ use Sys::Syslog; use xCAT::Scope; use xCAT::Utils; use xCAT::TableUtils; +use xCAT::DHCP::BootPolicy; use xCAT::ServiceNodeUtils; use xCAT::NetworkUtils; use xCAT::MsgUtils; @@ -311,9 +312,14 @@ sub setstate { return (1, "Stop grub2 configuration for this node, \"$grub2bin\" does not exits."); } + # grub2- stays for DHCP configurations that makedhcp did not write. + my @loaders = ("grub2-$node"); + my $dhcp_loader = xCAT::DHCP::BootPolicy->grub2_node_loader(node => $node, arch => $nodearch); + push @loaders, $dhcp_loader if ($dhcp_loader ne $loaders[0]); + chdir("$bootloader_root"); if ($cref->{currstate} eq "offline" or $cref->{currstate} eq "boot") { - unlink("grub2-$node"); + unlink(@loaders); } elsif ($cref->{currstate} eq "standby" and $nodeos =~ /^sle/i) { my $os_version = $nodeos; $os_version =~ s/sles//i; # Strip sles if there @@ -321,10 +327,12 @@ sub setstate { if ($os_version >= "15") { # Make sure for SLES15 or higher can still boot # from disk in "standby" state - unlink("grub2-$node"); + unlink(@loaders); + } + } else { + foreach my $loader (grep { !-e $_ } @loaders) { + symlink("grub2." . $nodearch, $loader); } - } elsif (! -e "grub2-$node") { - symlink("grub2." . $nodearch, "grub2-$node"); } my $ip = xCAT::NetworkUtils->getipaddr($node); From 8bb6f4ef91bdee143219166482192879aeef1665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:15:53 -0300 Subject: [PATCH 115/129] test(grub2): cover the aarch64 boot file name and node loader links Drive the Kea reservation builder and the ISC makedhcp path for grub2 nodes of each architecture. Place the loader links in the site TFTP directory or in noderes.tftpdir. An aarch64 node with only grub2- keeps that name. The table stub returns only the requested columns, so a missing nodetype.arch or noderes.tftpdir read fails the aarch64 cases. Drive grub2 setstate for the node loader links: both names for an aarch64 node and one for the others. Cover a repeated nodeset, a node with only the old link, and removal in the boot, offline and SLES 15 standby states. --- xCAT-test/unit/dhcp_grub2_node_loader.t | 209 +++++++++++++++++++++++ xCAT-test/unit/grub2_node_loader_links.t | 110 ++++++++++++ 2 files changed, 319 insertions(+) create mode 100644 xCAT-test/unit/dhcp_grub2_node_loader.t create mode 100644 xCAT-test/unit/grub2_node_loader_links.t diff --git a/xCAT-test/unit/dhcp_grub2_node_loader.t b/xCAT-test/unit/dhcp_grub2_node_loader.t new file mode 100644 index 0000000000..01f389cd67 --- /dev/null +++ b/xCAT-test/unit/dhcp_grub2_node_loader.t @@ -0,0 +1,209 @@ +#!/usr/bin/env perl +# The boot file both DHCP backends name for a grub2 node. An aarch64 node gets a name that ends in +# .efi once nodeset has created it: some aarch64 UEFI firmware ignores any other name and requests +# grubaa64.efi instead. +use strict; +use warnings; +## no critic (TestingAndDebugging::ProhibitNoWarnings) +no warnings 'once'; + +use FindBin; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../xCAT-server/lib"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use lib "$FindBin::Bin/../../perl-xCAT"; + +use File::Path qw(make_path); +use File::Temp qw(tempdir); +use Test::More; +use XCAT::Test::File qw(repo_path); + +BEGIN { + $ENV{XCATROOT} = repo_path('xCAT-server'); + $ENV{XCATCFG} = 'SQLite:' . tempdir( CLEANUP => 1 ); +} + +use xCAT::DHCP::BootPolicy; +use xCAT::TableUtils; + +# dhcp.pm reads the site TFTP directory once, when it loads. noderes.tftpdir moves one node elsewhere. +my $site_tftp = tempdir( CLEANUP => 1 ); +my $node_tftp = tempdir( CLEANUP => 1 ); +{ + no warnings 'redefine'; + *xCAT::TableUtils::getTftpDir = sub { return $site_tftp; }; +} +require( repo_path('xCAT-server/lib/xcat/plugins/dhcp.pm') ); + +for my $dir ( $site_tftp, $node_tftp ) { + make_path("$dir/boot/grub2"); + open( my $loader, '>', "$dir/boot/grub2/grub2.aarch64" ) or die "Cannot create the loader: $!"; + close($loader) or die "Cannot close the loader: $!"; +} + +# The node loader links in a TFTP directory, as a nodeset left them. +sub publish { + my ( $dir, @names ) = @_; + unlink( glob("$dir/boot/grub2/grub2-cn1*") ); + for my $name (@names) { + symlink( 'grub2.aarch64', "$dir/boot/grub2/$name" ) or die "Cannot create $dir/boot/grub2/$name: $!"; + } + return; +} + +# A table returns only the columns the plugin asks for, like the real one. +{ + package GrubLoaderTable; + + our %rows; + sub new { my ( $class, $name ) = @_; return bless { name => $name }, $class; } + + sub getNodesAttribs { + my ( $self, $nodes, $cols ) = @_; + my %out; + for my $node (@$nodes) { + my $row = $rows{ $self->{name} }{$node} or next; + $out{$node} = [ { map { exists $row->{$_} ? ( $_ => $row->{$_} ) : () } @$cols } ]; + } + return \%out; + } + sub getNodeAttribs { return; } + sub getAllAttribs { return; } + sub getAttribs { return { username => 'xcat_key', password => 'dGVzdA==' }; } + sub close { return; } + + package GrubLoaderISCBackend; + sub name { return 'isc'; } + + package GrubLoaderKeaBackend; + sub subnet_id_for_ip { return 1; } +} + +sub node_rows { + my ( $arch, $netboot, $tftpdir ) = @_; + return ( + noderes => { cn1 => { netboot => $netboot, tftpserver => '192.0.2.1', ( $tftpdir ? ( tftpdir => $tftpdir ) : () ) } }, + chain => { cn1 => { currstate => 'install' } }, + mac => { cn1 => { mac => '02:00:00:00:00:11' } }, + nodetype => { cn1 => { os => 'rhels9.4', provmethod => 'install', ( defined $arch ? ( arch => $arch ) : () ) } }, + ); +} + +my @errors; +no warnings 'redefine'; +local *xCAT::Table::new = sub { return GrubLoaderTable->new( $_[1] ); }; +local *xCAT::TableUtils::get_site_attribute = sub { return; }; +local *xCAT::MsgUtils::trace = sub { return; }; +local *xCAT_plugin::dhcp::getipaddr = sub { return '192.0.2.11'; }; +local *xCAT::NetworkUtils::getipaddr = sub { return '192.0.2.11'; }; +local *xCAT_plugin::dhcp::ipIsDynamic = sub { return 0; }; +local $xCAT_plugin::dhcp::callback = sub { push @errors, @{ $_[0]->{error} || [] }; }; +use warnings 'redefine'; + +# The boot file of the reservation the Kea backend builds for cn1. +sub kea_boot_file { + my ( $arch, $netboot, $tftpdir ) = @_; + local %GrubLoaderTable::rows = node_rows( $arch, $netboot, $tftpdir ); + my $reservations = xCAT_plugin::dhcp::kea_build_node_reservations( bless( {}, 'GrubLoaderKeaBackend' ), {}, ['cn1'] ); + return [ map { $_->{'boot-file-name'} } @$reservations ]; +} + +my $dir = tempdir( CLEANUP => 1 ); +my $conf = "$dir/dhcpd.conf"; +open( my $fh, '>', $conf ) or die "Cannot create $conf: $!"; +print {$fh} "#xCAT generated dhcp configuration\n", + "option space gpxe;\n", + @{ xCAT::DHCP::BootPolicy->isc_ipxe_feature_option_lines() }, + "subnet 192.0.2.0 netmask 255.255.255.0 {\n", + "} # 192.0.2.0/255.255.255.0 subnet_end\n"; +close($fh) or die "Cannot close $conf: $!"; + +# The boot file of every host that makedhcp creates for cn1 through OMAPI. +sub isc_boot_files { + my ( $arch, $netboot, $tftpdir ) = @_; + local %GrubLoaderTable::rows = node_rows( $arch, $netboot, $tftpdir ); + my $commands = ''; + no warnings 'redefine'; + local *xCAT::DHCP::Backend::new_backend = sub { return bless {}, 'GrubLoaderISCBackend'; }; + local *xCAT::Utils::isServiceNode = sub { return 0; }; + local *xCAT::Utils::isLinux = sub { return 1; }; + local *xCAT::Utils::isFIPS = sub { return 0; }; + local *xCAT::Utils::checkservicestatus = sub { return 0; }; + local *xCAT::NetworkUtils::determinehostname = sub { return ('mn'); }; + local *xCAT::NetworkUtils::nodeonmynet = sub { return 1; }; + local *xCAT::DBobjUtils::getnodetype = sub { return {}; }; + local *xCAT::DBobjUtils::getNetwkInfo = sub { return ( cn1 => { mgtifname => 'eth0' } ); }; + local *xCAT_plugin::dhcp::addnic = sub { return; }; + local *xCAT_plugin::dhcp::addnet = sub { return; }; + local *xCAT_plugin::dhcp::addnet6 = sub { return; }; + local *xCAT_plugin::dhcp::writeout = sub { return; }; + local *xCAT_plugin::dhcp::_open_omshell_writer = sub { + open( my $out, '>', \$commands ) or die "Cannot open an omshell buffer: $!"; + return $out; + }; + local *xCAT_plugin::dhcp::_close_omshell_writer = sub { return; }; + local $::XCATSITEVALS{externaldhcpservers}; + local $xCAT_plugin::dhcp::dhcpconffile = $conf; + local $xCAT_plugin::dhcp::distro = 'rhels9.4'; + use warnings 'redefine'; + + open( my $printed, '>', \my $text ) or die "Cannot open an output buffer: $!"; + my $selected = select($printed); + my $died; + eval { + xCAT_plugin::dhcp::process_request( { _xcatpreprocessed => [1], node => ['cn1'], arg => [] }, + sub { push @errors, @{ $_[0]->{error} || [] }; } ); + 1; + } or $died = $@; + select($selected); + die "makedhcp died: $died" if $died; + + return [ map { /filename = \\"([^\\"]*)\\"/g } $commands =~ /^set statements = "(.*)"$/mg ]; +} + +my @both = qw(grub2-cn1 grub2-cn1.efi); +my @old = qw(grub2-cn1); + +# Architecture, links in the site TFTP directory, links in the node's own one (none: no noderes.tftpdir), +# the boot file DHCP names, and the case. +my @cases = ( + [ 'aarch64', \@both, undef, '/boot/grub2/grub2-cn1.efi', 'after nodeset' ], + [ 'aarch64', \@old, undef, '/boot/grub2/grub2-cn1', 'set by an older nodeset' ], + [ 'aarch64', [], undef, '/boot/grub2/grub2-cn1', 'without loader links' ], + [ 'aarch64', \@old, \@both, '/boot/grub2/grub2-cn1.efi', 'after nodeset in its own TFTP directory' ], + [ 'aarch64', \@both, \@old, '/boot/grub2/grub2-cn1', 'set by an older nodeset in its own TFTP directory' ], + [ 'x86_64', \@old, undef, '/boot/grub2/grub2-cn1', 'after nodeset' ], + [ 'x86_64', \@both, undef, '/boot/grub2/grub2-cn1', 'with a stray .efi link' ], + [ 'riscv64', \@old, undef, '/boot/grub2/grub2-cn1', 'after nodeset' ], + [ 'ppc64', \@old, undef, '/boot/grub2/grub2-cn1', 'after nodeset' ], + [ 'ppc64le', \@old, undef, '/boot/grub2/grub2-cn1', 'after nodeset' ], + [ '', \@both, undef, '/boot/grub2/grub2-cn1', 'with a .efi link' ], + [ undef, \@both, undef, '/boot/grub2/grub2-cn1', 'with a .efi link' ], +); + +for my $case (@cases) { + my ( $arch, $site_links, $node_links, $expected, $state ) = @$case; + my $label = ( defined $arch ? ( $arch eq '' ? 'a blank arch' : $arch ) : 'no arch' ) . " $state"; + publish( $site_tftp, @$site_links ); + publish( $node_tftp, @{ $node_links || [] } ); + my $tftpdir = $node_links ? $node_tftp : undef; + + for my $netboot (qw(grub2 grub2-tftp grub2-http)) { + @errors = (); + is_deeply( kea_boot_file( $arch, $netboot, $tftpdir ), [$expected], "Kea: $netboot node with $label" ) + or diag("errors: @errors"); + } + @errors = (); + is_deeply( isc_boot_files( $arch, 'grub2', $tftpdir ), [$expected], "ISC: grub2 node with $label" ) + or diag("errors: @errors"); +} + +publish( $site_tftp, @both ); +is( xCAT_plugin::dhcp::kea_boot_for_node( 'cn1', { netboot => 'grub2' }, undef, undef, undef, '192.0.2.1' )->{'boot-file-name'}, + '/boot/grub2/grub2-cn1', 'Kea: grub2 node without a nodetype entry' ); +is( xCAT_plugin::dhcp::kea_boot_for_node( + 'cn1', { netboot => 'grub2' }, { currstate => 'boot' }, { arch => 'aarch64' }, undef, '192.0.2.1' + )->{'boot-file-name'}, + '', 'Kea: aarch64 grub2 node in boot state still gets no boot file' ); + +done_testing(); diff --git a/xCAT-test/unit/grub2_node_loader_links.t b/xCAT-test/unit/grub2_node_loader_links.t new file mode 100644 index 0000000000..6572d979e4 --- /dev/null +++ b/xCAT-test/unit/grub2_node_loader_links.t @@ -0,0 +1,110 @@ +#!/usr/bin/env perl +# The per-node loader links nodeset publishes in boot/grub2. An aarch64 node also gets +# grub2-.efi, the name DHCP hands it, and grub2- stays for DHCP that makedhcp did not write. +use strict; +use warnings; +no warnings 'once'; + +use Cwd qw(getcwd); +use File::Path qw(make_path); +use File::Slurper qw(write_text); +use File::Temp qw(tempdir); +use FindBin; +use Test::More; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use XCAT::Test::File qw(repo_path); + +my $root = tempdir(CLEANUP => 1); +local $ENV{XCATROOT} = repo_path('xCAT-server'); +local $ENV{XCATCFG} = "$root/config"; +make_path($ENV{XCATCFG}); +local %::XCATSITEVALS = (tftpdir => "$root/tftpboot", xcatdebugmode => 0); +require xCAT::Table; +require xCAT::NetworkUtils; + +no warnings 'redefine'; +local *xCAT::Table::new = sub { die 'Unexpected database access'; }; +local *xCAT::NetworkUtils::getipaddr = sub { + my ($class, $host) = @_; + return '192.0.2.1' if $host eq 'server'; + return '192.0.2.2' if $host eq 'node'; + die "Unexpected hostname: $host"; +}; +use warnings 'redefine'; + +require(repo_path('xCAT-server/lib/xcat/plugins/grub2.pm')); + +sub new_bootdir { + my ($arch) = @_; + my $tftpdir = tempdir(DIR => $root, CLEANUP => 1); + make_path("$tftpdir/boot/grub2"); + write_text("$tftpdir/boot/grub2/grub2.$arch", "fixture loader\n"); + return $tftpdir; +} + +sub nodeset { + my ($tftpdir, $arch, $currstate, $os) = @_; + my $cwd = getcwd(); + my @result = xCAT_plugin::grub2::setstate( + 'node', + {node => [{kernel => 'images/vmlinuz', initrd => 'images/initrd.img', kcmdline => 'quiet'}]}, + {node => [{currstate => $currstate}]}, + {node => [{mac => '02:00:00:00:00:02'}]}, + $tftpdir, {node => [{tftpserver => 'server', netboot => 'grub2'}]}, {}, $arch, $os // 'rhels9.4', + ); + chdir($cwd) or die "Cannot restore working directory: $!"; + is_deeply(\@result, [0, ''], "nodeset $currstate succeeds"); + return; +} + +sub links { + my ($tftpdir) = @_; + opendir(my $dh, "$tftpdir/boot/grub2") or die "Cannot read $tftpdir/boot/grub2: $!"; + my %links = map { $_ => readlink("$tftpdir/boot/grub2/$_") } grep { -l "$tftpdir/boot/grub2/$_" } readdir($dh); + closedir($dh); + return \%links; +} + +for my $case (['aarch64', 'aarch64'], ['x86_64', 'x86_64'], ['riscv64', 'riscv64'], ['ppc64', 'ppc']) { + my ($arch, $loader_arch) = @$case; + subtest "$arch: install" => sub { + my $tftpdir = new_bootdir($loader_arch); + nodeset($tftpdir, $arch, 'install'); + my %expected = ('grub2-node' => "grub2.$loader_arch"); + $expected{'grub2-node.efi'} = 'grub2.aarch64' if $arch eq 'aarch64'; + is_deeply(links($tftpdir), \%expected, 'the node loader links point at the architecture loader'); + + nodeset($tftpdir, $arch, 'install'); + is_deeply(links($tftpdir), \%expected, 'a second nodeset leaves the same links'); + }; +} + +subtest 'aarch64: install after an older nodeset' => sub { + my $tftpdir = new_bootdir('aarch64'); + symlink('grub2.aarch64', "$tftpdir/boot/grub2/grub2-node") or die "Cannot create the old link: $!"; + nodeset($tftpdir, 'aarch64', 'install'); + is_deeply(links($tftpdir), {'grub2-node' => 'grub2.aarch64', 'grub2-node.efi' => 'grub2.aarch64'}, + 'the .efi link is added beside the old one'); +}; + +for my $case (['boot'], ['offline'], ['standby', 'sles15.5']) { + my ($state, $os) = @$case; + subtest "aarch64: $state after install" . ($os ? " on $os" : '') => sub { + my $tftpdir = new_bootdir('aarch64'); + nodeset($tftpdir, 'aarch64', 'install', $os); + nodeset($tftpdir, 'aarch64', $state, $os); + is_deeply(links($tftpdir), {}, 'both node loader links are removed'); + }; +} + +subtest 'aarch64: standby on an older SLES keeps both links' => sub { + my $tftpdir = new_bootdir('aarch64'); + nodeset($tftpdir, 'aarch64', 'install', 'sles12.5'); + nodeset($tftpdir, 'aarch64', 'standby', 'sles12.5'); + is_deeply(links($tftpdir), {'grub2-node' => 'grub2.aarch64', 'grub2-node.efi' => 'grub2.aarch64'}, + 'the node loader links stay'); +}; + +done_testing(); 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 116/129] 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"); } } From c35aa3f9ed836a6c587d311c874f69c27fd41980 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:16:07 -0300 Subject: [PATCH 117/129] fix(build): preserve binaries in source-only runs Source-only signing modified retained binary RPMs and repository signatures while leaving the binary index unchanged. It also removed and recreated the bootstrap alias. Limit signing to the source repository in this mode and leave the existing binary alias unchanged. --- buildrpms.pl | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/buildrpms.pl b/buildrpms.pl index 95c7655691..9ac5c76758 100755 --- a/buildrpms.pl +++ b/buildrpms.pl @@ -696,7 +696,7 @@ sub index_repo { # The stable bootstrap filename is a direct-download convenience, not a # second package. Keep it out of repository metadata. - unlink $alias if -f $alias; + unlink $alias if !$opts{source_only} && -f $alias; say "Creating repository $repodir"; # Drop the top-level stray src.rpm and the mock logs (build.log/root.log/...) # that mock leaves in the resultdir, so the dir is directly deployable (upstream @@ -719,6 +719,7 @@ sub update_repo { sub write_release_alias { my ($repodir) = @_; + return if $opts{source_only}; my $alias = "$repodir/xCAT-release-latest.noarch.rpm"; # glob() returns a wildcard-free pattern verbatim even when the file does not exist, so @@ -737,14 +738,12 @@ sub sign_rpms { sign_repo_dir("dist/$target/rpms", $opts{gpg_key_name}); } -# Sign every rpm in a core repo dir -- the top-level binaries AND SRPMS/*.src.rpm -- -# then re-index (signing rewrites the rpms, invalidating checksums) and detach-sign -# + export the key into BOTH the binary and the SRPMS repodata dirs. +# Source-only runs sign and index only SRPMS; normal runs also update the binary repository. sub sign_repo_dir { my ($repodir, $key_name) = @_; say "Signing RPMs in $repodir"; - my @bin = glob("$repodir/*.rpm"); + my @bin = $opts{source_only} ? () : glob("$repodir/*.rpm"); if (@bin) { sh_or_die(qq(rpmsign --define "%_gpg_name $key_name" --addsign ) . join(" ", map { qq("$_") } @bin), @@ -760,7 +759,7 @@ sub sign_repo_dir { # Signing can change RPM bytes without changing the size or timestamp used by the metadata cache. index_repo($repodir, 1); - for my $rd ("$repodir/repodata", + for my $rd (($opts{source_only} ? () : ("$repodir/repodata")), (-d "$repodir/SRPMS/repodata" ? ("$repodir/SRPMS/repodata") : ())) { my $repomd = "$rd/repomd.xml"; next unless -f $repomd; @@ -865,10 +864,7 @@ sub merge_core_repos { "Failed to rsync '$in' into '$out'\n"); } - # Index, sign (when --gpg-sign), write the final repository metadata, then create the - # xCAT-release-latest stable bootstrap alias. The alias MUST be created AFTER the final - # metadata pass so write_release_alias can unlink it before createrepo and keep it out of - # the repository index. + # Create the bootstrap alias after the final index pass so it does not enter repository metadata. index_repo($out); if ($opts{gpg_sign}) { $ENV{GNUPGHOME} = $opts{gpg_home} if $opts{gpg_home}; @@ -1198,11 +1194,10 @@ C<--rebuild> is skipped. ./buildrpms.pl --target alma+epel-9-x86_64 --source-only The srpms land in CtargetE/rpms/SRPMS/> and that index is regenerated. -The binary metadata under CtargetE/rpms/> is deliberately left as the -last binary build wrote it: re-indexing a directory with no binaries in it would -replace working metadata with metadata for an empty repository. For the same reason -no C<.repo> file or buildinfo is emitted, since both describe an installable binary -repo that this mode does not produce. With C<--gpg-sign> the srpms are signed. +Repository finalization leaves existing binary RPMs, metadata, signatures, +public keys and the bootstrap alias unchanged. No C<.repo> file or buildinfo is +emitted, since both describe an installable binary repo that this mode does not +produce. With C<--gpg-sign>, the source RPMs and their repository metadata are signed. Cannot be combined with C<--merge-core-repos>, which assembles already-built per-arch binary trees. @@ -1311,11 +1306,13 @@ Builds all selected package/target combinations. =item 2. -Runs C for each selected target under C. +Indexes repositories for each selected target under C. With C<--source-only>, +only the SRPM repository is indexed. =item 3. If C<--gpg-sign> is set, signs RPMs and C for each target. +With C<--source-only>, only source RPMs and their repository metadata are signed. =item 4. From a289434ae801421915c2e28b0f46caf33b4cd01b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:16:08 -0300 Subject: [PATCH 118/129] test(build): cover source-only repository preservation Run the real finalization command with empty, unsigned and differently signed binary repositories, including absent and retained aliases. Check binary bytes, modes and timestamps across unsigned and repeated signed runs. Verify source package checksums and signatures with a separate source key. --- xCAT-test/native/README.md | 6 ++ xCAT-test/native/release_repository.t | 111 +++++++++++++++++++++++--- 2 files changed, 105 insertions(+), 12 deletions(-) diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index d3089e6ff3..1f072b0b33 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -63,6 +63,12 @@ they do not qualify package installation on every target architecture. On EL8, install both `python36` and `python3-rpm` to provide the interpreter and its RPM bindings. +The release case also runs source-only finalization with unsigned and signed +binary RPMs, empty binary trees, and absent, retained and standalone aliases. +It checks that binary files and aliases retain their bytes, modes and timestamps +while source RPMs and metadata use a different signing key. This covers cached +source RPMs; it does not run mock or publish a repository. + The Debian probe permission test has a separate pull-request CI step. It needs Debian build tools, BATS, bubblewrap, fakeroot, reprepro and libfile-slurper-perl. Run it as an ordinary user on a Debian or Ubuntu host diff --git a/xCAT-test/native/release_repository.t b/xCAT-test/native/release_repository.t index a1e072eb57..3e07b70bae 100644 --- a/xCAT-test/native/release_repository.t +++ b/xCAT-test/native/release_repository.t @@ -4,7 +4,8 @@ use warnings; use Digest::SHA qw(sha256_hex); use File::Basename qw(dirname); use File::Copy qw(copy); -use File::Path qw(make_path); +use File::Find qw(find); +use File::Path qw(make_path remove_tree); use File::Slurper qw(read_binary write_text); use File::Temp qw(tempdir); use FindBin; @@ -117,6 +118,73 @@ my $schedule = command("$root/work", 'unshare', '--user', '--map-root-user', '-- is(scalar(grep { $_ eq "scheduled xCAT-release-$target" } split /\n/, $schedule), 1, 'default build schedules the release package once'); +command($root, 'gpg', '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', + '--quick-generate-key', 'Source Test ', 'rsa2048', 'sign', '0'); +my $source_key = command($root, 'gpg', '--armor', '--export', 'source@example.test'); +write_text("$root/source.key", $source_key); +command($root, 'rpm', '--dbpath', "$root/source-rpmdb", '--import', "$root/source.key"); +command($root, 'gpg', '--output', "$root/source-keyring.gpg", '--export', 'source@example.test'); +for my $state (qw(empty unsigned signed no-alias alias-only)) { + subtest "source-only with $state binaries" => sub { + remove_tree($cached); + make_path("$cached/SRPMS"); + copy("$root/SRPMS/$srpm", "$cached/SRPMS/$srpm") or die $!; + if ($state ne 'empty' && $state ne 'alias-only') { + command($root, 'cp', '-a', "$root/output/.", $cached); + copy("$root/SRPMS/$srpm", "$cached/SRPMS/$srpm") or die $!; + if ($state eq 'unsigned') { + copy("$root/RPMS/noarch/$rpm", "$cached/$rpm") or die $!; + command($root, 'createrepo_c', '--excludes', 'SRPMS/*', + '--excludes', 'xCAT-release-latest.noarch.rpm', $cached); + command($root, 'gpg', '--batch', '--yes', '--armor', '--detach-sign', + '--default-key', 'package@example.test', "$cached/repodata/repomd.xml"); + } + check_package_index($cached, $rpm, 'initial binary repository'); + } + if ($state eq 'no-alias') { + unlink "$cached/xCAT-release-latest.noarch.rpm" or die $!; + } elsif ($state ne 'empty') { + # Keep an older alias to detect replacement even when the versioned RPM still exists. + copy("$root/RPMS/noarch/$rpm", "$cached/xCAT-release-latest.noarch.rpm") or die $!; + chmod 0600, "$cached/xCAT-release-latest.noarch.rpm" or die $!; + utime 1600000000, 1600000000, "$cached/xCAT-release-latest.noarch.rpm" or die $!; + } + my $before = binary_snapshot($cached); + for my $attempt (0, 1, 2) { + my $signed = $attempt > 0 ? 1 : 0; + my $label = "$state source-only signed=$signed run=$attempt"; + my ($rc, $out, $err) = run_in("$root/work", 'unshare', '--user', '--map-root-user', '--mount', + 'bash', repo_path('xCAT-test/native/fixtures/buildrpms-namespace.sh'), + 'sh', '-c', 'trap \'gpgconf --homedir "$GNUPGHOME" --kill gpg-agent\' EXIT; "$@"', + 'source-test', $^X, 'buildrpms.pl', '--package', 'xCAT-release', '--target', $target, + '--release', '1', '--nproc', '1', '--source-only', + $signed ? ('--gpg-sign', '--gpg-key-name', 'source@example.test') : ()); + unless (is($rc, 0, "$label completes")) { + diag($out, $err); + return; + } + is_deeply(binary_snapshot($cached), $before, + "$label preserves all binary file bytes, modes and mtimes"); + check_package_index("$cached/SRPMS", $srpm, $label); + if ($signed) { + my $signature = command($root, 'rpmkeys', '--dbpath', "$root/source-rpmdb", + '--checksig', "$cached/SRPMS/$srpm"); + like($signature, qr/\bsignatures OK\b/, "$label verifies the source RPM signature"); + command($root, 'gpgv', '--keyring', "$root/source-keyring.gpg", + "$cached/SRPMS/repodata/repomd.xml.asc", + "$cached/SRPMS/repodata/repomd.xml"); + is(read_binary("$cached/SRPMS/repodata/repomd.xml.key"), $source_key, + "$label exports the source signing key"); + isnt(read_binary("$cached/SRPMS/$srpm"), read_binary("$root/SRPMS/$srpm"), + "$label signs the source RPM"); + } else { + is(read_binary("$cached/SRPMS/$srpm"), read_binary("$root/SRPMS/$srpm"), + "$label leaves the source RPM unsigned"); + } + } + }; +} + unlink "$root/input/$rpm" or die $!; command("$root/work", $^X, 'buildrpms.pl', '--merge-core-repos', '--target', $target, '--release', '1', '--output-dir', "$root/output", @@ -156,6 +224,35 @@ sub package_stats { return {map { $_ => [(stat("$directory/$_"))[7, 9]] } ($rpm, "SRPMS/$srpm")}; } +sub binary_snapshot { + my ($directory) = @_; + my %files; + find({no_chdir => 1, wanted => sub { + if ($File::Find::name eq "$directory/SRPMS") { + $File::Find::prune = 1; + return; + } + return unless -f $File::Find::name; + my $relative = substr($File::Find::name, length($directory) + 1); + $files{$relative} = [sha256_hex(read_binary($File::Find::name)), (stat($File::Find::name))[2, 9]]; + }}, $directory); + return \%files; +} + +sub check_package_index { + my ($repo, $filename, $label) = @_; + my @indexed = primary_packages($repo); + is(scalar(@indexed), 1, "$label indexes one $filename"); + for my $package (@indexed) { + my ($location) = $package->findnodes('./*[local-name()="location"]'); + is($location->getAttribute('href'), $filename, "$label locates $filename"); + my ($checksum) = $package->findnodes('./*[local-name()="checksum"]'); + is($checksum->getAttribute('type'), 'sha256', "$label uses SHA256 for $filename"); + is($checksum->textContent, sha256_hex(read_binary("$repo/$filename")), + "$label metadata matches final $filename bytes"); + } +} + sub check_repository { my ($directory, $signed, $label, $before) = @_; is_deeply(package_stats($directory), $before, "$label signing preserves package sizes and mtimes") @@ -165,17 +262,7 @@ sub check_repository { is(read_binary($alias), read_binary("$directory/$rpm"), "$label alias has final RPM bytes"); is((stat($alias))[2] & 0777, 0644, "$label alias is readable"); for my $entry ([$directory, $rpm], ["$directory/SRPMS", $srpm]) { - my ($repo, $filename) = @$entry; - my @indexed = primary_packages($repo); - is(scalar(@indexed), 1, "$label indexes one $filename"); - for my $package (@indexed) { - my ($location) = $package->findnodes('./*[local-name()="location"]'); - is($location->getAttribute('href'), $filename, "$label locates $filename"); - my ($checksum) = $package->findnodes('./*[local-name()="checksum"]'); - is($checksum->getAttribute('type'), 'sha256', "$label uses SHA256 for $filename"); - is($checksum->textContent, sha256_hex(read_binary("$repo/$filename")), - "$label metadata matches final $filename bytes"); - } + check_package_index(@$entry, $label); } if ($signed) { for my $repo ($directory, "$directory/SRPMS") { From 09e277a6a11621280eeee66152f24eb9fc7818ed Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:16:02 -0300 Subject: [PATCH 119/129] fix(xcat-genesis-base): the deb ships a Genesis loader with no execute bit, so every node panics An Ubuntu node that netboots legacy Genesis dies with Failed to execute /init (error -13) Kernel panic - not syncing: No working init found. xCAT-genesis-base/debian/rules is a bare `dh $@`, so dh_fixperms applies its *.so* rule to the whole package. That is right for a Debian shared library and wrong for a netboot ROOT FILESYSTEM: the kernel execs the payload's dynamic loader, and a loader with no execute bit makes open_exec() return EACCES, so every ELF in the image fails to start. mknb copies the tree verbatim into genesis.fs..lzma, so the mode travels into the image. The pipeline's iPXE command line carries `quiet`, which hid the reason. Measured on xcat-master-ub from the installed package: 644 .../netboot/genesis/x86_64/fs/usr/lib64/ld-linux-x86-64.so.2 755 .../netboot/genesis/x86_64/fs/usr/bin/basename and reproduced away from the lab: that management node's own kernel and image under qemu panicked at 35 seconds, a repack with no change panicked again, and a repack with only chmod 0755 on the loader reached /init and started dracut. The EL rpm is unaffected, because it never runs dh_fixperms. This is why only the Ubuntu genesis-legacy cell saw it, and why that cell has never had a non-mock green. It is not a regression: the same recipe builds the published xcat-genesis-base-amd64. The bit is restored AFTER dh_fixperms rather than excluding the tree with -X, which would also skip its chown 0:0 pass and ship the payload owned by the build user. genesis_deb_loader_executable.t asserts the override exists, still calls dh_fixperms, is scoped to the netboot tree, names both the glibc and the ppc64le loader, and runs the chmod AFTER dh_fixperms. Three of its ten assertions fail without the override, and the ordering assertion fails if the chmod is moved first -- which is the mistake that looks correct. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-genesis-base/debian/rules | 14 ++++ .../unit/genesis_deb_loader_executable.t | 73 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 xCAT-test/unit/genesis_deb_loader_executable.t diff --git a/xCAT-genesis-base/debian/rules b/xCAT-genesis-base/debian/rules index c5dec80962..072501b7a7 100755 --- a/xCAT-genesis-base/debian/rules +++ b/xCAT-genesis-base/debian/rules @@ -11,3 +11,17 @@ override_dh_auto_test: override_dh_auto_install: @true + +# dh_fixperms resets every *.so* in the package to 0644, which is right for a Debian shared +# library and wrong for a netboot ROOT FILESYSTEM. The kernel execs the payload's dynamic loader, +# and a loader with no execute bit makes open_exec() return EACCES, so every ELF in the Genesis +# image fails to start and the node panics with "No working init found". mknb copies the tree +# verbatim into genesis.fs..lzma, so the mode travels into the image. +# +# The bit is restored AFTER dh_fixperms rather than excluding the tree with -X, which would also +# skip its chown 0:0 pass and ship the payload owned by the build user. +override_dh_fixperms: + dh_fixperms + find debian/*/opt/xcat/share/xcat/netboot/genesis -type f \ + \( -name 'ld-*.so' -o -name 'ld-*.so.*' -o -name 'ld64.so.*' \) \ + -exec chmod 0755 {} + diff --git a/xCAT-test/unit/genesis_deb_loader_executable.t b/xCAT-test/unit/genesis_deb_loader_executable.t new file mode 100644 index 0000000000..91071b0aab --- /dev/null +++ b/xCAT-test/unit/genesis_deb_loader_executable.t @@ -0,0 +1,73 @@ +#!/usr/bin/env perl +# THE GENESIS PAYLOAD'S DYNAMIC LOADER MUST KEEP ITS EXECUTE BIT IN THE DEB. +# +# xCAT-genesis-base/debian/rules was a bare `dh $@`, so dh_fixperms applied its *.so* rule to the +# whole package -- correct for a Debian shared library, wrong for a netboot ROOT FILESYSTEM. The +# kernel execs the payload's dynamic loader, and a loader with no execute bit makes open_exec() +# return EACCES, so every ELF in the Genesis image fails to start: +# +# Failed to execute /init (error -13) +# Kernel panic - not syncing: No working init found. +# +# mknb copies the tree verbatim into genesis.fs..lzma, so the broken mode travels into the +# image. The pipeline's iPXE command line carries `quiet`, which hid the reason. +# +# Measured 2026-10-23 on xcat-master-ub, from the installed package: +# 644 .../netboot/genesis/x86_64/fs/usr/lib64/ld-linux-x86-64.so.2 +# 755 .../netboot/genesis/x86_64/fs/usr/bin/basename +# and reproduced off the lab: the MN's own kernel and image under qemu panicked at 35s, repacked +# unchanged panicked again, and repacked with only chmod 0755 on the loader booted. The EL rpm is +# unaffected -- it never runs dh_fixperms -- which is why only xcat-test-ubuntu-24-x86_64 +# -genesis-legacy saw it, and why that leaf has never had a non-mock green. +# +# debian/rules IS the artifact here: there is nothing to execute and the text is the contract, the +# same reason a test may assert a package name in a .spec. The live proof is the leaf. +use strict; +use warnings; +use Test::More; +use FindBin; +use File::Slurper qw(read_text); + +my $rules = "$FindBin::Bin/../../xCAT-genesis-base/debian/rules"; +ok(-f $rules, 'xCAT-genesis-base/debian/rules is present') or die "no rules file\n"; +my $text = read_text($rules); + +# The override must exist. Without it dh_fixperms runs with its defaults over the payload. +like($text, qr/^override_dh_fixperms:/m, + 'debian/rules overrides dh_fixperms'); + +# It must still RUN dh_fixperms. Dropping it would leave the rest of the package unnormalised -- +# the chown 0:0 pass and the 0644 on documentation are both wanted. +like($text, qr/^override_dh_fixperms:\n(?:.*\n)*?\tdh_fixperms\b/m, + '... and still calls dh_fixperms rather than replacing it'); + +# And it must restore the loader afterwards, under the netboot tree only. +my ($body) = $text =~ /^override_dh_fixperms:\n((?:[\t ].*\n|\n)*)/m; +ok(defined $body && length $body, 'the override has a body') or die "no override body\n"; +like($body, qr/netboot\/genesis/, + 'the restore is scoped to the netboot payload, not the whole package'); +like($body, qr/chmod\s+0?755/, + '... and puts the execute bit back'); +like($body, qr/ld-\*\.so/, + '... on the glibc loader (ld-*.so)'); +like($body, qr/ld64\.so/, + '... and on the ppc64le loader (ld64.so.*)'); + +# ORDER: dh_fixperms strips the bit, so the chmod has to come after it. A chmod first would be +# undone by the very command this override exists to correct. +my @lines = split /\n/, $body; +my ($fix) = grep { $lines[$_] =~ /\bdh_fixperms\b/ } 0 .. $#lines; +my ($chm) = grep { $lines[$_] =~ /\bchmod\b/ } 0 .. $#lines; +if (defined $fix && defined $chm) { + cmp_ok($fix, '<', $chm, 'dh_fixperms runs BEFORE the chmod that corrects it'); +} + +# NOT with -X. Excluding the tree from dh_fixperms would also skip its chown 0:0 pass, so the +# payload would ship owned by the build user. +# Command lines only. A comment that merely MENTIONS -X is not an exclusion, and matching the +# whole file made this assertion fail on the comment that explains why -X was not used. +my @recipe = grep { /^\t/ } split /\n/, $text; +ok(!(grep { /dh_fixperms[^\n]*-X/ } @recipe), + 'the tree is not excluded from dh_fixperms wholesale'); + +done_testing; From d9936e4a6040493547694433f865ab84974098f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:42:44 -0300 Subject: [PATCH 120/129] fix(grub2): validate boot inputs before replacing configuration Rejected protocols, unresolved addresses and missing loaders can leave a partial configuration after removing the previous files. Check these inputs before replacing the node configuration and its aliases. --- xCAT-server/lib/xcat/plugins/grub2.pm | 80 +++++++++++++-------------- 1 file changed, 39 insertions(+), 41 deletions(-) diff --git a/xCAT-server/lib/xcat/plugins/grub2.pm b/xCAT-server/lib/xcat/plugins/grub2.pm index ba048ff348..2d0f576b04 100644 --- a/xCAT-server/lib/xcat/plugins/grub2.pm +++ b/xCAT-server/lib/xcat/plugins/grub2.pm @@ -187,27 +187,9 @@ sub setstate { return (1, "Cannot determine current state for this node"); } - # remove the old boot configuration files and create a new one, but only if not offline directive - system("find $bootloader_root/ -inum \$(stat --printf \%i $bootloader_root/$node 2>/dev/null) -exec rm -f {} \\; 2>/dev/null"); - - my $pcfg; - if ($cref->{currstate} ne "offline") { - open($pcfg, '>', "$bootloader_root/" . $node); - print $pcfg "#" . $cref->{currstate} . "\n"; - - if (($::XCATSITEVALS{xcatdebugmode} eq "1") or ($::XCATSITEVALS{xcatdebugmode} eq "2")) { - print $pcfg "set debug=all\n"; - } - - print $pcfg "set timeout=5\n"; - } - - if ($cref->{currstate} eq "boot") { - close($pcfg); - } elsif ($kern and $kern->{kernel}) { - - #It's time to set grub configuration for this node to boot the kernel.. - #get tftpserver + my $serverip; + my $grub2protocol = "tftp"; + if ($cref->{currstate} ne "boot" and $kern and $kern->{kernel}) { my $tftpserver; if (defined($nrhash{$node}->[0]) && $nrhash{$node}->[0]->{'tftpserver'}) { $tftpserver = $nrhash{$node}->[0]->{'tftpserver'}; @@ -217,8 +199,6 @@ sub setstate { $tftpserver = ""; } - my $serverip; - if($tftpserver eq ""){ my @nxtsrvd = xCAT::NetworkUtils->my_ip_facing($node); unless ($nxtsrvd[0]) { @@ -239,19 +219,52 @@ sub setstate { } unless($serverip){ - close($pcfg); return (1, "Unable to determine the tftpserver for $node"); } - my $grub2protocol = "tftp"; if (defined($nrhash{$node}->[0]) && $nrhash{$node}->[0]->{'netboot'} && ($nrhash{$node}->[0]->{'netboot'} =~ /grub2-(.*)/)) { $grub2protocol = $1; } unless ($grub2protocol =~ /^(http|tftp)$/) { - close($pcfg); return (1, "Invalid netboot method, please check noderes.netboot for $node"); } + } + + unless ($nodearch) { + return (1, "No archictecture defined in nodetype table for the node."); + } + if ($nodearch =~ /ppc64/i) { + $nodearch = "ppc" + } + my $grub2bin = "$bootloader_root/grub2." . $nodearch; + unless (-e "$grub2bin") { + return (1, "Stop grub2 configuration for this node, \"$grub2bin\" does not exits."); + } + + my $ip = xCAT::NetworkUtils->getipaddr($node); + unless ($ip) { + return (1, "xCAT unable to resolve IP in grub2 plugin"); + } + + # Keep the previous configuration until the requested boot inputs pass validation. + system("find $bootloader_root/ -inum \$(stat --printf \%i $bootloader_root/$node 2>/dev/null) -exec rm -f {} \\; 2>/dev/null"); + + my $pcfg; + if ($cref->{currstate} ne "offline") { + open($pcfg, '>', "$bootloader_root/" . $node); + print $pcfg "#" . $cref->{currstate} . "\n"; + + if (($::XCATSITEVALS{xcatdebugmode} eq "1") or ($::XCATSITEVALS{xcatdebugmode} eq "2")) { + print $pcfg "set debug=all\n"; + } + + print $pcfg "set timeout=5\n"; + } + + if ($cref->{currstate} eq "boot") { + close($pcfg); + } elsif ($kern and $kern->{kernel}) { # write entries to boot config file, but only if not offline directive if ($cref and $cref->{currstate} ne "offline") { @@ -301,17 +314,6 @@ sub setstate { close($pcfg); } - unless ($nodearch) { - return (1, "No archictecture defined in nodetype table for the node."); - } - if ($nodearch =~ /ppc64/i) { - $nodearch = "ppc" - } - my $grub2bin = "$bootloader_root/grub2." . $nodearch; - unless (-e "$grub2bin") { - return (1, "Stop grub2 configuration for this node, \"$grub2bin\" does not exits."); - } - # grub2- stays for DHCP configurations that makedhcp did not write. my @loaders = ("grub2-$node"); my $dhcp_loader = xCAT::DHCP::BootPolicy->grub2_node_loader(node => $node, arch => $nodearch); @@ -335,10 +337,6 @@ sub setstate { } } - my $ip = xCAT::NetworkUtils->getipaddr($node); - unless ($ip) { - return (1, "xCAT unable to resolve IP in grub2 plugin"); - } #my $mactab = xCAT::Table->new('mac'); my %ipaddrs; my $macstring; From e5df3dde1b4e010529038966310683dfac760e43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:44:45 -0300 Subject: [PATCH 121/129] test(grub2): preserve boot artifacts on rejected updates --- xCAT-test/unit/grub2_preserve_config.t | 118 +++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 xCAT-test/unit/grub2_preserve_config.t diff --git a/xCAT-test/unit/grub2_preserve_config.t b/xCAT-test/unit/grub2_preserve_config.t new file mode 100644 index 0000000000..bc46f92cc7 --- /dev/null +++ b/xCAT-test/unit/grub2_preserve_config.t @@ -0,0 +1,118 @@ +#!/usr/bin/env perl +use strict; +use warnings; +no warnings 'once'; + +use Cwd qw(getcwd); +use File::Path qw(make_path); +use File::Slurper qw(read_text write_text); +use File::Temp qw(tempdir); +use FindBin; +use Test::More; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use XCAT::Test::File qw(repo_path); + +my $root = tempdir(CLEANUP => 1); +local $ENV{XCATROOT} = repo_path('xCAT-server'); +local $ENV{XCATCFG} = "$root/config"; +make_path($ENV{XCATCFG}); +local %::XCATSITEVALS = (tftpdir => "$root/tftpboot", xcatdebugmode => 0); +require xCAT::Table; +require xCAT::NetworkUtils; + +no warnings 'redefine'; +local *xCAT::Table::new = sub { die 'Unexpected database access'; }; +require(repo_path('xCAT-server/lib/xcat/plugins/grub2.pm')); + +sub snapshot { + my ($directory) = @_; + opendir(my $dh, $directory) or die $!; + my %files; + for my $name (sort grep { !/^\./ } readdir($dh)) { + my $file = "$directory/$name"; + my @stat = lstat($file); + $files{$name} = { + inode => $stat[1], mode => $stat[2], links => $stat[3], + uid => $stat[4], gid => $stat[5], mtime => $stat[9], + value => -l $file ? readlink($file) : scalar read_text($file), + }; + } + closedir($dh) or die $!; + return \%files; +} + +my @cases = ( + { name => 'invalid protocol', protocol => 'grub2-ftp', + error => 'Invalid netboot method, please check noderes.netboot for node' }, + { name => 'unresolved server', server => 'missing-server', + error => 'xCAT unable to resolve missing-server' }, + { name => 'failed facing address', server => '', facing => [1, 'no facing network'], + error => 'no facing network' }, + { name => 'empty facing address', server => '', facing => [0, undef], + error => 'Unable to determine the tftpserver for node' }, + { name => 'unresolved node', node_ip => undef, + error => 'xCAT unable to resolve IP in grub2 plugin' }, + { name => 'unresolved boot node', state => 'boot', node_ip => undef, + error => 'xCAT unable to resolve IP in grub2 plugin' }, + { name => 'unresolved offline node', state => 'offline', node_ip => undef, + error => 'xCAT unable to resolve IP in grub2 plugin' }, + { name => 'missing architecture', missing_arch => 1, + error => 'No archictecture defined in nodetype table for the node.' }, + { name => 'missing loader', missing_loader => 1 }, + { name => 'missing state', state => '', + error => 'Cannot determine current state for this node' }, +); + +for my $arch (qw(x86_64 ppc64le aarch64 riscv64)) { + for my $case (@cases) { + subtest "$arch: $case->{name}" => sub { + my $tftpdir = tempdir(DIR => $root, CLEANUP => 1); + my $bootdir = "$tftpdir/boot/grub2"; + make_path($bootdir); + my $loader_arch = $arch eq 'ppc64le' ? 'ppc' : $arch; + my $loader = "$bootdir/grub2.$loader_arch"; + write_text($loader, "loader\n") unless $case->{missing_loader}; + write_text("$bootdir/grub2.previous", "previous loader\n"); + symlink('grub2.previous', "$bootdir/grub2-node") or die $!; + symlink('grub2.previous', "$bootdir/grub2-node.efi") or die $! + if $arch eq 'aarch64'; + write_text("$bootdir/node", "#shell\nset timeout=3\n"); + chmod 0640, "$bootdir/node" or die $!; + for my $alias (qw(grub.cfg-C0000202 grub.cfg-01-02-00-00-00-00-02 old-alias)) { + link("$bootdir/node", "$bootdir/$alias") or die $!; + } + write_text("$bootdir/unrelated", "#boot\n"); + my $before = snapshot($bootdir); + my $node_ip = exists $case->{node_ip} ? $case->{node_ip} : '192.0.2.2'; + local *xCAT::NetworkUtils::getipaddr = sub { + my ($class, $host) = @_; + return '192.0.2.1' if $host eq 'server'; + return $node_ip if $host eq 'node'; + return if $host eq 'missing-server'; + die "Unexpected hostname: $host"; + }; + local *xCAT::NetworkUtils::my_ip_facing = sub { + return @{ $case->{facing} || [0, '192.0.2.1'] }; + }; + my $cwd = getcwd(); + my @result = xCAT_plugin::grub2::setstate( + 'node', + {node => [{kernel => 'images/vmlinuz', initrd => 'images/initrd.img', kcmdline => 'quiet'}]}, + {node => [{currstate => $case->{state} // 'install'}]}, + {node => [{mac => '02:00:00:00:00:02'}]}, + $tftpdir, + {node => [{tftpserver => $case->{server} // 'server', netboot => $case->{protocol} // 'grub2-tftp'}]}, + {}, $case->{missing_arch} ? undef : $arch, 'linux', + ); + chdir($cwd) or die "Cannot restore working directory: $!"; + my $error = $case->{error} // "Stop grub2 configuration for this node, \"$loader\" does not exits."; + is_deeply(\@result, [1, $error], 'the requested update is rejected'); + is_deeply(snapshot($bootdir), $before, 'all prior artifacts and hard links remain unchanged'); + is(xCAT_plugin::grub2::getstate('node', $tftpdir), 'shell', 'reported state remains the previous state'); + }; + } +} + +done_testing(); From 97a0c8d7ac9ba9f07343163d02fe52976fcfae5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:45:22 -0300 Subject: [PATCH 122/129] fix(destiny): match complete states when advancing the chain Substring and regular-expression matches can mistake a different boot state or image name for a completed chain. Compare the full state values while preserving the completed boot exception. --- xCAT-server/lib/xcat/plugins/destiny.pm | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xCAT-server/lib/xcat/plugins/destiny.pm b/xCAT-server/lib/xcat/plugins/destiny.pm index ea5114ea17..f16f1cd3a5 100644 --- a/xCAT-server/lib/xcat/plugins/destiny.pm +++ b/xCAT-server/lib/xcat/plugins/destiny.pm @@ -845,7 +845,10 @@ sub nextdestiny { unless ($ref->{currchain}) { #If no current chain, copy the default $ref->{currchain} = $ref->{chain}; } elsif ($ref->{currchain} !~ /[,;]/){ - if ($ref->{currstate} and ($ref->{currchain} =~ /$ref->{currstate}/)) { + my $completed_state = $ref->{currchain}; + # setdestiny records ondiscover without its command arguments. + $completed_state = 'ondiscover' if $completed_state =~ /^ondiscover=/; + if ($ref->{currstate} and $completed_state eq $ref->{currstate}) { # 'boot' is the steady state a completed provision leaves behind, # set by setdestiny once the install or netboot destiny is applied. # Some installers advance the destiny more than once, so it has to From 9b47f76ca2f034fe3d00830dff30375fd1c862d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:45:48 -0300 Subject: [PATCH 123/129] test(destiny): distinguish complete and overlapping chain states --- xCAT-test/unit/destiny_chain_advance.t | 82 +++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 2 deletions(-) diff --git a/xCAT-test/unit/destiny_chain_advance.t b/xCAT-test/unit/destiny_chain_advance.t index b946815c28..5279f935a4 100644 --- a/xCAT-test/unit/destiny_chain_advance.t +++ b/xCAT-test/unit/destiny_chain_advance.t @@ -17,11 +17,12 @@ BEGIN { package xCAT::Table; sub new { my ( $class, $table ) = @_; - die "Unexpected table $table" unless $table eq 'chain'; - return bless {}, $class; + die "Unexpected table $table" unless $table eq 'chain' || $table eq 'bootparams'; + return bless { table => $table }, $class; } sub getNodesAttribs { my ( $self, $nodes, @attributes ) = @_; + return {} if $self->{table} eq 'bootparams'; @attributes = @{ $attributes[0] } if ref($attributes[0]) eq 'ARRAY'; my %result; for my $node (@$nodes) { @@ -37,6 +38,14 @@ BEGIN { @{$rows{$node}}{keys %$copy} = values %$copy; return 0; } + sub setNodesAttribs { + my ( $self, $updates ) = @_; + for my $node (keys %$updates) { + $self->setNodeAttribs($node, $updates->{$node}); + } + return 0; + } + sub close { return; } $INC{'xCAT/Table.pm'} = __FILE__; package xCAT::NodeRange; @@ -99,6 +108,38 @@ sub capture_chain_handoffs { my $image = 'osimage=rhels9-x86_64-install-compute'; my @cases = ( + { + name => 'boot does not complete a new iSCSI boot step', + rows => { node1 => { currstate => 'boot', currchain => 'iscsiboot', chain => 'iscsiboot' } }, + steps => [ { transitions => [ [ 'node1', 'iscsiboot', 'iscsiboot' ] ], enact => ['node1'] } ], + }, + { + name => 'iSCSI boot does not complete a new local boot step', + rows => { node1 => { currstate => 'iscsiboot', currchain => 'boot', chain => 'boot' } }, + steps => [ { transitions => [ [ 'node1', 'boot', 'boot' ] ], enact => ['node1'] } ], + }, + { + name => 'an exactly completed iSCSI boot step retains the standby policy', + rows => { node1 => { currstate => 'iscsiboot', currchain => 'iscsiboot', chain => 'iscsiboot' } }, + steps => [ { transitions => [ [ 'node1', 'standby', 'standby' ] ] } ], + }, + { + name => 'an image-name prefix does not complete a different image', + rows => { node1 => { currstate => $image, currchain => "$image-extra", chain => "$image-extra" } }, + steps => [ { transitions => [ [ 'node1', "$image-extra", "$image-extra" ] ], enact => ['node1'] } ], + }, + { + name => 'dots in image names are literal', + rows => { node1 => { currstate => 'osimage=rhels9.6-compute', + currchain => 'osimage=rhels9x6-compute', chain => 'osimage=rhels9x6-compute' } }, + steps => [ { transitions => [ [ 'node1', 'osimage=rhels9x6-compute', 'osimage=rhels9x6-compute' ] ], enact => ['node1'] } ], + }, + { + name => 'an exactly completed dotted image retains the standby policy', + rows => { node1 => { currstate => 'osimage=rhels9.6-compute', + currchain => 'osimage=rhels9.6-compute', chain => 'osimage=rhels9.6-compute' } }, + steps => [ { transitions => [ [ 'node1', 'standby', 'standby' ] ] } ], + }, { name => 'repeated advances from boot preserve the state without enacting again', rows => { node1 => { currstate => 'boot', currchain => 'boot', chain => $image } }, @@ -245,4 +286,41 @@ for my $case (@cases) { }; } +subtest 'a final discovery step completes using the state recorded by setdestiny' => sub { + my $discovery = 'ondiscover=makegocons|rspconfig:sshcfg'; + %rows = (node1 => {currstate => 'boot', currchain => $discovery, chain => $discovery}); + my (@commands, @errors); + { + no warnings qw(once redefine); + local *xCAT::Utils::runcmd = sub { + push @commands, [@_]; + return; + }; + local *xCAT_plugin::destiny::getdestiny = sub { return; }; + xCAT_plugin::destiny::process_request( + {command => ['setdestiny'], node => ['node1'], arg => [$discovery]}, + sub { push @errors, dclone($_[0]); }, + sub { die 'Unexpected subrequest while applying discovery'; }, + ); + } + is_deeply(\@commands, [ + ['xCAT::Utils', 'makegocons node1 ', 0], + ['xCAT::Utils', 'rspconfig node1 sshcfg', 0], + ], 'the real applicator runs both discovery commands once'); + is_deeply(\@errors, [], 'applying discovery emits no errors'); + is($rows{node1}->{currstate}, 'ondiscover', 'the real applicator records the bare discovery state'); + is($rows{node1}->{currchain}, $discovery, 'the chain retains its command arguments'); + + my $result = capture_chain_handoffs({command => ['nextdestiny'], node => ['node1']}); + is_deeply($rows{node1}, {currstate => 'standby', currchain => 'standby', chain => $discovery}, + 'the recorded state completes the final discovery step'); + is_deeply($result->{handoffs}, [{ + request => {node => ['node1'], arg => ['standby']}, flag => 1, + chain_at_handoff => dclone($rows{node1}), + }], 'completion hands off standby instead of repeating discovery'); + is_deeply($result->{subrequests}, [], 'completed discovery does not enact again'); + is_deeply($result->{errors}, [], 'completion emits no callback error'); + is_deeply($result->{logs}, [], 'completion emits no syslog error'); +}; + done_testing(); From d83bf58d9eb3a5c8b766d97e2a921a409b33cf78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:46:20 -0300 Subject: [PATCH 124/129] fix(destiny): preserve enactment when other nodes have completed --- xCAT-server/lib/xcat/plugins/destiny.pm | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/xCAT-server/lib/xcat/plugins/destiny.pm b/xCAT-server/lib/xcat/plugins/destiny.pm index f16f1cd3a5..8626899192 100644 --- a/xCAT-server/lib/xcat/plugins/destiny.pm +++ b/xCAT-server/lib/xcat/plugins/destiny.pm @@ -830,9 +830,11 @@ sub nextdestiny { my $node; my $noupdate_flag = 0; + my @enactnodes; $chaintab = xCAT::Table->new('chain'); my $chainents = $chaintab->getNodesAttribs(\@nodes, [qw(currstate currchain chain)]); foreach $node (@nodes) { + my $enact = 1; unless ($chaintab) { syslog("local4|err", "ERROR: $node requested destiny update, no chain table"); return; #nothing to do... @@ -857,7 +859,7 @@ sub nextdestiny { unless ($ref->{currchain} eq 'boot') { $ref->{currchain} = 'standby'; } - $callnodeset = 0; + $enact = 0; } } my @chain = split /[,;]/, $ref->{currchain}; @@ -876,12 +878,13 @@ sub nextdestiny { { my @items = split /[:]/, $ref->{currstate}; $requ{arg} = \@items; - $noupdate_flag = 1; + $noupdate_flag = 1 if $enact; } setdestiny(\%requ, $flag + 1); + push @enactnodes, $node if $enact; } - if ($callnodeset) { + if ($callnodeset and @enactnodes) { my $args; if ($noupdate_flag) { @@ -892,7 +895,7 @@ sub nextdestiny { $args = ['enact']; } $subreq->({ command => ['nodeset'], - node => \@nodes, + node => \@enactnodes, arg => $args }); } From 2de8d308edd954f949bdb2fc05e44778b4075d68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:46:45 -0300 Subject: [PATCH 125/129] test(destiny): cover mixed completed and active chain requests --- xCAT-test/unit/destiny_chain_advance.t | 43 ++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/xCAT-test/unit/destiny_chain_advance.t b/xCAT-test/unit/destiny_chain_advance.t index 5279f935a4..f70d21469a 100644 --- a/xCAT-test/unit/destiny_chain_advance.t +++ b/xCAT-test/unit/destiny_chain_advance.t @@ -249,6 +249,49 @@ my @cases = ( }, ); +for my $order ([qw(node1 node2)], [qw(node2 node1)]) { + for my $option (0, 1) { + my $state = $option ? "$image:--noupdateinitrd" : 'shutdown'; + my %transitions = ( + node1 => ['node1', 'boot', 'boot'], + node2 => ['node2', $state, 'boot', $option ? [$image, '--noupdateinitrd'] : ['shutdown']], + ); + push @cases, { + name => "completed and active nodes in order @$order, initrd option=$option", + request => {command => ['nextdestiny'], node => $order}, + rows => { + node1 => {currstate => 'boot', currchain => 'boot', chain => 'boot'}, + node2 => {currstate => 'boot', currchain => "$state,boot", chain => "$state,boot"}, + }, + steps => [{ + transitions => [map { $transitions{$_} } @$order], + enact => ['node2'], enact_args => $option ? ['enact', '--noupdateinitrd'] : ['enact'], + }], + }; + } +} +push @cases, { + name => 'a completed middle node does not suppress either active neighbor', + request => {command => ['nextdestiny'], node => [qw(node3 node2 node1)]}, + rows => { + node1 => {currstate => 'offline', currchain => 'boot', chain => 'boot'}, + node2 => {currstate => 'boot', currchain => 'boot', chain => 'boot'}, + node3 => {currstate => 'boot', currchain => 'shutdown,boot', chain => 'shutdown,boot'}, + }, + steps => [{ + transitions => [['node3', 'shutdown', 'boot'], ['node2', 'boot', 'boot'], ['node1', 'boot', 'boot']], + enact => [qw(node3 node1)], + }], +}, { + name => 'a request containing only completed nodes does not enact', + request => {command => ['nextdestiny'], node => [qw(node1 node2)]}, + rows => { + node1 => {currstate => 'boot', currchain => 'boot', chain => 'boot'}, + node2 => {currstate => $image, currchain => $image, chain => $image}, + }, + steps => [{transitions => [['node1', 'boot', 'boot'], ['node2', 'standby', 'standby']]}], +}; + for my $case (@cases) { subtest $case->{name} => sub { %rows = %{ dclone($case->{rows}) }; From 0aefdb479b49ac4fec0350fd9bfc0b4c72e6391a Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:13:33 -0300 Subject: [PATCH 126/129] test(xcat-test): a harness path beside an xCAT directory counts as an xCAT denial selinux_avc_check.sh decides which SELinux denials xCAT answers for by matching the audit record's path against XCAT_AVC_PATH. The match treats each entry as a string prefix, so a sibling directory whose name merely starts with one of them is kept. On build 2 of xcat-test-el10-x86_64-selinux the one denial the run attributed to xCAT was xcatd executing the CI's own notification hook under /var/lib/xcat-cluster-test, and selinux_cn_diskful_enforcing failed on it. The new bats test classifies that record and asserts nothing is kept. Two more assert the directories themselves and a file under one are still kept, so an over-anchored match does not pass silently. Without the fix 1 of 18 fails, and it is the sibling-path test. The other two pass before and after. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/bats/selinux_avc_check.bats | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/xCAT-test/bats/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats index 060ec143b0..614a3c7135 100644 --- a/xCAT-test/bats/selinux_avc_check.bats +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -66,6 +66,31 @@ SSH_RECORD='type=AVC msg=audit(1759000002.333:444): avc: denied { siginh } for [[ "$output" == *'comm="genimage"'* ]] } +# The hook cluster-test.pl registers with regnotif, executed by an xcatd worker. The +# harness wrote this file, not xCAT, and /var/lib/xcat-cluster-test is not /var/lib/xcat. +# Captured on build 2 of xcat-test-el10-x86_64-selinux, where it was the one denial the +# run attributed to xCAT and selinux_cn_diskful_enforcing failed on it. +HARNESS_RECORD='type=AVC msg=audit(1792858690.329:3003): avc: denied { execute_no_trans } for pid=51342 comm=78636174643A204442204163636573 path="/var/lib/xcat-cluster-test/event-notify.pl" dev="vda4" ino=75521321 scontext=system_u:system_r:xcat_t:s0 tcontext=unconfined_u:object_r:var_lib_t:s0 tclass=file permissive=1' + +@test "a path that merely starts with the name of an xCAT directory is not kept" { + run classify "$HARNESS_RECORD" + [ -z "$output" ] +} + +@test "an xCAT directory is kept when the path names the directory itself" { + local record='type=AVC msg=audit(1759000005.666:777): avc: denied { search } for pid=6789 comm="httpd" path="/install" dev="vda2" ino=56 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:default_t:s0 tclass=dir permissive=0' + run classify "$record" + [ "$status" -eq 0 ] + [[ "$output" == *'path="/install"'* ]] +} + +@test "a file under an xCAT directory is kept" { + local record='type=AVC msg=audit(1759000006.777:888): avc: denied { read } for pid=7890 comm="httpd" path="/var/lib/xcat/cert/server-cert.pem" dev="vda2" ino=57 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:var_lib_t:s0 tclass=file permissive=0' + run classify "$record" + [ "$status" -eq 0 ] + [[ "$output" == *'/var/lib/xcat/cert/server-cert.pem'* ]] +} + @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" From 65f4de2c6b34d452df05d7a26687e772cbf81a32 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:13:46 -0300 Subject: [PATCH 127/129] fix(xcat-test): a path that only starts with an xCAT directory name is counted as xCAT selinux_avc_classify matched the entries of XCAT_AVC_PATH as string prefixes, with [^"]* before the alternation and no boundary after it. A directory name is not a string prefix: /var/lib/xcat-cluster-test is not /var/lib/xcat, and /installer is not /install. The CI writes its regnotif notification hook to /var/lib/xcat-cluster-test/event-notify.pl. xcatd executes it, the file carries var_lib_t, and xcat_t has no execute_no_trans on it, so the audit log holds the record. The classifier kept it on the strength of the prefix, the count read XCAT_AVC=1, and selinux_cn_diskful_enforcing failed on a file the product does not ship. The policy was confining xcat_t correctly. The path half of the pattern now starts at the opening quote and ends at a / or at the closing quote, so a listed directory matches itself and the files under it, and nothing else. The subject half is unchanged: a denial by an xCAT program is still kept whatever the path. selinux_avc_check.bats covers it. Reverting the boundary group fails the sibling-path test alone; requiring a trailing / fails the bare-directory test alone. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh index ffe4357bd1..9968a0c254 100755 --- a/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh +++ b/xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh @@ -40,9 +40,13 @@ 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' +# The path must be one of those directories, or a file under one. A directory name is +# not a string prefix: /var/lib/xcat-cluster-test holds the CI's own notification hook, +# and matching it as /var/lib/xcat put an xcatd denial on a harness file into the count. +# So the name starts at the quote and ends at a / or at the closing quote. selinux_avc_classify() { - grep -E "(comm|exe)=\"[^\"]*(${XCAT_AVC_COMM})[^\"]*\"|(path|name)=\"[^\"]*(${XCAT_AVC_PATH})" + 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: From 2c56d3d2e8a3e7b2e0103d0f86f39634a0aadba6 Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:52:34 -0300 Subject: [PATCH 128/129] test(xcat-core): xcattest skips every case on an openSUSE management node xCAT::Test::OS::current_os returns undef on openSUSE. /etc/os-release carries ID="opensuse-leap" and the word sles appears nowhere in it, so the os-release arm falls through to its own return undef, and Leap ships none of /etc/redhat-release, /etc/lsb-release or /etc/SuSE-release to reach another arm. xcattest then warns "Use of uninitialized value $currentos" four times per case and rejects all of them: "Test case reg_linux_diskfull_installation_flat has an invalid OS option - Linux" and "There is no valid case to run". 328 of the shipped cases declare os:Linux, so an openSUSE management node runs none of them. The message blames the case, and the cases are skipped rather than failed, which reports no result at all. Measured 2026-10-24 on xcat20-mn, an openSUSE Leap 15.6 management node: current_os answered UNDEF, /etc/os-release holds ID="opensuse-leap" and VERSION_ID="15.6", and none of the three fallback files exist. Five assertions fail on this commit: Leap is recognised, at any Leap version, the older ID="opensuse" spelling, Tumbleweed, and a Leap node matching an os:Linux case. The fourteen that already existed pass, including the one that holds the change down -- a distribution whose os-release names neither sles nor openSUSE is still not recognised. The same bug was fixed on 2026-09-18 in f7be54a1b, against the chain of greps xcattest carried before xCAT::Test::OS existed. That branch was never merged, 3582c6ab1 rewrote the routine as a module without it, and its test lifted the routine out of xcattest with a regex. This test loads the module instead. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/unit/xcattest_os_selection.t | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/xCAT-test/unit/xcattest_os_selection.t b/xCAT-test/unit/xcattest_os_selection.t index eed16fc128..9b55327cac 100644 --- a/xCAT-test/unit/xcattest_os_selection.t +++ b/xCAT-test/unit/xcattest_os_selection.t @@ -60,6 +60,56 @@ is(xCAT::Test::OS::current_os(a_system('lsb-release' => "DISTRIB_ID=Ubuntu\n")), 'Ubuntu is named from lsb-release'); is(xCAT::Test::OS::current_os(a_system('os-release' => qq{ID="sles"\nVERSION="15-SP6"\n})), 'sles', 'SLES is named from os-release'); + +# openSUSE. /etc/os-release carries ID="opensuse-leap" and no "sles" anywhere, and Leap ships +# none of redhat-release, lsb-release or SuSE-release, so current_os fell through its os-release +# arm and returned undef. xcattest then warned "Use of uninitialized value $currentos" four +# times per case and rejected every one: "Test case reg_linux_diskfull_installation_flat has an +# invalid OS option - Linux / There is no valid case to run". 328 of the shipped cases declare +# os:Linux, so an openSUSE management node ran none of them, and the two cases were skipped +# rather than failed -- no result at all. +# +# Measured 2026-10-24 on xcat20-mn, an openSUSE Leap 15.6 management node: current_os answered +# UNDEF, /etc/os-release holds ID="opensuse-leap" and VERSION_ID="15.6", and none of the three +# fallback files exist. +# +# openSUSE answers with the SLE family rather than a name of its own, which was decided on +# 2026-09-18 for the same bug against the routine xcattest carried before xCAT::Test::OS +# existed. Leap and SLE of the same major share a package set, sles.pm claims leap15, and +# xcat.org publishes the Leap dependencies under sles15. It also lets the 18 cases written +# os:sles select a Leap node, which a separate name would not. +my $LEAP_OS_RELEASE = <<'REL'; +NAME="openSUSE Leap" +VERSION="15.6" +ID="opensuse-leap" +ID_LIKE="suse opensuse" +VERSION_ID="15.6" +PRETTY_NAME="openSUSE Leap 15.6" +REL + +is(xCAT::Test::OS::current_os(a_system('os-release' => $LEAP_OS_RELEASE)), 'sles', + 'openSUSE Leap is the SLE family whose package set it shares'); + +my $leap16 = $LEAP_OS_RELEASE; +$leap16 =~ s/15\.6/16.0/g; +is(xCAT::Test::OS::current_os(a_system('os-release' => $leap16)), 'sles', + 'at any Leap version, so a new release needs no change here'); + +# Leap 42.3, which the sles12 cell runs, spells its ID without the -leap suffix. +my $leap42 = $LEAP_OS_RELEASE; +$leap42 =~ s/ID="opensuse-leap"/ID="opensuse"/; +$leap42 =~ s/15\.6/42.3/g; +is(xCAT::Test::OS::current_os(a_system('os-release' => $leap42)), 'sles', + 'the older spelling, ID="opensuse", is recognised too'); + +is(xCAT::Test::OS::current_os( + a_system('os-release' => qq{NAME="openSUSE Tumbleweed"\nID="opensuse-tumbleweed"\n})), + 'sles', 'Tumbleweed answers rather than falling through silently'); + +# The thing that actually broke: an empty answer matches no os: restriction at all. +my @linux = xCAT::Test::OS::linux_aliases(); +ok(scalar(grep { xCAT::Test::OS::current_os(a_system('os-release' => $LEAP_OS_RELEASE)) =~ /$_/i } @linux), + 'an openSUSE Leap management node matches an os:Linux case'); is(xCAT::Test::OS::current_os(a_system()), 'aix', 'a system with none of the release files is aix, as before'); From f47541e19b839b4cf3196e58ef7576d14a5e9d4f Mon Sep 17 00:00:00 2001 From: Daniel Hilst <392820+dhilst@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:52:34 -0300 Subject: [PATCH 129/129] fix(xcat-core): an openSUSE management node is not recognised, so no case runs current_os reads /etc/os-release and returns undef for openSUSE. The word sles appears nowhere in Leap's os-release -- ID is opensuse-leap on 15.x and opensuse on 42.3 -- and Leap ships none of /etc/redhat-release, /etc/lsb-release or /etc/SuSE-release, so no other arm is reached. xcattest rejects every case on the resulting undef, and 328 of the shipped cases declare os:Linux. openSUSE now answers with the SLE family whose package set it shares, which is the answer decided on 2026-09-18 for the same bug: sles.pm claims leap15 and xcat.org publishes the Leap dependencies under sles15. It also lets the 18 cases written os:sles select a Leap node, which a name of its own would not. current_os has one consumer -- the os: comparison at xcattest:1052 -- so the answer affects nothing else. The match is on the whole file rather than on ID alone, because Leap 42.3 spells its ID opensuse and Tumbleweed opensuse-tumbleweed. It is placed after the sles test, so a real SLES node is unaffected. xcattest_os_selection.t passes, 19 of 19. Reverting this file alone fails its five openSUSE assertions and nothing else. Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com> --- xCAT-test/lib/xCAT/Test/OS.pm | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xCAT-test/lib/xCAT/Test/OS.pm b/xCAT-test/lib/xCAT/Test/OS.pm index 7bb05c0539..b50076881d 100644 --- a/xCAT-test/lib/xCAT/Test/OS.pm +++ b/xCAT-test/lib/xCAT/Test/OS.pm @@ -49,6 +49,13 @@ sub current_os { if (-f "$root/etc/os-release") { my $text = _slurp("$root/etc/os-release") // ''; return 'sles' if $text =~ /sles/; + # openSUSE answers with the SLE family whose package set it shares: sles.pm claims + # leap15 and xcat.org publishes the Leap dependencies under sles15. Leap's os-release + # says ID="opensuse-leap" and carries no SLES string, and Leap ships no + # /etc/SuSE-release, so without this arm the sub returns undef -- which matches no + # case's os: restriction, so xcattest skips every os-restricted case and reports it as + # "has an invalid OS option", blaming the case. + return 'sles' if $text =~ /opensuse/i; if ($text =~ /^ID\s*=\s*"?openeuler"?\s*$/mi) { my ($version) = $text =~ /^VERSION\s*=\s*"?([^"\n]+?)"?\s*$/mi; my $release = _openeuler_release($version);