diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 633154e3f7..f2911b4cfe 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -128,10 +128,31 @@ jobs: - name: Enable lifecycle test namespaces run: sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - name: Test RPM package lifecycle - run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/xcatd_rpm_lifecycle.t xCAT-test/native/apache_rpm_configuration.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t' + run: su -s /bin/sh nobody -c 'prove -v xCAT-test/native/xcatd_rpm_lifecycle.t xCAT-test/native/xcatd_relocated_startup.t xCAT-test/native/apache_rpm_configuration.t xCAT-test/native/apache_package_lifecycle.t xCAT-test/native/package_upgrade_logging.t xCAT-test/native/profile_package_payload.t' - 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 684231c62d..fb9138de19 100644 --- a/build-utils/lib/XCAT/BuildUtils.pm +++ b/build-utils/lib/XCAT/BuildUtils.pm @@ -43,7 +43,7 @@ our @EXPORT_OK = qw( rewrite_file write_script read_line buildinfo_text targetarch_from_target - openeuler_build_target openeuler_repo_subdir + openeuler_build_target openeuler_repo_subdir package_skip_reason mock_config_text mock_build_owner prepare_mock_resultdirs genesis_chroot_name genesis_target_arch genesis_build_plan genesis_log_errors genesis_log_deny_rules deb_belongs_to_dist @@ -807,28 +807,56 @@ sub cancel_build { sub DESTROY { shift->release } } -# The packages a target does not build, and why. Each rule names the package and -# the target-name prefixes that do not build it. +# 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); + 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 grep { index($target, $_) == 0 } @{ $skip->{prefixes} }; + if $skip->{prefixes} + && grep { index($target, $_) == 0 } @{ $skip->{prefixes} }; } return undef; } diff --git a/buildrpms.pl b/buildrpms.pl index 95c7655691..1878f63fc4 100755 --- a/buildrpms.pl +++ b/buildrpms.pl @@ -137,6 +137,7 @@ my @PACKAGES = qw( xCAT-openbmc-py xCAT-probe xCAT-rmc + xCAT-selinux xCAT-server xCAT-test xCAT-vlan 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/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-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/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 8057490eb2..993dae39b1 100644 --- a/xCAT-server/lib/xcat/plugins/anaconda.pm +++ b/xCAT-server/lib/xcat/plugins/anaconda.pm @@ -19,6 +19,7 @@ use xCAT::MsgUtils; use xCAT::SvrUtils; use xCAT::UFTP; use xCAT::Yum; +use xCAT::SELinux; use Getopt::Long; Getopt::Long::Configure("bundling"); @@ -390,6 +391,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; @@ -975,10 +979,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) { @@ -1113,6 +1122,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; @@ -1411,6 +1421,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/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/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/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' + +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/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/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/selinux_avc_check.bats b/xCAT-test/bats/selinux_avc_check.bats new file mode 100644 index 0000000000..060ec143b0 --- /dev/null +++ b/xCAT-test/bats/selinux_avc_check.bats @@ -0,0 +1,137 @@ +#!/usr/bin/env bats +# +# The classifier that decides which SELinux denials xCAT is answerable for. The records +# below are real: they were captured on an enforcing AlmaLinux 10 management node while a +# compute node was provisioned. + +load 'helpers/shell_source' + +setup() +{ + . "$(repo_path 'xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh')" +} + +classify() +{ + printf '%s\n' "$@" | selinux_avc_classify +} + +count_kept() +{ + printf '%s\n' "$@" | selinux_avc_classify | grep -c '^type=' +} + +# httpd serving /tftpboot through the xcat.conf AliasMatch. This is the one the xcat +# policy module exists for, so a denial here is xCAT's. +XCAT_RECORD='type=AVC msg=audit(1759000000.111:222): avc: denied { getattr } for pid=1234 comm="httpd" path="/tftpboot/xcat/xnba.kpxe" dev="vda2" ino=55 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:shadow_t:s0 tclass=file permissive=0' + +# httpd asking for net_admin on itself, every ten seconds, on an idle node. 817 of 1034 +# denials on one node in one day were this shape. +TIMER_RECORD='type=AVC msg=audit(1759000001.222:333): avc: denied { net_admin } for pid=2345 comm="httpd" scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:system_r:httpd_t:s0 tclass=capability permissive=0' + +# An ordinary ssh login. cluster-test.pl makes one on every step. +SSH_RECORD='type=AVC msg=audit(1759000002.333:444): avc: denied { siginh } for pid=3456 comm="sshd" scontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tcontext=system_u:system_r:sshd_session_t:s0-s0:c0.c1023 tclass=process permissive=0' + +@test "a denial on an xCAT directory is kept" { + run classify "$XCAT_RECORD" + [ "$status" -eq 0 ] + [[ "$output" == *'/tftpboot/xcat/xnba.kpxe'* ]] +} + +@test "the httpd net_admin timer is not kept" { + run classify "$TIMER_RECORD" + [ -z "$output" ] +} + +@test "an ssh login denial is not kept" { + run classify "$SSH_RECORD" + [ -z "$output" ] +} + +@test "one xCAT denial among the noise is found and counted once" { + run count_kept "$TIMER_RECORD" "$XCAT_RECORD" "$SSH_RECORD" "$TIMER_RECORD" + [ "$status" -eq 0 ] + [ "$output" = "1" ] +} + +@test "a window of noise alone is kept empty" { + run classify "$TIMER_RECORD" "$SSH_RECORD" + [ -z "$output" ] +} + +@test "a denial by an xCAT program is kept whatever the path" { + local record='type=AVC msg=audit(1759000003.444:555): avc: denied { read } for pid=4567 comm="genimage" name="dracut.conf" scontext=system_u:system_r:unconfined_service_t:s0 tcontext=system_u:object_r:etc_t:s0 tclass=file permissive=0' + run classify "$record" + [ "$status" -eq 0 ] + [[ "$output" == *'comm="genimage"'* ]] +} + +@test "a program whose name merely contains a kept word is not matched by accident" { + local record='type=AVC msg=audit(1759000004.555:666): avc: denied { execute } for pid=5678 comm="systemd-udevd" scontext=system_u:system_r:udev_t:s0 tcontext=system_u:object_r:bin_t:s0 tclass=file permissive=0' + run classify "$record" + [ -z "$output" ] +} + +@test "the report refuses a call with no start time" { + run "$(repo_path 'xCAT-test/autotest/testcase/commoncmd/selinux_avc_check.sh')" + [ "$status" -eq 2 ] +} + +@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/native/README.md b/xCAT-test/native/README.md index b1f5e5d73a..786f13f5bc 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -200,6 +200,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. @@ -260,6 +289,7 @@ On EL8 or EL10, install `bubblewrap`, `rpm-build`, `systemd`, `chkconfig`, ``` prove xCAT-test/native/xcatd_rpm_lifecycle.t \ + xCAT-test/native/xcatd_relocated_startup.t \ xCAT-test/native/apache_rpm_configuration.t \ xCAT-test/native/apache_package_lifecycle.t \ xCAT-test/native/package_upgrade_logging.t diff --git a/xCAT-test/native/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/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/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/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/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/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