add dport: factor out ICMP-type validity checking
authorThomas Lamprecht <t.lamprecht@proxmox.com>
Mon, 4 May 2020 12:13:23 +0000 (14:13 +0200)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Mon, 4 May 2020 12:13:30 +0000 (14:13 +0200)
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
src/PVE/Firewall.pm

index a6157e3..eadfc6b 100644 (file)
@@ -812,6 +812,17 @@ my $icmpv6_type_names = {
     'redirect' => 1,
 };
 
+my $is_valid_icmp_type = sub {
+    my ($type, $valid_types) = @_;
+
+    if ($type =~ m/^\d+$/) {
+       # values for icmp-type range between 0 and 255 (8 bit field)
+       die "invalid icmp-type '$type'\n" if $type > 255;
+    } else {
+       die "unknown icmp-type '$type'\n" if !defined($valid_types->{$type});
+    }
+};
+
 sub init_firewall_macros {
 
     $pve_fw_parsed_macros = {};
@@ -2041,21 +2052,12 @@ sub ipt_rule_to_cmds {
            my $add_dport = sub {
                return if !defined($rule->{dport});
 
+               # NOTE: we re-use dport to store --icmp-type for icmp* protocol
                if ($proto eq 'icmp') {
-                   # Note: we use dport to store --icmp-type
-                   die "unknown icmp-type '$rule->{dport}'\n"
-                       if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
-                   # values for icmp-type range between 0 and 255
-                   # higher values and iptables-restore fails
-                   die "invalid icmp-type '$rule->{dport}'\n" if ($rule->{dport} =~ m/^(\d+)$/) && ($1 > 255);
+                   $is_valid_icmp_type->($rule->{dport}, $icmp_type_names);
                    push @match, "-m icmp --icmp-type $rule->{dport}";
                } elsif ($proto eq 'icmpv6') {
-                   # Note: we use dport to store --icmpv6-type
-                   die "unknown icmpv6-type '$rule->{dport}'\n"
-                       if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
-                   # values for icmpv6-type range between 0 and 255
-                   # higher values and iptables-restore fails
-                   die "invalid icmpv6-type '$rule->{dport}'\n" if ($rule->{dport} =~ m/^(\d+)$/) && ($1 > 255);
+                   $is_valid_icmp_type->($rule->{dport}, $icmpv6_type_names);
                    push @match, "-m icmpv6 --icmpv6-type $rule->{dport}";
                } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
                    die "protocol $proto does not have ports\n";