diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 629fc208f0..63c742b3fb 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/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 @@ -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 @@ -102,7 +103,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 @@ -123,11 +124,35 @@ 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 - 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' - 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' + + 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 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/build-utils/lib/XCAT/BuildUtils.pm b/build-utils/lib/XCAT/BuildUtils.pm index c5268a109c..fb9138de19 100644 --- a/build-utils/lib/XCAT/BuildUtils.pm +++ b/build-utils/lib/XCAT/BuildUtils.pm @@ -43,12 +43,13 @@ 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 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,60 @@ sub cancel_build { sub DESTROY { shift->release } } +# The packages a target does not build, and why. A rule names either the target +# prefixes that do NOT build the package, or, with `only`, the pattern of the +# targets that DO. +# +# 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. +# +# 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. openSUSE Leap ships no +# selinux-policy-devel at all. +# +# It is named with `only` rather than by listing the families that are not EL, +# because naming them means a family added later TRIES to build it. openSUSE was +# added after the first version of this guard, matched neither arm of its +# /\Aopeneuler-/ test, and xcat-core-build-opensuse #42 spent three attempts on +# "No matching package to install: selinux-policy-devel" and failed the whole +# openSUSE family. + +# 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)?-/; + +my @PACKAGE_SKIPS = ( + { package => 'xCAT-genesis-base', + prefixes => ['opensuse-'], + reason => 'openSUSE ships no legacy Genesis', + }, + { package => 'xCAT-selinux', + only => $EL_TARGET, + reason => 'SELinux support is EL only', + }, +); + +# 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) && length($target); + for my $skip (@PACKAGE_SKIPS) { + next unless $pkg eq $skip->{package}; + return $skip->{reason} if $skip->{only} && $target !~ $skip->{only}; + return $skip->{reason} + if $skip->{prefixes} + && 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..8b3392e131 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); @@ -136,6 +137,7 @@ my @PACKAGES = qw( xCAT-openbmc-py xCAT-probe xCAT-rmc + xCAT-selinux xCAT-server xCAT-test xCAT-vlan @@ -676,9 +678,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,12 +692,12 @@ 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 # 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 @@ -705,9 +708,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 { @@ -717,6 +720,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 @@ -735,14 +739,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), @@ -755,10 +757,10 @@ 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", + for my $rd (($opts{source_only} ? () : ("$repodir/repodata")), (-d "$repodir/SRPMS/repodata" ? ("$repodir/SRPMS/repodata") : ())) { my $repomd = "$rd/repomd.xml"; next unless -f $repomd; @@ -863,10 +865,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}; @@ -1027,7 +1026,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. @@ -1185,11 +1195,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. @@ -1298,11 +1307,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. 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/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..8cdb44d130 --- /dev/null +++ b/docs/source/advanced/security/selinux.rst @@ -0,0 +1,119 @@ +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 runs in two permissive domains +----------------------------------- + +``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. + +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 +-------------------------- + +``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/advanced/selinux/index.rst b/docs/source/advanced/selinux/index.rst new file mode 100644 index 0000000000..d8f4df8234 --- /dev/null +++ b/docs/source/advanced/selinux/index.rst @@ -0,0 +1,225 @@ +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 +----- + +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 +--------------- + +``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`` +/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 +``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``. + +A rootimg component in the middle of an image root is ambiguous, because +``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. ``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 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. + +``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 + + # 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 +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. + +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 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 +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)" + ps -eo label,args | grep '[x]catd:' + +The domains are permissive +-------------------------- + +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 +and the domain becomes enforcing. + +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:: + + 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. diff --git a/docs/source/guides/get-started/quick_start.rst b/docs/source/guides/get-started/quick_start.rst index b85d5c9e4c..e6e889cc7e 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``: :: @@ -102,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 ] 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/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/perl-xCAT/xCAT/SELinux.pm b/perl-xCAT/xCAT/SELinux.pm new file mode 100644 index 0000000000..7ed29943ba --- /dev/null +++ b/perl-xCAT/xCAT/SELinux.pm @@ -0,0 +1,439 @@ +# 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'; + +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 + + 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 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 when SELinux is off + 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, + ); + + return \%answer if $mode eq 'disabled'; + + $answer{warning} = + "SELINUX is $mode. xCAT does not change the SELinux mode or $CONFIG_FILE."; + + return \%answer; +} + +#----------------------------------------------------------------------------- + +=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: + 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; +} + +#----------------------------------------------------------------------------- + +=head3 netboot_supported + + Descriptions: + Reports whether a stateless image of this OS can boot with SELinux on. + 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: + 0. + Example: + my $ok = xCAT::SELinux->netboot_supported($osver); + +=cut + +#----------------------------------------------------------------------------- +sub netboot_supported { + my ($class, $osver) = @_; + + 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 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) = @_; + + 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) = @_; + + open(my $fh, '<', $path) or return undef; + my $line = <$fh>; + close($fh); + + return $line; +} + +1; diff --git a/perl-xCAT/xCAT/Schema.pm b/perl-xCAT/xCAT/Schema.pm index 33a80f6abb..fefcc0fc99 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.", }, @@ -1254,6 +1255,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" . @@ -2084,6 +2090,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', diff --git a/xCAT-client/bin/mysqlsetup b/xCAT-client/bin/mysqlsetup index 2db1a81874..0091ced6b3 100755 --- a/xCAT-client/bin/mysqlsetup +++ b/xCAT-client/bin/mysqlsetup @@ -764,6 +764,74 @@ 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. +# 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 +{ + 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 +936,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-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-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. diff --git a/xCAT-probe/lib/perl/probe_format.pm b/xCAT-probe/lib/perl/probe_format.pm new file mode 100644 index 0000000000..6abbd0e391 --- /dev/null +++ b/xCAT-probe/lib/perl/probe_format.pm @@ -0,0 +1,124 @@ +# 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, always more than the flag width + +=cut + +#----------------------------------- +sub screen_width { + my ($raw) = @_; + + # '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; +} + +#----------------------------------- + +=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/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-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 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-selinux/xCAT-selinux.spec b/xCAT-selinux/xCAT-selinux.spec new file mode 100644 index 0000000000..9db0e8287b --- /dev/null +++ b/xCAT-selinux/xCAT-selinux.spec @@ -0,0 +1,72 @@ +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 + +%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 +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 diff --git a/xCAT-selinux/xcat.fc b/xCAT-selinux/xcat.fc new file mode 100644 index 0000000000..b8ed67a361 --- /dev/null +++ b/xCAT-selinux/xcat.fc @@ -0,0 +1,55 @@ +# 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) +/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 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) + +# A rootimg keeps the labels of its own OS, so restorecon must not change them. +# genimage puts the tree at /rootimg, and rootimgdir can be at any +# 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. +# +# 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. +# +# 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. 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) +/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) + +# 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. diff --git a/xCAT-selinux/xcat.te b/xCAT-selinux/xcat.te new file mode 100644 index 0000000000..5be39a605d --- /dev/null +++ b/xCAT-selinux/xcat.te @@ -0,0 +1,456 @@ +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, dhcpd_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 domains +# + +# 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) + +# 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 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; + +# 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 }; + + # setup_tftpd kills a stray server before it starts its own. + allow xcat_t tftpd_t:process { signal signull }; +') + +optional_policy(` + gen_require(` + type unconfined_t; + role unconfined_r; + ') + + # 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 }; +# 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) +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) +# 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) +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) +# 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 +# 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; +# 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; +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 +# + +# 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 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, 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 +# 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; 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/xCAT-server/etc/init.d/xcatd.service b/xCAT-server/etc/init.d/xcatd.service index 362b76dea8..4ae5e0f099 100644 --- a/xCAT-server/etc/init.d/xcatd.service +++ b/xCAT-server/etc/init.d/xcatd.service @@ -3,12 +3,21 @@ Description=xCAT management service After=network.target syslog.service [Service] +# 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 +# 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 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 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 9200a8b594..a23f923de8 100644 --- a/xCAT-server/lib/xcat/plugins/anaconda.pm +++ b/xCAT-server/lib/xcat/plugins/anaconda.pm @@ -20,6 +20,7 @@ use xCAT::SvrUtils; use xCAT::UFTP; use xCAT::Yum; use xCAT::MediaPerms; +use xCAT::SELinux; use Getopt::Long; Getopt::Long::Configure("bundling"); @@ -391,6 +392,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; @@ -976,10 +980,15 @@ 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' 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}"] }); + } + $kcmdline .= " " . xCAT::SELinux->kcmdline_selinux($selinux, $osver) . " "; # if kdump service is enbaled, add "crashkernel=" and "kdtarget=" if ($dump) { @@ -1114,6 +1123,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; @@ -1412,6 +1422,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/destiny.pm b/xCAT-server/lib/xcat/plugins/destiny.pm index ea5114ea17..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... @@ -845,7 +847,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 @@ -854,7 +859,7 @@ sub nextdestiny { unless ($ref->{currchain} eq 'boot') { $ref->{currchain} = 'standby'; } - $callnodeset = 0; + $enact = 0; } } my @chain = split /[,;]/, $ref->{currchain}; @@ -873,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) { @@ -889,7 +895,7 @@ sub nextdestiny { $args = ['enact']; } $subreq->({ command => ['nodeset'], - node => \@nodes, + node => \@enactnodes, arg => $args }); } 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..2d0f576b04 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; @@ -186,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'}; @@ -216,8 +199,6 @@ sub setstate { $tftpserver = ""; } - my $serverip; - if($tftpserver eq ""){ my @nxtsrvd = xCAT::NetworkUtils->my_ip_facing($node); unless ($nxtsrvd[0]) { @@ -238,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") { @@ -300,20 +314,14 @@ 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); + 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,16 +329,14 @@ 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); - unless ($ip) { - return (1, "xCAT unable to resolve IP in grub2 plugin"); - } #my $mactab = xCAT::Table->new('mac'); my %ipaddrs; my $macstring; diff --git a/xCAT-server/lib/xcat/plugins/mknb.pm b/xCAT-server/lib/xcat/plugins/mknb.pm index 0d483c4cd4..9e75a5d1ff 100644 --- a/xCAT-server/lib/xcat/plugins/mknb.pm +++ b/xCAT-server/lib/xcat/plugins/mknb.pm @@ -381,8 +381,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 @@ -395,13 +397,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; - $rc = $run->("cp -a $a{genesis_dir}/kernel $a{tftpdir}/xcat/genesis.kernel.$a{arch}"); - return ($rc, "$a{genesis_dir}/kernel") if $rc; - return (0, undef); + 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", "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. + 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 { @@ -633,12 +648,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-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); } diff --git a/xCAT-server/sbin/xcatconfig b/xCAT-server/sbin/xcatconfig index 4f83d4a4dd..43bb5bd9ef 100755 --- a/xCAT-server/sbin/xcatconfig +++ b/xCAT-server/sbin/xcatconfig @@ -28,9 +28,11 @@ 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; +use xCAT::TableUtils; use Socket; #----------------------------------------------------------------------------- @@ -415,6 +417,11 @@ if ($::INITIALINSTALL || $::UPDATEINSTALL || $::FORCE || $::initDB) &initDB; } +if ($::INITIALINSTALL) +{ + &recordselinuxdefault; +} + # # set up syslog # @@ -513,41 +520,10 @@ 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 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") - { - $enforcefile = "/selinux/enforce"; - } elsif (-f "/sys/fs/selinux/enforce") { - $enforcefile = "/sys/fs/selinux/enforce"; - } - if ($enforcefile) - { - my $cmd = "echo 0 > $enforcefile"; - 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/' /etc/selinux/config"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); - } + xCAT::MsgUtils->message('W', $selinux->{warning}); } } @@ -1110,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 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.aarch64.postinstall b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall index 2ad53bb406..be42313772 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.aarch64.postinstall @@ -37,19 +37,19 @@ 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 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 dd2576c8f7..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels10.ppc64le.postinstall @@ -37,20 +37,20 @@ 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 #-- 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 2ad53bb406..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 @@ -37,19 +37,19 @@ 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 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.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..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels8.ppc64le.postinstall @@ -37,20 +37,20 @@ 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 #-- 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 2ad53bb406..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 @@ -37,19 +37,19 @@ 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 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 dd2576c8f7..ba8f22b6ae 100755 --- a/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall +++ b/xCAT-server/share/xcat/netboot/rh/compute.rhels9.ppc64le.postinstall @@ -37,20 +37,20 @@ 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 #-- 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 2ad53bb406..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 @@ -37,19 +37,19 @@ 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 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/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..1e7ea3d54e 100755 --- a/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall +++ b/xCAT-server/share/xcat/netboot/rocky/compute.rocky10.riscv64.postinstall @@ -37,19 +37,19 @@ 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 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/xCAT-server.spec b/xCAT-server/xCAT-server.spec index 2bbeaaaad3..8fc21abee1 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} +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 @@ -517,6 +521,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 < 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: 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. +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})(/|\")" +} + +# 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 + [ -n "$since" ] || return 2 + + searched=$(ausearch --input-logs -ts "$since" --raw 2>/dev/null | grep -c '^type=') + if [ "$searched" -eq 0 ]; then + 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 + + 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 ;; + --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/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..1c51000de5 --- /dev/null +++ b/xCAT-test/autotest/testcase/genesis/selinux_context.sh @@ -0,0 +1,81 @@ +#!/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 +[ "$arch" = ppc64el ] && arch=ppc64le + +tftpdir=$(lsdef -t site -i tftpdir 2>/dev/null | sed -n 's/^[[:space:]]*tftpdir=//p') +[ -n "$tftpdir" ] || tftpdir=/tftpboot + +# 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" + 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 + # 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. 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" + exit 1 +fi +echo "GENESIS_SELINUX_OK: the staged kernel carries the context the policy declares" +exit 0 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/autotest/testcase/probe/xcatmn b/xCAT-test/autotest/testcase/probe/xcatmn new file mode 100644 index 0000000000..fc4ac30736 --- /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 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 -H 2>&1 +check:output=~Checking SELinux policy for xCAT\.\.\..*\[ OK \] +check:output!~Checking SELinux policy for xCAT\.\.\..*\[FAIL\] +end diff --git a/xCAT-test/autotest/testcase/selinux/cases0 b/xCAT-test/autotest/testcase/selinux/cases0 new file mode 100644 index 0000000000..ebf95660ea --- /dev/null +++ b/xCAT-test/autotest/testcase/selinux/cases0 @@ -0,0 +1,155 @@ +start:selinux_xcatd_domain +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=~:xcat_t: +cmd:ps -eo label,args | grep '[x]catd:' +check:rc==0 +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: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 +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: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 --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.ck /tmp/selinux_client_domain.err +check:rc==0 +end + +start:selinux_mn_labels +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 +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' +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:]].*)?"' +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 --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: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 '/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 --since /tmp/selinux_mn_control.avcck' +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.ck /tmp/selinux_mn_labels.avc /tmp/selinux_mn_labels.avcck /tmp/selinux_mn_control.avcck +end + +start:selinux_restapi_avc +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 +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' +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 +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 --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: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.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 new file mode 100644 index 0000000000..defdf7c18c --- /dev/null +++ b/xCAT-test/autotest/testcase/selinux/cases1 @@ -0,0 +1,207 @@ +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. 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 '/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 +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 -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" +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 --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.avcck +end + +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: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 cat /proc/cmdline +check:rc==0 +check:output=~selinux=0 +cmd:xdsh $$CN getenforce +check:rc==0 +check:output=~Disabled +cmd:chdef -t node -o $$CN selinux= +check:rc==0 +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 + +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. The labels of /xcatpost are reported and not asserted, as on a compute node +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 /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 +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:genimage $$STATELITE +check:rc==0 +cmd:liteimg $$STATELITE +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/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 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/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/bats/postinstall_selinux_config.bats b/xCAT-test/bats/postinstall_selinux_config.bats new file mode 100644 index 0000000000..ec0cb51f05 --- /dev/null +++ b/xCAT-test/bats/postinstall_selinux_config.bats @@ -0,0 +1,120 @@ +#!/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"* ]] + [[ "$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" { + 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 +} 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 + ' +} diff --git a/xCAT-test/bats/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats new file mode 100644 index 0000000000..614a3c7135 --- /dev/null +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -0,0 +1,162 @@ +#!/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"'* ]] +} + +# 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" + [ -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 ] +} + +@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" == *"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" ] +} 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/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(); 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); diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 71401eaa8c..da1f1d859c 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -56,11 +56,18 @@ 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 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 @@ -199,6 +206,35 @@ generates disposable SSH keys and checks their installation through the real scr These tests do not perform an installation, capture a kernel crash or modify host accounts. +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. + +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. @@ -259,6 +295,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 @@ -374,6 +411,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 +424,21 @@ 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. +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. Architecture names in these fixtures do not qualify native firmware or boot 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; 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; 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/netboot_profile_postinstall.t b/xCAT-test/native/netboot_profile_postinstall.t new file mode 100644 index 0000000000..b481b4ecea --- /dev/null +++ b/xCAT-test/native/netboot_profile_postinstall.t @@ -0,0 +1,201 @@ +#!/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 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::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 %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); + +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" ], +); + +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' ); + } + }; + } + } +} + +done_testing(); diff --git a/xCAT-test/native/netboot_profile_riscv64.t b/xCAT-test/native/netboot_profile_riscv64.t index be5109d4c9..d993577a22 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"); @@ -88,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"); } 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"); diff --git a/xCAT-test/native/release_repository.t b/xCAT-test/native/release_repository.t index dc131a98e5..3e07b70bae 100644 --- a/xCAT-test/native/release_repository.t +++ b/xCAT-test/native/release_repository.t @@ -1,9 +1,11 @@ #!/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); +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; @@ -55,13 +57,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 +89,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 { @@ -100,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", @@ -134,17 +219,50 @@ 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 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) = @_; + 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]) { + check_package_index(@$entry, $label); } if ($signed) { for my $repo ($directory, "$directory/SRPMS") { @@ -153,5 +271,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"); } } diff --git a/xCAT-test/native/selinux_file_contexts.t b/xCAT-test/native/selinux_file_contexts.t new file mode 100644 index 0000000000..44bea1c0ce --- /dev/null +++ b/xCAT-test/native/selinux_file_contexts.t @@ -0,0 +1,219 @@ +#!/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(); + +# 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', +); + +# 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/$_" } @published_names; +} @images; + +# 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, @custom_published) { + 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 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. +my $mn = "$work/mn"; +my %before; +$before{$_} = 'shadow_t' foreach @guest; +$before{$_} = 'etc_t' foreach @guest_dirs; +$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"; + 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); +} + +#--- + +=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, @guest_dirs, @custom_published) { + 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/native/selinux_image_repair.t b/xCAT-test/native/selinux_image_repair.t new file mode 100644 index 0000000000..0128b73de7 --- /dev/null +++ b/xCAT-test/native/selinux_image_repair.t @@ -0,0 +1,338 @@ +#!/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; + + # 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. + 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 $step ('repair', 'host relabel', 'policy upgrade') { + 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}"); + } + } +} + +# 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 { + 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 +# 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 { + 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/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 + ' +} diff --git a/xCAT-test/native/xcatd_relocated_startup.t b/xCAT-test/native/xcatd_relocated_startup.t new file mode 100644 index 0000000000..db0bb10062 --- /dev/null +++ b/xCAT-test/native/xcatd_relocated_startup.t @@ -0,0 +1,180 @@ +#!/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'); + }; +} + +# %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(); 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: diff --git a/xCAT-test/unit/destiny_chain_advance.t b/xCAT-test/unit/destiny_chain_advance.t index b946815c28..f70d21469a 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 } }, @@ -208,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}) }; @@ -245,4 +329,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(); 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/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; 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(); 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(); 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..1f65b971a9 --- /dev/null +++ b/xCAT-test/unit/mknb_genesis_selinux_context.t @@ -0,0 +1,113 @@ +#!/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, $error) = 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, error => $error, 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 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}); +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'); + +done_testing(); 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; 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..dab748e531 --- /dev/null +++ b/xCAT-test/unit/mysqlsetup_bind_address_label.t @@ -0,0 +1,142 @@ +#!/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; + +# 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 +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(); 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(); 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/probe_xcatmn_selinux_case.t b/xCAT-test/unit/probe_xcatmn_selinux_case.t new file mode 100644 index 0000000000..921897b70e --- /dev/null +++ b/xCAT-test/unit/probe_xcatmn_selinux_case.t @@ -0,0 +1,88 @@ +#!/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; +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 +# 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'); + +# 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/, + "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(); diff --git a/xCAT-test/unit/selinux_bundle.t b/xCAT-test/unit/selinux_bundle.t new file mode 100644 index 0000000000..7b9fdf06d9 --- /dev/null +++ b/xCAT-test/unit/selinux_bundle.t @@ -0,0 +1,38 @@ +#!/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|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(); diff --git a/xCAT-test/unit/selinux_docs.t b/xCAT-test/unit/selinux_docs.t new file mode 100644 index 0000000000..28fe44e96f --- /dev/null +++ b/xCAT-test/unit/selinux_docs.t @@ -0,0 +1,85 @@ +#!/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"); +} + +# 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"); +} + +# 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'); + +done_testing(); 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..98f9ff22d9 --- /dev/null +++ b/xCAT-test/unit/selinux_el_only_scope.t @@ -0,0 +1,85 @@ +#!/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 +); +# 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 + 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', 20 unless $decides; + + foreach my $target (@openeuler_targets, @opensuse_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"); + is($decides->($pkg, 'opensuse-leap-15.6-x86_64'), undef, + "$pkg is built for openSUSE"); + } +} + +# 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(); diff --git a/xCAT-test/unit/selinux_kickstart_template.t b/xCAT-test/unit/selinux_kickstart_template.t new file mode 100644 index 0000000000..0d7bd71b2b --- /dev/null +++ b/xCAT-test/unit/selinux_kickstart_template.t @@ -0,0 +1,128 @@ +#!/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"); + + # 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]"); + } + } +} + +# 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..3850869660 --- /dev/null +++ b/xCAT-test/unit/selinux_netboot_kcmdline.t @@ -0,0 +1,73 @@ +#!/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::Find (); +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'); + +# 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); + +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"); + } +} + +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(); 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(); 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(); 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/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(); 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; 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(); diff --git a/xCAT-test/unit/xcat_selinux_package.t b/xCAT-test/unit/xcat_selinux_package.t new file mode 100644 index 0000000000..e501ef7d55 --- /dev/null +++ b/xCAT-test/unit/xcat_selinux_package.t @@ -0,0 +1,322 @@ +#!/usr/bin/env perl +use strict; +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 +# 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'); +# 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'); +# 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"); +} + +my @fc = grep { !/^\s*(?:#|$)/ } lines_of("$root/xCAT-selinux/xcat.fc"); +my %fc = map { (split /\s+/, $_, 2) } @fc; +# 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. +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. +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'); + + +######################################## +# +# 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'); +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'); +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'); + +# 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)) { + 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'); + +# 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/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'); + +# 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 +# listens on the network must not hold that authority. +# 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 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)) { + 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(); diff --git a/xCAT-test/unit/xcatconfig_selinux_policy.t b/xCAT-test/unit/xcatconfig_selinux_policy.t new file mode 100644 index 0000000000..74e5e95ec7 --- /dev/null +++ b/xCAT-test/unit/xcatconfig_selinux_policy.t @@ -0,0 +1,193 @@ +#!/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'); +} + +# 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(); 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..3f06e8aff6 --- /dev/null +++ b/xCAT-test/unit/xcatd_service_direct_exec.t @@ -0,0 +1,66 @@ +#!/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, 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] // ''); +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"); +} + +# 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(); 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'); 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 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 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 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 diff --git a/xCATsn/xCATsn.spec b/xCATsn/xCATsn.spec index ec36669c10..cea6eeda81 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} +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