← Back
Editing: CheckIP.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 (RequireUseWarnings, ProhibitExplicitReturnUndef, ProhibitMixedBooleanOperators, RequireBriefOpen) # start main package ConfigServer::CheckIP; use strict; use lib '/usr/local/csf/lib'; use Carp; use Net::IP; use ConfigServer::Config; use Exporter qw(import); our $VERSION = 1.04; our @ISA = qw(Exporter); our @EXPORT_OK = qw(checkip cccheckip validate_port validate_uid valid_adport_prefix); my $ipv4reg = ConfigServer::Config->ipv4reg; my $ipv6reg = ConfigServer::Config->ipv6reg; # Length caps for the advanced rule field validators below. The character # classes alone accept an arbitrarily long value, which cannot inject anything # but does reach an iptables command line and the log, where csf.pl printsafe() # and lfd.pl logsafe() truncate a rejection sample at 120 characters. Cap the # validators to match so an oversized field is refused up front rather than # passed on and then reported in truncated form. # # The limits are set well above anything legitimate. iptables accepts at most 15 # ports in a multiport list, so the longest real port field is 15 five digit # ports plus separators (89 characters); a UID is at most 10 digits and a user # name at most 32. A fused prefix+IP is the sum of a full rule's fields plus an # IPv6 address with a mask, so it gets a larger cap of its own our $MAX_FIELD_LENGTH = 120; our $MAX_PREFIX_LENGTH = 256; # end main ############################################################################### # start checkip sub checkip { my ($ipin,$opts) = @_; my $ret = 0; my $ipref = 0; my $ip; my $cidr; my $value; # A "/0" mask means "every address". It is legitimate in the root owned # csf.allow/csf.deny files, where a blanket deny paired with a tight allow # list is an established lockdown technique, so the callers that handle that # content opt in with allow_zero_mask. It stays rejected by default, and so # for remote feed data: iptables expands "1.2.3.4/0" to 0.0.0.0/0, and # because GALLOWIN is inserted ahead of the deny chains a single such # GLOBAL_ALLOW entry would short-circuit every deny rule on the server my $minmask = ($opts and $opts->{allow_zero_mask}) ? 0 : 1; if (ref $ipin) { $value = ${$ipin}; $ipref = 1; } else { $value = $ipin; } # Split with a negative limit so trailing fields are preserved; a valid # value is at most "ip/cidr". Reject anything with extra fields, otherwise # data after a second "/" is silently dropped from validation yet retained # in the caller's value and can reach a shell command my @parts = split(/\//,$value,-1); return 0 if @parts > 2; ($ip,$cidr) = @parts; my $testip = $ip; # A "/" with no mask after it is malformed. Anchor with \z so a trailing # newline cannot ride along on the mask if (@parts == 2) { return 0 unless (length $cidr and $cidr =~ /\A\d+\z/); } if ($ip =~ /\A$ipv4reg\z/) { $ret = 4; # Test "length" rather than truthiness: a "/0" mask is a false value, # so a truthiness test skips the range check entirely and lets # "1.2.3.4/0" through as a clean IPv4 - which iptables expands to # 0.0.0.0/0, matching every address if (length $cidr) { unless ($cidr >= $minmask && $cidr <= 32) {return 0} } if ($ip eq "127.0.0.1") {return 0} } if ($ip =~ /\A$ipv6reg\z/) { $ret = 6; if (length $cidr) { unless ($cidr >= $minmask && $cidr <= 128) {return 0} } $ip =~ s/://g; $ip =~ s/^0*//g; if ($ip == 1) {return 0} if ($ipref) { eval { local $SIG{__DIE__} = undef; my $netip = Net::IP->new($testip); my $myip = $netip->short(); if ($myip ne "") { if ($cidr eq "") { ${$ipin} = $myip; } else { ${$ipin} = $myip."/".$cidr; } } }; if ($@) {return 0} } } return $ret; } # end checkip ############################################################################### # start cccheckip sub cccheckip { my ($ipin,$opts) = @_; my $ret = 0; my $ipref = 0; my $ip; my $cidr; my $value; # See checkip(): a "/0" mask is rejected unless the caller is handling # root owned local allow/deny content and opts in my $minmask = ($opts and $opts->{allow_zero_mask}) ? 0 : 1; if (ref $ipin) { $value = ${$ipin}; $ipref = 1; } else { $value = $ipin; } # Split with a negative limit so trailing fields are preserved; a valid # value is at most "ip/cidr". Reject anything with extra fields, otherwise # data after a second "/" is silently dropped from validation yet retained # in the caller's value and can reach a shell command my @parts = split(/\//,$value,-1); return 0 if @parts > 2; ($ip,$cidr) = @parts; my $testip = $ip; # A "/" with no mask after it is malformed. Anchor with \z so a trailing # newline cannot ride along on the mask if (@parts == 2) { return 0 unless (length $cidr and $cidr =~ /\A\d+\z/); } if ($ip =~ /\A$ipv4reg\z/) { $ret = 4; # Test "length" rather than truthiness: a "/0" mask is a false value, # so a truthiness test skips the range check entirely and lets # "8.8.8.8/0" through as a clean IPv4 - which iptables expands to # 0.0.0.0/0, matching every address if (length $cidr) { unless ($cidr >= $minmask && $cidr <= 32) {return 0} } if ($ip eq "127.0.0.1") {return 0} my $type; eval { local $SIG{__DIE__} = undef; my $netip = Net::IP->new($testip); $type = $netip->iptype(); }; if ($@) {return 0} if ($type ne "PUBLIC") {return 0} } if ($ip =~ /\A$ipv6reg\z/) { $ret = 6; if (length $cidr) { unless ($cidr >= $minmask && $cidr <= 128) {return 0} } $ip =~ s/://g; $ip =~ s/^0*//g; if ($ip == 1) {return 0} if ($ipref) { eval { local $SIG{__DIE__} = undef; my $netip = Net::IP->new($testip); my $myip = $netip->short(); if ($myip ne "") { if ($cidr eq "") { ${$ipin} = $myip; } else { ${$ipin} = $myip."/".$cidr; } } }; if ($@) {return 0} } } return $ret; } # end cccheckip ############################################################################### # start validate_port # Validates a port field from an advanced allow/deny rule before it is # interpolated into an iptables command. Accepts a single port, an underscore or # colon separated range, a comma separated multiport list, or an ICMP type name # or numeric "type/code" pair. Rejects anything containing whitespace or shell # metacharacters, anything beginning with "-" so the value cannot reach iptables # as an option instead of as an argument, and anything over the length cap sub validate_port { my $port = shift; return 0 unless defined $port; return 0 unless length $port; return 0 if length $port > $MAX_FIELD_LENGTH; # "/" is permitted for the iptables ICMP "type/code" form (see # iptables-extensions --icmp-type). It is not a shell metacharacter, and # checkip()/cccheckip() separately reject any bare IP with more than one # "/", so allowing it here does not widen the injection surface. # # The first character may not be "-", or the value is passed to iptables as # an option rather than as the argument to --dport. A leading ":" stays # legal for the open ended ":3000" range form. Anchored with \z rather than # $ so a trailing newline cannot terminate the generated command early return ($port =~ /\A[A-Za-z0-9_,:\/][A-Za-z0-9_,:\/-]*\z/) ? 1 : 0; } # end validate_port ############################################################################### # start validate_uid # Validates a UID/GID owner field from an advanced allow/deny rule before it is # interpolated into an iptables command. Accepts a numeric id or an account # name; rejects anything containing whitespace or shell metacharacters, anything # beginning with "-" so the value cannot reach iptables as an option instead of # as an argument, and anything over the length cap sub validate_uid { my $uid = shift; return 0 unless defined $uid; return 0 unless length $uid; return 0 if length $uid > $MAX_FIELD_LENGTH; # The first character may not be "-", or the value is passed to iptables as # an option rather than as the argument to --uid-owner. Anchored with \z # rather than $ so a trailing newline cannot terminate the generated # command early return ($uid =~ /\A[A-Za-z0-9_.][A-Za-z0-9_.-]*\z/) ? 1 : 0; } # end validate_uid ############################################################################### # start valid_adport_prefix # Validates an advanced allow/deny rule fragment before it is interpolated into # an iptables command via linefilter(). Used for the (Global) DynDNS feed # supplied prefix (e.g. "tcp|in|d=22|s=") and for the persisted # csf.tempdyn/csf.tempgdyn entries, where the prefix and the resolved IP have # been fused into a single field (e.g. "tcp|in|d=22|s=203.0.113.5"). # # The character class is the union of what the field validators accept: # validate_port() ([A-Za-z0-9_,:/-], permitting ICMP type names and the numeric # "type/code" form) and validate_uid() ([A-Za-z0-9_.-]), plus the "|" and "=" # separators and "." for the IP. As with those validators a leading "-" is # rejected so the value cannot reach iptables as an option. The length cap is # $MAX_PREFIX_LENGTH rather than $MAX_FIELD_LENGTH because a fused value carries # every field of a rule plus an IPv6 address and mask. # # NOTE: unlike upstream 16.30, an undefined or empty value is rejected here. # Callers that treat an absent prefix as legitimate (a bare FQDN/IP) must test # for that themselves before calling this sub valid_adport_prefix { my $prefix = shift; return 0 unless defined $prefix; return 0 unless length $prefix; return 0 if length $prefix > $MAX_PREFIX_LENGTH; # The first character may not be "-", so that neither the prefix nor a # fused prefix+IP can reach iptables as an option. A leading ":" stays legal # because a persisted csf.tempdyn/csf.tempgdyn entry may be a bare # compressed IPv6 address. Anchored with \z rather than $ so a trailing # newline cannot terminate the generated command early return ($prefix =~ /\A[A-Za-z0-9_,.:|=\/][A-Za-z0-9_,.:|=\/-]*\z/) ? 1 : 0; } # end valid_adport_prefix ############################################################################### 1;
Save File
Cancel