← Back
Editing: KernelModules.pm
############################################################################### # Copyright (C) 2006-2025 Jonathan Michaelson # # https://github.com/waytotheweb/scripts # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, see <https://www.gnu.org/licenses>. ############################################################################### ## no critic (ProhibitExplicitReturnUndef, ProhibitMixedBooleanOperators) # start main # # ConfigServer::KernelModules - netfilter kernel module availability checks # # Reports whether the modules iptables needs are available to the running # kernel, by reading /proc/modules and the module index under # /lib/modules/<release>/ rather than by loading anything. # # EL10 moved nft_compat and the legacy xt_*/ipt_*/ip_set_* modules from # kernel-modules-core into kernel-modules-extra, which is not installed by # default. A server without it gets one "Extension <x> revision 0 not # supported" warning per extension and no firewall, which is what # missing_module_advice() exists to translate into a single actionable line. # # The split is EL10-only, so on EL7/8/9 (and on any release this cannot # identify as EL10) the check is a no-op that reports nothing missing. # package ConfigServer::KernelModules; use strict; use warnings; use lib '/usr/local/csf/lib'; use Exporter qw(import); our $VERSION = 1.00; our @ISA = qw(Exporter); our @EXPORT_OK = qw(missing_module_advice autoinstall_required_modules); # Modules iptables-nft needs before any CSF rule will load my @required = qw(nft_compat xt_conntrack xt_multiport); our $moduledir = "/lib/modules"; our $loadedfile = "/proc/modules"; our $releasefile = "/proc/sys/kernel/osrelease"; our $osreleasefile = "/etc/os-release"; our $redhatfile = "/etc/redhat-release"; # One attempt per day at most on persistently broken hosts, cPanel's # KMOD_REMEDIATION_SCHEDULED lesson: a boot that cannot reach dnf must not # hammer it with a retry on every start our $statefile = "/var/lib/csf/csf.kmod-remediation"; our $installtimeout = 180; # The first EL major version where the kernel-modules-extra split applies my $splitmajor = 10; my %index_cache; my %dep_read_cache; my $elmajor_cache; my $elmajor_done = 0; # end main ############################################################################### # start module_available # my $ok = ConfigServer::KernelModules::module_available("nft_compat"); # # Returns 1 when the module is available to the running kernel (loaded, built # in, or present on disk), 0 when it is not, and 1 when the module index # cannot be read at all, so an unreadable index never reads as a fault sub module_available { my ($module) = @_; $module = "" unless defined $module; return 1 unless length $module; # A resident module works even when its files belong to another kernel # version, which is the state a kernel upgrade leaves behind until reboot return 1 if &_module_loaded($module); my $index = &_module_index(); return 1 unless keys %{$index}; # modules.dep is the only index of loadable modules. If it could not be # read (no depmod run, or /lib/modules/<release> trimmed to builtins only) # the index holds builtins only, so a loadable module such as nft_compat # reads as "missing" even when its .ko is present on disk - which would # print false install advice on every failed start. Fail open instead. # EL10-only in practice: missing_required_modules() gates on elmajor >= 10 # before this is reached for the advice text return 1 unless &_modules_dep_read(); return $index->{$module} ? 1 : 0; } # end module_available ############################################################################### # start missing_required_modules # my @missing = ConfigServer::KernelModules::missing_required_modules(); # # Returns the subset of @required that is unavailable to the running kernel, in # the same order as @required, or an empty list when nothing is missing, when # the module index cannot be read, or when this is not an EL10 or later server sub missing_required_modules { my $elmajor = &_el_major(); return () unless (defined $elmajor and $elmajor >= $splitmajor); return grep {!&module_available($_)} @required; } # end missing_required_modules ############################################################################### # start required_modules_available # Returns 1 when nothing is missing, 0 when at least one required module is # unavailable. An explicit boolean, unlike missing_required_modules(), whose # truthiness in scalar context is an incidental side effect of grep sub required_modules_available { return &missing_required_modules() ? 0 : 1; } # end required_modules_available ############################################################################### # start remediation_package # Names the package that provides the required modules for the running kernel, # regardless of whether anything is actually missing. This fork targets # CentOS 7 and AlmaLinux/Rocky 8/9/10 only, so there is no Debian variant sub remediation_package { my $release = &_running_release(); return length $release ? "kernel-modules-extra-$release" : "kernel-modules-extra"; } # end remediation_package ############################################################################### # start remediation_command # Names the full command that installs remediation_package(), so installer # selection lives in one place rather than in each caller. EL7 has no dnf, so # it gets yum; EL8 and later get dnf sub remediation_command { my $package = &remediation_package(); my $elmajor = &_el_major(); my $installer = (defined $elmajor and $elmajor <= 7) ? "yum" : "dnf"; return "$installer install $package"; } # end remediation_command ############################################################################### # start missing_module_advice # Builds a diagnostic naming the package that owns the missing modules, for # printing after a failed ruleset load. Returns a multi-line string ending in a # newline when required modules are missing, or an empty string when nothing is # missing or the module index cannot be read sub missing_module_advice { my @missing = &missing_required_modules(); return "" unless @missing; my $release = &_running_release(); my $text = "*ERROR* The running kernel ($release) has no ".join(", ",@missing)." module(s), so iptables cannot load any rule.\n"; $text .= " Install the package that provides them for the running kernel, then restart csf:\n"; $text .= " ".&remediation_command()."\n"; $text .= " kernel-debug-modules-extra does not provide them for this kernel.\n"; $text .= " A reboot is needed if the package installs for a different kernel version.\n"; return $text; } # end missing_module_advice ############################################################################### # start autoinstall_required_modules # my $ok = ConfigServer::KernelModules::autoinstall_required_modules(); # # EL10 self-heal: installs the package that provides the required modules when # they are missing, so a fresh EL10 server's first start loads its ruleset # instead of failing with the missing-module advice (which the caller still # prints on failure, unchanged). Returns 1 when the required modules are # available after this call, 0 when skipped or the install failed - the caller # proceeds to load either way. # # Gates, in order: # 1. EL10 or later (_el_major) - EL7/8/9 and unidentifiable hosts are a # no-op, byte-identical to before this feature # 2. missing_required_modules() - healthy hosts cost one modules.dep scan # (cached), no rpm, no yum; an unreadable module index fails open here # (module_available returns 1), so it never triggers an install # 3. State file - skip when written less than 24h ago, so a persistently # broken host gets at most one attempt per day # 4. Install - timeout(1) bound plus dnf's own connect/retry timeouts, so a # network-less boot costs at most a bounded delay and then falls through # to the unchanged loud failure # 5. Re-check - success unlinks the state file and prints confirmation; # failure writes it so the 24h gate applies to the next start # # The command string is built internally (remediation_command() plus the # running release), no user input, distro-signed package only. gated by # CSF_KMOD_AUTOINSTALL at the call sites in csf.pl sub autoinstall_required_modules { my $elmajor = &_el_major(); return 0 unless (defined $elmajor and $elmajor >= $splitmajor); return 0 unless &missing_required_modules(); if (-f $statefile) { my @stat = stat ($statefile); return 0 if @stat and (time - $stat[9]) < 86400; } my $package = &remediation_package(); print "*NOTICE* EL10: required iptables module(s) missing - installing $package for the running kernel\n"; my $status = system ("timeout $installtimeout ".&remediation_command()." -y"); if ($status == 0 and !&missing_required_modules()) { unlink $statefile; print "*NOTICE* $package installed - the required modules are now available\n"; return 1; } # Failed install (no network at boot, repo down, elrepo/custom kernel with # the modules built in): remember the attempt so a wedged boot does not # hammer dnf on every start - the 24h state-file gate above open (my $STATE, ">", $statefile) or return 0; print $STATE "kernel-modules-extra autoinstall attempt\n"; close ($STATE); return 0; } # end autoinstall_required_modules ############################################################################### # start _module_loaded sub _module_loaded { my ($module) = @_; $module = "" unless defined $module; return 0 unless length $module; return 0 unless -f $loadedfile; # Deliberately not ConfigServer::Slurp: it carps and then flocks an undef # handle when sysopen fails, which dies. This is called from error() in # csf.pl, where a die loses the actual error the operator needs to see open (my $LOADED, "<", $loadedfile) or return 0; while (my $line = <$LOADED>) { my ($name) = split(/\s+/,$line); if (defined $name and length $name and $name eq $module) { close ($LOADED); return 1; } } close ($LOADED); return 0; } # end _module_loaded ############################################################################### # start _running_release sub _running_release { return "" unless -f $releasefile; open (my $RELEASE, "<", $releasefile) or return ""; my $release = <$RELEASE>; close ($RELEASE); $release = "" unless defined $release; $release =~ s/^\s+|\s+$//g; return $release; } # end _running_release ############################################################################### # start _module_index sub _module_index { my $release = &_running_release(); return $index_cache{$release} if exists $index_cache{$release}; my %present; my $dep_read = 0; foreach my $name ("modules.dep","modules.builtin") { my $path = "$moduledir/$release/$name"; next unless -f $path; open (my $INDEX, "<", $path) or next; $dep_read = 1 if $name eq "modules.dep"; while (my $line = <$INDEX>) { while ($line =~ m{([A-Za-z0-9_-]+)[.]ko}gxms) {$present{$1} = 1} } close ($INDEX); } $index_cache{$release} = \%present; $dep_read_cache{$release} = $dep_read; return $index_cache{$release}; } # end _module_index ############################################################################### # start _modules_dep_read # Whether modules.dep was readable for the running kernel. The loadable-module # index lives in modules.dep; modules.builtin only names compiled-in modules, so # a non-empty builtins-only index is not enough to call a loadable module # missing. module_available() therefore fails open when this is false sub _modules_dep_read { my $release = &_running_release(); return $dep_read_cache{$release} ? 1 : 0; } # end _modules_dep_read ############################################################################### # start _el_major # Returns the Enterprise Linux major version, or undef when it cannot be # determined or when this is not an EL server. Fork-local: upstream branched on # /etc/debian_version instead, which is dead code here since this fork only # targets EL7 through EL10 sub _el_major { return $elmajor_cache if $elmajor_done; my ($major, $id, $idlike); if (-f $osreleasefile) { if (open (my $OSRELEASE, "<", $osreleasefile)) { while (my $line = <$OSRELEASE>) { if ($line =~ /^VERSION_ID\s*=\s*"?(\d+)/) {$major = $1} elsif ($line =~ /^ID\s*=\s*"?([^"\s]*)/) {$id = $1} elsif ($line =~ /^ID_LIKE\s*=\s*"?([^"\r\n]*?)"?\s*$/) {$idlike = $1} } close ($OSRELEASE); } # VERSION_ID alone is not enough: Debian 13, Ubuntu 24.04, Fedora and # Amazon Linux 2023 (ID_LIKE=fedora, VERSION_ID=2023) would all otherwise # open the EL10 gate and be advised to install a package they do not ship. # Trust VERSION_ID only when ID/ID_LIKE names a known EL family. 'fedora' # is intentionally excluded - every EL release matches on its own ID # (centos/almalinux/rocky/rhel/ol) even though ID_LIKE usually contains # 'fedora'. No bare '-f $redhatfile' shortcut here either: Fedora ships # /etc/redhat-release, so that would re-open the gate. The only trust of # $redhatfile is the fallback below, which rejects Fedora content if (defined $major) { $id = "" unless defined $id; $idlike = "" unless defined $idlike; undef $major unless ("$id $idlike" =~ /\b(?:rhel|centos|almalinux|rocky|ol)\b/i); } } if (!defined $major and -f $redhatfile) { if (open (my $REDHAT, "<", $redhatfile)) { my $line = <$REDHAT>; close ($REDHAT); $line = "" unless defined $line; # /etc/redhat-release is the canonical EL detector, but Fedora also # ships one ("Fedora release N"). Fedora is not an EL target, so reject # it here too - this is the only path that trusts $redhatfile if ($line =~ /release\s+(\d+)/ and $line !~ /Fedora/i) {$major = $1} } } $elmajor_cache = $major; $elmajor_done = 1; return $elmajor_cache; } # end _el_major ############################################################################### 1;
Save File
Cancel