X-Git-Url: https://git.proxmox.com/?p=pve-firewall.git;a=blobdiff_plain;f=src%2FPVE%2FFirewall.pm;h=f4b199bdb7281f8ab894cdfd26b194f295e8a2bc;hp=667c876ce87275715ef7f77898197b7cb539cdb5;hb=eea9d2a1b76524876e3b84442e9c3db521fe7a66;hpb=8b453a09f302dd91db5c02c92da144df37503d79 diff --git a/src/PVE/Firewall.pm b/src/PVE/Firewall.pm index 667c876..f4b199b 100644 --- a/src/PVE/Firewall.pm +++ b/src/PVE/Firewall.pm @@ -5,12 +5,13 @@ use strict; use POSIX; use Data::Dumper; use Digest::SHA; +use Socket qw(AF_INET6 inet_ntop inet_pton); use PVE::INotify; use PVE::Exception qw(raise raise_param_exc); use PVE::JSONSchema qw(register_standard_option get_standard_option); use PVE::Cluster; use PVE::ProcFSTools; -use PVE::Tools qw($IPV4RE); +use PVE::Tools qw($IPV4RE $IPV6RE); use File::Basename; use File::Path; use IO::File; @@ -19,7 +20,8 @@ use PVE::Tools qw(run_command lock_file dir_glob_foreach); use Encode; my $hostfw_conf_filename = "/etc/pve/local/host.fw"; -my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw"; +my $pvefw_conf_dir = "/etc/pve/firewall"; +my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw"; # dynamically include PVE::QemuServer and PVE::OpenVZ # to avoid dependency problems @@ -35,11 +37,23 @@ eval { $have_pve_manager = 1; }; -PVE::JSONSchema::register_format('IPv4orCIDR', \&pve_verify_ipv4_or_cidr); -sub pve_verify_ipv4_or_cidr { +my $pve_fw_status_dir = "/var/lib/pve-firewall"; + +mkdir $pve_fw_status_dir; # make sure this exists + +my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+'; +my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+'; +our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+'; + +my $max_alias_name_length = 64; +my $max_ipset_name_length = 64; +my $max_group_name_length = 20; + +PVE::JSONSchema::register_format('IPorCIDR', \&pve_verify_ip_or_cidr); +sub pve_verify_ip_or_cidr { my ($cidr, $noerr) = @_; - if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) { + if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) { return $cidr if Net::IP->new($cidr); return undef if $noerr; die Net::IP::Error() . "\n"; @@ -48,20 +62,29 @@ sub pve_verify_ipv4_or_cidr { die "value does not look like a valid IP address or CIDR network\n"; } +PVE::JSONSchema::register_format('IPorCIDRorAlias', \&pve_verify_ip_or_cidr_or_alias); +sub pve_verify_ip_or_cidr_or_alias { + my ($cidr, $noerr) = @_; + + return if $cidr =~ m/^(?:$ip_alias_pattern)$/; + + return pve_verify_ip_or_cidr($cidr, $noerr); +} + PVE::JSONSchema::register_standard_option('ipset-name', { description => "IP set name.", type => 'string', - pattern => '[A-Za-z][A-Za-z0-9\-\_]+', + pattern => $ipset_name_pattern, minLength => 2, - maxLength => 20, + maxLength => $max_ipset_name_length, }); PVE::JSONSchema::register_standard_option('pve-fw-alias', { description => "Alias name.", type => 'string', - pattern => '[A-Za-z][A-Za-z0-9\-\_]+', + pattern => $ip_alias_pattern, minLength => 2, - maxLength => 20, + maxLength => $max_alias_name_length, }); PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => { @@ -71,15 +94,12 @@ PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => { optional => 1, }); -my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+'; -my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+'; - PVE::JSONSchema::register_standard_option('pve-security-group-name', { description => "Security Group name.", type => 'string', pattern => $security_group_name_pattern, minLength => 2, - maxLength => 20, + maxLength => $max_group_name_length, }); my $feature_ipset_nomatch = 0; @@ -438,8 +458,8 @@ my $pve_fw_macros = { { action => 'PARAM', proto => 'icmp', dport => 'echo-request' }, ], 'VNC' => [ - "VNC traffic for VNC display's 0 - 9", - { action => 'PARAM', proto => 'tcp', dport => '5900:5909' }, + "VNC traffic for VNC display's 0 - 99", + { action => 'PARAM', proto => 'tcp', dport => '5900:5999' }, ], 'VNCL' => [ "VNC traffic from Vncservers to Vncviewers in listen mode", @@ -468,7 +488,8 @@ my $pve_fw_parsed_macros; my $pve_fw_macro_descr; my $pve_fw_preferred_macro_names = {}; -my $pve_std_chains = { +my $pve_std_chains = {}; +$pve_std_chains->{4} = { 'PVEFW-SET-ACCEPT-MARK' => [ "-j MARK --set-mark 1", ], @@ -555,6 +576,92 @@ my $pve_std_chains = { ], }; +$pve_std_chains->{6} = { + 'PVEFW-SET-ACCEPT-MARK' => [ + "-j MARK --set-mark 1", + ], + 'PVEFW-DropBroadcast' => [ + # same as shorewall 'Broadcast' + # simply DROP BROADCAST/MULTICAST/ANYCAST + # we can use this to reduce logging + #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6 + # ipv6 addrtype does not work with kernel 2.6.32 + #{ action => 'DROP', dsttype => 'MULTICAST' }, + #{ action => 'DROP', dsttype => 'ANYCAST' }, + { action => 'DROP', dest => 'ff00::/8' }, + #{ action => 'DROP', dest => '224.0.0.0/4' }, + ], + 'PVEFW-reject' => [ + # same as shorewall 'reject' + #{ action => 'DROP', dsttype => 'BROADCAST' }, + #{ action => 'DROP', source => '224.0.0.0/4' }, + { action => 'DROP', proto => 'icmpv6' }, + "-p tcp -j REJECT --reject-with tcp-reset", + #"-p udp -j REJECT --reject-with icmp-port-unreachable", + #"-p icmp -j REJECT --reject-with icmp-host-unreachable", + #"-j REJECT --reject-with icmp-host-prohibited", + ], + 'PVEFW-Drop' => [ + # same as shorewall 'Drop', which is equal to DROP, + # but REJECT/DROP some packages to reduce logging, + # and ACCEPT critical ICMP types + { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth' + # we are not interested in BROADCAST/MULTICAST/ANYCAST + { action => 'PVEFW-DropBroadcast' }, + # ACCEPT critical ICMP types + { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' }, + { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' }, + { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' }, + + # Drop packets with INVALID state + "-m conntrack --ctstate INVALID -j DROP", + # Drop Microsoft SMB noise + { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 }, + { action => 'DROP', proto => 'udp', dport => '137:139'}, + { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 }, + { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 }, + { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP + # Drop new/NotSyn traffic so that it doesn't get logged + "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP", + # Drop DNS replies + { action => 'DROP', proto => 'udp', sport => 53 }, + ], + 'PVEFW-Reject' => [ + # same as shorewall 'Reject', which is equal to Reject, + # but REJECT/DROP some packages to reduce logging, + # and ACCEPT critical ICMP types + { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth' + # we are not interested in BROADCAST/MULTICAST/ANYCAST + { action => 'PVEFW-DropBroadcast' }, + # ACCEPT critical ICMP types + { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' }, + { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' }, + { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' }, + + # Drop packets with INVALID state + "-m conntrack --ctstate INVALID -j DROP", + # Drop Microsoft SMB noise + { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 }, + { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'}, + { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 }, + { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 }, + { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP + # Drop new/NotSyn traffic so that it doesn't get logged + "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP", + # Drop DNS replies + { action => 'DROP', proto => 'udp', sport => 53 }, + ], + 'PVEFW-tcpflags' => [ + # same as shorewall tcpflags action. + # Packets arriving on this interface are checked for som illegal combinations of TCP flags + "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags", + "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags", + "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags", + "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags", + "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags", + ], +}; + # iptables -p icmp -h my $icmp_type_names = { any => 1, @@ -596,6 +703,32 @@ my $icmp_type_names = { 'address-mask-reply' => 1, }; +# ip6tables -p icmpv6 -h + +my $icmpv6_type_names = { + 'any' => 1, + 'destination-unreachable' => 1, + 'no-route' => 1, + 'communication-prohibited' => 1, + 'address-unreachable' => 1, + 'port-unreachable' => 1, + 'packet-too-big' => 1, + 'time-exceeded' => 1, + 'ttl-zero-during-transit' => 1, + 'ttl-zero-during-reassembly' => 1, + 'parameter-problem' => 1, + 'bad-header' => 1, + 'unknown-header-type' => 1, + 'unknown-option' => 1, + 'echo-request' => 1, + 'echo-reply' => 1, + 'router-solicitation' => 1, + 'router-advertisement' => 1, + 'neighbour-solicitation' => 1, + 'neighbour-advertisement' => 1, + 'redirect' => 1, +}; + sub init_firewall_macros { $pve_fw_parsed_macros = {}; @@ -682,29 +815,131 @@ sub get_etc_protocols { close($fh); + # add special case for ICMP v6 + $protocols->{byid}->{icmpv6}->{name} = "icmpv6"; + $protocols->{byname}->{icmpv6} = $protocols->{byid}->{icmpv6}; + $etc_protocols = $protocols; return $etc_protocols; } +my $ipv4_mask_hash_localnet = { + '255.255.0.0' => 16, + '255.255.128.0' => 17, + '255.255.192.0' => 18, + '255.255.224.0' => 19, + '255.255.240.0' => 20, + '255.255.248.0' => 21, + '255.255.252.0' => 22, + '255.255.254.0' => 23, + '255.255.255.0' => 24, + '255.255.255.128' => 25, + '255.255.255.192' => 26, + '255.255.255.224' => 27, + '255.255.255.240' => 28, + '255.255.255.248' => 29, + '255.255.255.252' => 30, +}; + +my $__local_network; + +sub local_network { + my ($new_value) = @_; + + $__local_network = $new_value if defined($new_value); + + return $__local_network if defined($__local_network); + + eval { + my $nodename = PVE::INotify::nodename(); + + my $ip = PVE::Cluster::remote_node_ip($nodename); + + my $testip = Net::IP->new($ip); + + my $routes = PVE::ProcFSTools::read_proc_net_route(); + foreach my $entry (@$routes) { + my $mask = $ipv4_mask_hash_localnet->{$entry->{mask}}; + next if !defined($mask); + return if $mask eq '0.0.0.0'; + my $cidr = "$entry->{dest}/$mask"; + my $testnet = Net::IP->new($cidr); + if ($testnet->overlaps($testip)) { + $__local_network = $cidr; + return; + } + } + }; + warn $@ if $@; + + return $__local_network; +} + +# ipset names are limited to 31 characters, +# and we use '-v4' or '-v6' to indicate IP versions, +# and we use '_swap' suffix for atomic update, +# for example PVEFW-${VMID}-${ipset_name}_swap + +my $max_iptables_ipset_name_length = 31 - length("_swap") - length("-v4"); + +sub compute_ipset_chain_name { + my ($vmid, $ipset_name) = @_; + + $vmid = 0 if !defined($vmid); + + my $id = "$vmid-${ipset_name}"; + + if ((length($id) + 6) > $max_iptables_ipset_name_length) { + $id = PVE::Tools::fnv31a_hex($id); + } + + return "PVEFW-$id"; +} + +sub compute_ipfilter_ipset_name { + my ($iface) = @_; + + return "ipfilter-$iface"; +} + sub parse_address_list { my ($str) = @_; - return if $str =~ m/^(\+)(\S+)$/; # ipset ref - return if $str =~ m/^${ip_alias_pattern}$/; + if ($str =~ m/^(\+)(\S+)$/) { # ipset ref + die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1); + return; + } + + if ($str =~ m/^${ip_alias_pattern}$/) { + die "alias name too long\n" if length($str) > $max_alias_name_length; + return; + } my $count = 0; my $iprange = 0; + my $ipversion; + foreach my $elem (split(/,/, $str)) { $count++; - if (!Net::IP->new($elem)) { + my $ip = Net::IP->new($elem); + if (!$ip) { my $err = Net::IP::Error(); die "invalid IP address: $err\n"; } $iprange = 1 if $elem =~ m/-/; + + my $new_ipversion = Net::IP::ip_is_ipv6($ip->ip()) ? 6 : 4; + + die "detected mixed ipv4/ipv6 addresses in address list '$str'\n" + if $ipversion && ($new_ipversion != $ipversion); + + $ipversion = $new_ipversion; } - die "you can use a range in a list\n" if $iprange && $count > 1; + die "you can't use a range in a list\n" if $iprange && $count > 1; + + return $ipversion; } sub parse_port_name_number_or_range { @@ -726,6 +961,8 @@ sub parse_port_name_number_or_range { } else { if ($icmp_type_names->{$item}) { $icmp_port = 1; + } elsif ($icmpv6_type_names->{$item}) { + $icmp_port = 1; } else { die "invalid port '$item'\n" if !$services->{byname}->{$item}; } @@ -746,8 +983,8 @@ sub pve_fw_verify_port_spec { return $portstr; } -PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec); -sub pve_fw_verify_v4addr_spec { +PVE::JSONSchema::register_format('pve-fw-addr-spec', \&pve_fw_verify_addr_spec); +sub pve_fw_verify_addr_spec { my ($list) = @_; parse_address_list($list); @@ -803,7 +1040,8 @@ sub copy_list_with_digest { my $v = $entry->{$k}; next if !defined($v); $data->{$k} = $v; - $sha->add($k, ':', $v, "\n"); + # Note: digest ignores refs ($rule->{errors}) + $sha->add($k, ':', $v, "\n") if !ref($v); ; } push @$res, $data; } @@ -845,11 +1083,11 @@ my $rule_properties = { }, iface => get_standard_option('pve-iface', { optional => 1 }), source => { - type => 'string', format => 'pve-fw-v4addr-spec', + type => 'string', format => 'pve-fw-addr-spec', optional => 1, }, dest => { - type => 'string', format => 'pve-fw-v4addr-spec', + type => 'string', format => 'pve-fw-addr-spec', optional => 1, }, proto => { @@ -951,61 +1189,167 @@ my $apply_macro = sub { return $rules; }; +my $rule_env_iface_lookup = { + 'ct' => 1, + 'vm' => 1, + 'group' => 0, + 'cluster' => 1, + 'host' => 1, +}; + sub verify_rule { - my ($rule, $allow_groups) = @_; + my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_; - my $type = $rule->{type}; + my $allow_groups = $rule_env eq 'group' ? 0 : 1; - raise_param_exc({ type => "missing property"}) if !$type; - raise_param_exc({ action => "missing property"}) if !$rule->{action}; - - if ($type eq 'in' || $type eq 'out') { - raise_param_exc({ action => "unknown action '$rule->{action}'"}) - if $rule->{action} !~ m/^(ACCEPT|DROP|REJECT)$/; - } elsif ($type eq 'group') { - raise_param_exc({ type => "security groups not allowed"}) - if !$allow_groups; - raise_param_exc({ action => "invalid characters in security group name"}) - if $rule->{action} !~ m/^${security_group_name_pattern}$/; - } else { - raise_param_exc({ type => "unknown rule type '$type'"}); + my $allow_iface = $rule_env_iface_lookup->{$rule_env}; + die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen + + my $errors = $rule->{errors} || {}; + + my $error_count = 0; + + my $add_error = sub { + my ($param, $msg) = @_; + chomp $msg; + raise_param_exc({ $param => $msg }) if !$noerr; + $error_count++; + $errors->{$param} = $msg if !$errors->{$param}; + }; + + my $ipversion; + my $set_ip_version = sub { + my $vers = shift; + if ($vers) { + die "detected mixed ipv4/ipv6 adresses in rule\n" + if $ipversion && ($vers != $ipversion); + $ipversion = $vers; + } + }; + + my $check_ipset_or_alias_property = sub { + my ($name, $expected_ipversion) = @_; + + if (my $value = $rule->{$name}) { + if ($value =~ m/^\+/) { + if ($value =~ m/^\+(${ipset_name_pattern})$/) { + &$add_error($name, "no such ipset '$1'") + if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1})); + + } else { + &$add_error($name, "invalid ipset name '$value'"); + } + } elsif ($value =~ m/^${ip_alias_pattern}$/){ + my $alias = lc($value); + &$add_error($name, "no such alias '$value'") + if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias})); + + my $e = $fw_conf->{aliases}->{$alias} if $fw_conf; + $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf; + + &$set_ip_version($e->{ipversion}); + } + } + }; + + my $type = $rule->{type}; + my $action = $rule->{action}; + + &$add_error('type', "missing property") if !$type; + &$add_error('action', "missing property") if !$action; + + if ($type) { + if ($type eq 'in' || $type eq 'out') { + &$add_error('action', "unknown action '$action'") + if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/); + } elsif ($type eq 'group') { + &$add_error('type', "security groups not allowed") + if !$allow_groups; + &$add_error('action', "invalid characters in security group name") + if $action && ($action !~ m/^${security_group_name_pattern}$/); + } else { + &$add_error('type', "unknown rule type '$type'"); + } } if ($rule->{iface}) { + &$add_error('type', "parameter -i not allowed for this rule type") + if !$allow_iface; eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); }; - raise_param_exc({ iface => $@ }) if $@; - } + &$add_error('iface', $@) if $@; + if ($rule_env eq 'vm') { + &$add_error('iface', "value does not match the regex pattern 'net\\d+'") + if $rule->{iface} !~ m/^net(\d+)$/; + } elsif ($rule_env eq 'ct') { + &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'") + if $rule->{iface} !~ m/^(venet|eth(\d+))$/; + } + } if ($rule->{macro}) { - my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}; - raise_param_exc({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name; - $rule->{macro} = $preferred_name; + if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) { + $rule->{macro} = $preferred_name; + } else { + &$add_error('macro', "unknown macro '$rule->{macro}'"); + } + } + + if ($rule->{proto}) { + eval { pve_fw_verify_protocol_spec($rule->{proto}); }; + &$add_error('proto', $@) if $@; + &$set_ip_version(4) if $rule->{proto} eq 'icmp'; + &$set_ip_version(6) if $rule->{proto} eq 'icmpv6'; } if ($rule->{dport}) { eval { parse_port_name_number_or_range($rule->{dport}); }; - raise_param_exc({ dport => $@ }) if $@; + &$add_error('dport', $@) if $@; + &$add_error('proto', "missing property - 'dport' requires this property") + if !$rule->{proto}; } if ($rule->{sport}) { eval { parse_port_name_number_or_range($rule->{sport}); }; - raise_param_exc({ sport => $@ }) if $@; + &$add_error('sport', $@) if $@; + &$add_error('proto', "missing property - 'sport' requires this property") + if !$rule->{proto}; } if ($rule->{source}) { - eval { parse_address_list($rule->{source}); }; - raise_param_exc({ source => $@ }) if $@; + eval { + my $source_ipversion = parse_address_list($rule->{source}); + &$set_ip_version($source_ipversion); + }; + &$add_error('source', $@) if $@; + &$check_ipset_or_alias_property('source', $ipversion); } if ($rule->{dest}) { - eval { parse_address_list($rule->{dest}); }; - raise_param_exc({ dest => $@ }) if $@; + eval { + my $dest_ipversion = parse_address_list($rule->{dest}); + &$set_ip_version($dest_ipversion); + }; + &$add_error('dest', $@) if $@; + &$check_ipset_or_alias_property('dest', $ipversion); } - if ($rule->{macro}) { - &$apply_macro($rule->{macro}, $rule, 1); + if ($rule->{macro} && !$error_count) { + eval { &$apply_macro($rule->{macro}, $rule, 1); }; + if (my $err = $@) { + if (ref($err) eq "PVE::Exception" && $err->{errors}) { + my $eh = $err->{errors}; + foreach my $p (keys %$eh) { + &$add_error($p, $eh->{$p}); + } + } else { + &$add_error('macro', "$err"); + } + } } + $rule->{errors} = $errors if $error_count; + $rule->{ipversion} = $ipversion if $ipversion; + return $rule; } @@ -1019,16 +1363,52 @@ sub copy_rule_data { } else { $rule->{$k} = $v; } - } else { - delete $rule->{$k}; } } - # verify rule now - return $rule; } +sub rules_modify_permissions { + my ($rule_env) = @_; + + if ($rule_env eq 'host') { + return { + check => ['perm', '/nodes/{node}', [ 'Sys.Modify' ]], + }; + } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') { + return { + check => ['perm', '/', [ 'Sys.Modify' ]], + }; + } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') { + return { + check => ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]], + } + } + + return undef; +} + +sub rules_audit_permissions { + my ($rule_env) = @_; + + if ($rule_env eq 'host') { + return { + check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]], + }; + } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') { + return { + check => ['perm', '/', [ 'Sys.Audit' ]], + }; + } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') { + return { + check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]], + } + } + + return undef; +} + # core functions my $bridge_firewall_enabled = 0; @@ -1050,16 +1430,25 @@ my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n"; sub iptables_restore_cmdlist { my ($cmdlist) = @_; - run_command("/sbin/iptables-restore -n", input => $cmdlist); + run_command("/sbin/iptables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist"); +} + +sub ip6tables_restore_cmdlist { + my ($cmdlist) = @_; + + run_command("/sbin/ip6tables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist"); } sub ipset_restore_cmdlist { my ($cmdlist) = @_; - run_command("/usr/sbin/ipset restore", input => $cmdlist); + run_command("/usr/sbin/ipset restore", input => $cmdlist, errmsg => "ipset_restore_cmdlist"); } sub iptables_get_chains { + my ($iptablescmd) = @_; + + $iptablescmd = "iptables" if !$iptablescmd; my $res = {}; @@ -1114,7 +1503,7 @@ sub iptables_get_chains { } }; - run_command("/sbin/iptables-save", outfunc => $parser); + run_command("/sbin/$iptablescmd-save", outfunc => $parser); return wantarray ? ($res, $hooks) : $res; } @@ -1169,9 +1558,10 @@ sub ipset_get_chains { } sub ruleset_generate_cmdstr { - my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_; + my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_; return if defined($rule->{enable}) && !$rule->{enable}; + return if $rule->{errors}; die "unable to emit macro - internal error" if $rule->{macro}; # should not happen @@ -1188,20 +1578,28 @@ sub ruleset_generate_cmdstr { if ($source) { if ($source =~ m/^\+/) { - if ($source =~ m/^\+(${security_group_name_pattern})$/) { - die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1}; - push @cmd, "-m set --match-set PVEFW-$1 src"; + if ($source =~ m/^\+(${ipset_name_pattern})$/) { + my $name = $1; + if ($fw_conf && $fw_conf->{ipset}->{$name}) { + my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name); + push @cmd, "-m set --match-set ${ipset_chain} src"; + } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) { + my $ipset_chain = compute_ipset_chain_name(0, $name); + push @cmd, "-m set --match-set ${ipset_chain} src"; + } else { + die "no such ipset '$name'\n"; + } } else { die "invalid security group name '$source'\n"; } } elsif ($source =~ m/^${ip_alias_pattern}$/){ my $alias = lc($source); - my $e = $cluster_conf->{aliases}->{$alias}; - die "no such alias $source\n" if !$e; + my $e = $fw_conf->{aliases}->{$alias} if $fw_conf; + $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf; + die "no such alias '$source'\n" if !$e; push @cmd, "-s $e->{cidr}"; } elsif ($source =~ m/\-/){ push @cmd, "-m iprange --src-range $source"; - } else { push @cmd, "-s $source"; } @@ -1209,20 +1607,28 @@ sub ruleset_generate_cmdstr { if ($dest) { if ($dest =~ m/^\+/) { - if ($dest =~ m/^\+(${security_group_name_pattern})$/) { - die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1}; - push @cmd, "-m set --match-set PVEFW-$1 dst"; + if ($dest =~ m/^\+(${ipset_name_pattern})$/) { + my $name = $1; + if ($fw_conf && $fw_conf->{ipset}->{$name}) { + my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name); + push @cmd, "-m set --match-set ${ipset_chain} dst"; + } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) { + my $ipset_chain = compute_ipset_chain_name(0, $name); + push @cmd, "-m set --match-set ${ipset_chain} dst"; + } else { + die "no such ipset '$name'\n"; + } } else { die "invalid security group name '$dest'\n"; } } elsif ($dest =~ m/^${ip_alias_pattern}$/){ my $alias = lc($dest); - my $e = $cluster_conf->{aliases}->{$alias}; - die "no such alias $dest" if !$e; + my $e = $fw_conf->{aliases}->{$alias} if $fw_conf; + $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf; + die "no such alias '$dest'\n" if !$e; push @cmd, "-d $e->{cidr}"; } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){ push @cmd, "-m iprange --dst-range $dest"; - } else { push @cmd, "-d $dest"; } @@ -1245,6 +1651,10 @@ sub ruleset_generate_cmdstr { # Note: we use dport to store --icmp-type die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}}); push @cmd, "-m icmp --icmp-type $rule->{dport}"; + } elsif ($rule->{proto} && $rule->{proto} eq 'icmpv6') { + # Note: we use dport to store --icmpv6-type + die "unknown icmpv6-type '$rule->{dport}'\n" if !defined($icmpv6_type_names->{$rule->{dport}}); + push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}"; } else { if ($nbdport > 1) { if ($multiport == 2) { @@ -1266,8 +1676,8 @@ sub ruleset_generate_cmdstr { } } } elsif ($rule->{dport} || $rule->{sport}) { - warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport}; - warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport}; + die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport}; + die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport}; } push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype}; @@ -1282,7 +1692,7 @@ sub ruleset_generate_cmdstr { } sub ruleset_generate_rule { - my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_; + my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_; my $rules; @@ -1296,7 +1706,7 @@ sub ruleset_generate_rule { my @cmds = (); foreach my $tmp (@$rules) { - if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) { + if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) { push @cmds, $cmdstr; } } @@ -1409,15 +1819,22 @@ sub ruleset_chain_add_conn_filters { } sub ruleset_chain_add_input_filters { - my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_; + my ($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel) = @_; if ($cluster_conf->{ipset}->{blacklist}){ - ruleset_addlog($ruleset, $chain, 0, "DROP: ", $loglevel, "-m set --match-set PVEFW-blacklist src"); - ruleset_addrule($ruleset, $chain, "-m set --match-set PVEFW-blacklist src -j DROP"); + if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) { + ruleset_create_chain($ruleset, "PVEFW-blacklist"); + ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel; + ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP"); + } + my $ipset_chain = compute_ipset_chain_name(0, 'blacklist'); + ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist"); } if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) { - ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs"); + if ($ipversion == 4) { + ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs"); + } } if ($options->{tcpflags}) { @@ -1426,7 +1843,7 @@ sub ruleset_chain_add_input_filters { } sub ruleset_create_vm_chain { - my ($ruleset, $chain, $options, $macaddr, $direction) = @_; + my ($ruleset, $chain, $options, $macaddr, $ipfilter_ipset, $direction) = @_; ruleset_create_chain($ruleset, $chain); my $accept = generate_nfqueue($options); @@ -1445,19 +1862,22 @@ sub ruleset_create_vm_chain { if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) { ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP"); } + if ($ipfilter_ipset) { + ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP"); + } ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark } } sub ruleset_add_group_rule { - my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_; + my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_; my $group = $rule->{action}; my $group_chain = "GROUP-$group-$direction"; if(!ruleset_chain_exist($ruleset, $group_chain)){ - generate_group_rules($ruleset, $cluster_conf, $group); + generate_group_rules($ruleset, $cluster_conf, $group, $ipversion); } - + if ($direction eq 'OUT' && $rule->{iface_out}) { ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain"); } elsif ($direction eq 'IN' && $rule->{iface_in}) { @@ -1470,7 +1890,7 @@ sub ruleset_add_group_rule { } sub ruleset_generate_vm_rules { - my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_; + my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_; my $lc_direction = lc($direction); @@ -1478,21 +1898,23 @@ sub ruleset_generate_vm_rules { foreach my $rule (@$rules) { next if $rule->{iface} && $rule->{iface} ne $netid; - next if !$rule->{enable}; + next if !$rule->{enable} || $rule->{errors}; + next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion); + if ($rule->{type} eq 'group') { ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction, - $direction eq 'OUT' ? 'RETURN' : $in_accept); + $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion); } else { next if $rule->{type} ne $lc_direction; eval { if ($direction eq 'OUT') { ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, - undef, $cluster_conf); + undef, $cluster_conf, $vmfw_conf); } else { ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $in_accept , REJECT => "PVEFW-reject" }, - undef, $cluster_conf); + undef, $cluster_conf, $vmfw_conf); } }; warn $@ if $@; @@ -1534,7 +1956,7 @@ sub ruleset_generate_vm_ipsrules { } sub generate_venet_rules_direction { - my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_; + my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_; my $lc_direction = lc($direction); @@ -1545,9 +1967,9 @@ sub generate_venet_rules_direction { my $chain = "venet0-$vmid-$direction"; - ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction); + ruleset_create_vm_chain($ruleset, $chain, $options, undef, undef, $direction); - ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction); + ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion); # implement policy my $policy; @@ -1576,7 +1998,7 @@ sub generate_venet_rules_direction { } sub generate_tap_rules_direction { - my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_; + my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_; my $lc_direction = lc($direction); @@ -1587,24 +2009,34 @@ sub generate_tap_rules_direction { my $tapchain = "$iface-$direction"; - ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction); + my $ipfilter_name = compute_ipfilter_ipset_name($netid); + my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name) + if $vmfw_conf->{ipset}->{$ipfilter_name}; - ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options); + # create chain with mac and ip filter + ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $ipfilter_ipset, $direction); - ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface); + if ($options->{enable}) { + ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion); - # implement policy - my $policy; + ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface); - if ($direction eq 'OUT') { - $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default - } else { + # implement policy + my $policy; + + if ($direction eq 'OUT') { + $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default + } else { $policy = $options->{policy_in} || 'DROP'; # allow nothing by default - } + } - my $accept = generate_nfqueue($options); - my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept; - ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action); + my $accept = generate_nfqueue($options); + my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept; + ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action); + } else { + my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT'; + ruleset_add_chain_policy($ruleset, $tapchain, $vmid, 'ACCEPT', $loglevel, $accept_action); + } # plug the tap chain to bridge chain if ($direction eq 'IN') { @@ -1617,7 +2049,7 @@ sub generate_tap_rules_direction { } sub enable_host_firewall { - my ($ruleset, $hostfw_conf, $cluster_conf) = @_; + my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_; my $options = $hostfw_conf->{options}; my $cluster_options = $cluster_conf->{options}; @@ -1633,27 +2065,48 @@ sub enable_host_firewall { ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT"); ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT'); - ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel); - - ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT"); - ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT"); - ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync + ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $ipversion, $loglevel); # we use RETURN because we need to check also tap rules my $accept_action = 'RETURN'; + ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast + # add host rules first, so that cluster wide rules can be overwritten foreach my $rule (@$rules, @$cluster_rules) { + next if !$rule->{enable} || $rule->{errors}; + $rule->{iface_in} = $rule->{iface} if $rule->{iface}; - if ($rule->{type} eq 'group') { - ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action); - } elsif ($rule->{type} eq 'in') { - ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, - undef, $cluster_conf); - } + + eval { + if ($rule->{type} eq 'group') { + ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion); + } elsif ($rule->{type} eq 'in') { + ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, + undef, $cluster_conf, $hostfw_conf); + } + }; + warn $@ if $@; delete $rule->{iface_in}; } + # allow standard traffic for management ipset (includes cluster network) + my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management"); + my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src"; + ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API + ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console + ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy + ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH + + my $localnet = local_network(); + + # corosync + if ($localnet) { + my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action"; + ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule"); + ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule"); + } + # implement input policy my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action); @@ -1668,25 +2121,40 @@ sub enable_host_firewall { ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT'); - ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT"); - ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT"); - ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync - # we use RETURN because we may want to check other thigs later $accept_action = 'RETURN'; + ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast + # add host rules first, so that cluster wide rules can be overwritten foreach my $rule (@$rules, @$cluster_rules) { + next if !$rule->{enable} || $rule->{errors}; + $rule->{iface_out} = $rule->{iface} if $rule->{iface}; - if ($rule->{type} eq 'group') { - ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action); - } elsif ($rule->{type} eq 'out') { - ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, - undef, $cluster_conf); - } + eval { + if ($rule->{type} eq 'group') { + ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion); + } elsif ($rule->{type} eq 'out') { + ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, + undef, $cluster_conf, $hostfw_conf); + } + }; + warn $@ if $@; delete $rule->{iface_out}; } + # allow standard traffic on cluster network + if ($localnet) { + ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API + ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH + ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console + ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy + + my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action"; + ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule"); + ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule"); + } + # implement output policy $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action); @@ -1696,7 +2164,7 @@ sub enable_host_firewall { } sub generate_group_rules { - my ($ruleset, $cluster_conf, $group) = @_; + my ($ruleset, $cluster_conf, $group, $ipversion) = @_; my $rules = $cluster_conf->{groups}->{$group}; @@ -1712,6 +2180,7 @@ sub generate_group_rules { foreach my $rule (@$rules) { next if $rule->{type} ne 'in'; + next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion; ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf); } @@ -1722,6 +2191,7 @@ sub generate_group_rules { foreach my $rule (@$rules) { next if $rule->{type} ne 'out'; + next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion; # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to # check also other tap rules later ruleset_generate_rule($ruleset, $chain, $rule, @@ -1736,77 +2206,62 @@ for (my $i = 0; $i < $MAX_NETS; $i++) { } sub parse_fw_rule { - my ($line, $allow_iface, $allow_groups) = @_; + my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_; - my ($type, $action, $macro, $iface, $source, $dest, $proto, $dport, $sport); + my $orig_line = $line; - chomp $line; + my $rule = {}; # we can add single line comments to the end of the rule - my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//; + if ($line =~ s/#\s*(.*?)\s*$//) { + $rule->{comment} = decode('utf8', $1); + } # we can disable a rule when prefixed with '|' - my $enable = 1; - $enable = 0 if $line =~ s/^\|//; + $rule->{enable} = $line =~ s/^\|// ? 0 : 1; $line =~ s/^(\S+)\s+(\S+)\s*// || die "unable to parse rule: $line\n"; - - $type = lc($1); - $action = $2; - - if ($type eq 'in' || $type eq 'out') { - if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) { - # OK - } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) { - $action = $2; - my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)}; - die "unknown macro '$1'\n" if !$preferred_name; - $macro = $preferred_name; - } else { - die "unknown action '$action'\n"; + + $rule->{type} = lc($1); + $rule->{action} = $2; + + if ($rule->{type} eq 'in' || $rule->{type} eq 'out') { + if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) { + $rule->{macro} = $1; + $rule->{action} = $2; } - } elsif ($type eq 'group') { - die "groups disabled\n" if !$allow_groups; - die "invalid characters in group name\n" if $action !~ m/^${security_group_name_pattern}$/; - } else { - die "unknown rule type '$type'\n"; } while (length($line)) { if ($line =~ s/^-i (\S+)\s*//) { - die "parameter -i not allowed\n" if !$allow_iface; - $iface = $1; - PVE::JSONSchema::pve_verify_iface($iface); + $rule->{iface} = $1; next; } - last if $type eq 'group'; + last if $rule->{type} eq 'group'; if ($line =~ s/^-p (\S+)\s*//) { - $proto = $1; - pve_fw_verify_protocol_spec($proto); + $rule->{proto} = $1; next; } + if ($line =~ s/^-dport (\S+)\s*//) { - $dport = $1; - parse_port_name_number_or_range($dport); + $rule->{dport} = $1; next; } + if ($line =~ s/^-sport (\S+)\s*//) { - $sport = $1; - parse_port_name_number_or_range($sport); + $rule->{sport} = $1; next; } if ($line =~ s/^-source (\S+)\s*//) { - $source = $1; - parse_address_list($source); + $rule->{source} = $1; next; } if ($line =~ s/^-dest (\S+)\s*//) { - $dest = $1; - parse_address_list($dest); + $rule->{dest} = $1; next; } @@ -1815,19 +2270,15 @@ sub parse_fw_rule { die "unable to parse rule parameters: $line\n" if length($line); - return { - type => $type, - enable => $enable, - comment => $comment, - action => $action, - macro => $macro, - iface => $iface, - source => $source, - dest => $dest, - proto => $proto, - dport => $dport, - sport => $sport, - }; + $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1); + if ($verbose && $rule->{errors}) { + warn "$prefix - errors in rule parameters: $orig_line\n"; + foreach my $p (keys %{$rule->{errors}}) { + warn " $p: $rule->{errors}->{$p}\n"; + } + } + + return $rule; } sub parse_vmfw_option { @@ -1850,7 +2301,6 @@ sub parse_vmfw_option { $opt = lc($1); $value = $2; } else { - chomp $line; die "can't parse option '$line'\n" } @@ -1874,7 +2324,6 @@ sub parse_hostfw_option { $opt = lc($1); $value = int($2); } else { - chomp $line; die "can't parse option '$line'\n" } @@ -1893,182 +2342,132 @@ sub parse_clusterfw_option { $opt = lc($1); $value = uc($3); } else { - chomp $line; die "can't parse option '$line'\n" } return ($opt, $value); } -sub parse_clusterfw_alias { - my ($line) = @_; +sub resolve_alias { + my ($clusterfw_conf, $fw_conf, $cidr) = @_; - # we can add single line comments to the end of the line - my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//; + my $alias = lc($cidr); + my $e = $fw_conf->{aliases}->{$alias} if $fw_conf; + $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf; - if ($line =~ m/^(\S+)\s(\S+)$/) { - my ($name, $cidr) = ($1, $2); - $cidr =~ s|/32$||; - pve_verify_ipv4_or_cidr($cidr); - my $data = { - name => $name, - cidr => $cidr, - }; - $data->{comment} = $comment if $comment; - return $data; - } + die "no such alias '$cidr'\n" if !$e;; - return undef; + return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr}; } -sub parse_vm_fw_rules { - my ($filename, $fh) = @_; - - my $res = { rules => [], options => {}}; - - my $section; - - while (defined(my $line = <$fh>)) { - next if $line =~ m/^#/; - next if $line =~ m/^\s*$/; - - my $linenr = $fh->input_line_number(); - my $prefix = "$filename (line $linenr)"; - - if ($line =~ m/^\[(\S+)\]\s*$/i) { - $section = lc($1); - warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section}; - next; - } - if (!$section) { - warn "$prefix: skip line - no section"; - next; - } - - next if !$res->{$section}; # skip undefined section - - if ($section eq 'options') { - eval { - my ($opt, $value) = parse_vmfw_option($line); - $res->{options}->{$opt} = $value; - }; - warn "$prefix: $@" if $@; - next; - } - - my $rule; - eval { $rule = parse_fw_rule($line, 1, 1); }; - if (my $err = $@) { - warn "$prefix: $err"; - next; - } +sub parse_ip_or_cidr { + my ($cidr) = @_; - push @{$res->{$section}}, $rule; + my $ipversion; + + if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) { + $cidr =~ s|/128$||; + $ipversion = 6; + } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) { + $cidr =~ s|/32$||; + $ipversion = 4; + } else { + die "value does not look like a valid IP address or CIDR network\n"; } - return $res; + return wantarray ? ($cidr, $ipversion) : $cidr; } -sub parse_host_fw_rules { - my ($filename, $fh) = @_; - - my $res = { rules => [], options => {}}; - - my $section; - - while (defined(my $line = <$fh>)) { - next if $line =~ m/^#/; - next if $line =~ m/^\s*$/; - - my $linenr = $fh->input_line_number(); - my $prefix = "$filename (line $linenr)"; - - if ($line =~ m/^\[(\S+)\]\s*$/i) { - $section = lc($1); - warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section}; - next; - } - if (!$section) { - warn "$prefix: skip line - no section"; - next; - } +sub parse_alias { + my ($line) = @_; - next if !$res->{$section}; # skip undefined section + # we can add single line comments to the end of the line + my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//; - if ($section eq 'options') { - eval { - my ($opt, $value) = parse_hostfw_option($line); - $res->{options}->{$opt} = $value; - }; - warn "$prefix: $@" if $@; - next; - } + if ($line =~ m/^(\S+)\s(\S+)$/) { + my ($name, $cidr) = ($1, $2); + my $ipversion; - my $rule; - eval { $rule = parse_fw_rule($line, 1, 1); }; - if (my $err = $@) { - warn "$prefix: $err"; - next; - } + ($cidr, $ipversion) = parse_ip_or_cidr($cidr); - push @{$res->{$section}}, $rule; + my $data = { + name => $name, + cidr => $cidr, + ipversion => $ipversion, + }; + $data->{comment} = $comment if $comment; + return $data; } - return $res; + return undef; } -sub parse_cluster_fw_rules { - my ($filename, $fh) = @_; +sub generic_fw_config_parser { + my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_; my $section; my $group; - my $res = { - rules => [], - options => {}, - aliases => {}, - groups => {}, - group_comments => {}, - ipset => {} , - ipset_comments => {}, - }; + my $res = $empty_conf; while (defined(my $line = <$fh>)) { next if $line =~ m/^#/; next if $line =~ m/^\s*$/; + chomp $line; + my $linenr = $fh->input_line_number(); my $prefix = "$filename (line $linenr)"; - if ($line =~ m/^\[options\]$/i) { + if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) { $section = 'options'; next; } - if ($line =~ m/^\[aliases\]$/i) { + if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) { $section = 'aliases'; next; } - if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) { + if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) { $section = 'groups'; $group = lc($1); my $comment = $2; + eval { + die "security group name too long\n" if length($group) > $max_group_name_length; + die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/; + }; + if (my $err = $@) { + ($section, $group, $comment) = undef; + warn "$prefix: $err"; + next; + } + $res->{$section}->{$group} = []; $res->{group_comments}->{$group} = decode('utf8', $comment) if $comment; next; } - if ($line =~ m/^\[rules\]$/i) { + if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) { $section = 'rules'; next; } - if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) { + if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) { $section = 'ipset'; $group = lc($1); my $comment = $2; + eval { + die "ipset name too long\n" if length($group) > $max_ipset_name_length; + die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/; + }; + if (my $err = $@) { + ($section, $group, $comment) = undef; + warn "$prefix: $err"; + next; + } + $res->{$section}->{$group} = []; $res->{ipset_comments}->{$group} = decode('utf8', $comment) if $comment; @@ -2082,19 +2481,26 @@ sub parse_cluster_fw_rules { if ($section eq 'options') { eval { - my ($opt, $value) = parse_clusterfw_option($line); + my ($opt, $value); + if ($rule_env eq 'cluster') { + ($opt, $value) = parse_clusterfw_option($line); + } elsif ($rule_env eq 'host') { + ($opt, $value) = parse_hostfw_option($line); + } else { + ($opt, $value) = parse_vmfw_option($line); + } $res->{options}->{$opt} = $value; }; warn "$prefix: $@" if $@; } elsif ($section eq 'aliases') { eval { - my $data = parse_clusterfw_alias($line); + my $data = parse_alias($line); $res->{aliases}->{lc($data->{name})} = $data; }; warn "$prefix: $@" if $@; } elsif ($section eq 'rules') { my $rule; - eval { $rule = parse_fw_rule($line, 1, 1); }; + eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); }; if (my $err = $@) { warn "$prefix: $err"; next; @@ -2102,7 +2508,7 @@ sub parse_cluster_fw_rules { push @{$res->{$section}}, $rule; } elsif ($section eq 'groups') { my $rule; - eval { $rule = parse_fw_rule($line, 0, 0); }; + eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); }; if (my $err = $@) { warn "$prefix: $err"; next; @@ -2115,28 +2521,87 @@ sub parse_cluster_fw_rules { $line =~ m/^(\!)?\s*(\S+)\s*$/; my $nomatch = $1; my $cidr = $2; + my $errors; - if($cidr !~ m/^${ip_alias_pattern}$/) { - $cidr =~ s|/32$||; + if ($nomatch && !$feature_ipset_nomatch) { + $errors->{nomatch} = "nomatch not supported by kernel"; + } - eval { pve_verify_ipv4_or_cidr($cidr); }; - if (my $err = $@) { - warn "$prefix: $cidr - $err"; - next; + eval { + if ($cidr =~ m/^${ip_alias_pattern}$/) { + resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists + } else { + $cidr = parse_ip_or_cidr($cidr); } + }; + if (my $err = $@) { + chomp $err; + $errors->{cidr} = $err; } my $entry = { cidr => $cidr }; $entry->{nomatch} = 1 if $nomatch; $entry->{comment} = $comment if $comment; + $entry->{errors} = $errors if $errors; + + if ($verbose && $errors) { + warn "$prefix - errors in ipset '$group': $line\n"; + foreach my $p (keys %{$errors}) { + warn " $p: $errors->{$p}\n"; + } + } push @{$res->{$section}->{$group}}, $entry; + } else { + warn "$prefix: skip line - unknown section\n"; + next; } } return $res; } +sub parse_hostfw_config { + my ($filename, $fh, $cluster_conf, $verbose) = @_; + + my $empty_conf = { rules => [], options => {}}; + + return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host'); +} + +sub parse_vmfw_config { + my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_; + + my $empty_conf = { + rules => [], + options => {}, + aliases => {}, + ipset => {} , + ipset_comments => {}, + }; + + return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env); +} + +sub parse_clusterfw_config { + my ($filename, $fh, $verbose) = @_; + + my $section; + my $group; + + my $empty_conf = { + rules => [], + options => {}, + aliases => {}, + groups => {}, + group_comments => {}, + ipset => {} , + ipset_comments => {}, + }; + + return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster'); +} + sub run_locked { my ($code, @param) = @_; @@ -2186,15 +2651,16 @@ sub read_local_vm_config { }; sub load_vmfw_conf { - my ($vmid, $dir) = @_; + my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_; my $vmfw_conf = {}; - $dir = "/etc/pve/firewall" if !defined($dir); + $dir = $pvefw_conf_dir if !defined($dir); my $filename = "$dir/$vmid.fw"; if (my $fh = IO::File->new($filename, O_RDONLY)) { - $vmfw_conf = parse_vm_fw_rules($filename, $fh); + $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose); + $vmfw_conf->{vmid} = $vmid; } return $vmfw_conf; @@ -2269,23 +2735,35 @@ my $format_aliases = sub { return $raw; }; -my $format_ipset = sub { - my ($options) = @_; - +my $format_ipsets = sub { + my ($fw_conf) = @_; + my $raw = ''; - my $nethash = {}; - foreach my $entry (@$options) { - $nethash->{$entry->{cidr}} = $entry; - } + foreach my $ipset (sort keys %{$fw_conf->{ipset}}) { + if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) { + my $utf8comment = encode('utf8', $comment); + $raw .= "[IPSET $ipset] # $utf8comment\n\n"; + } else { + $raw .= "[IPSET $ipset]\n\n"; + } + my $options = $fw_conf->{ipset}->{$ipset}; - foreach my $cidr (sort keys %$nethash) { - my $entry = $nethash->{$cidr}; - my $line = $entry->{nomatch} ? '!' : ''; - $line .= $entry->{cidr}; - $line .= " # " . encode('utf8', $entry->{comment}) - if $entry->{comment} && $entry->{comment} !~ m/^\s*$/; - $raw .= "$line\n"; + my $nethash = {}; + foreach my $entry (@$options) { + $nethash->{$entry->{cidr}} = $entry; + } + + foreach my $cidr (sort keys %$nethash) { + my $entry = $nethash->{$cidr}; + my $line = $entry->{nomatch} ? '!' : ''; + $line .= $entry->{cidr}; + $line .= " # " . encode('utf8', $entry->{comment}) + if $entry->{comment} && $entry->{comment} !~ m/^\s*$/; + $raw .= "$line\n"; + } + + $raw .= "\n"; } return $raw; @@ -2297,26 +2775,38 @@ sub save_vmfw_conf { my $raw = ''; my $options = $vmfw_conf->{options}; - $raw .= &$format_options($options) if scalar(keys %$options); + $raw .= &$format_options($options) if $options && scalar(keys %$options); + + my $aliases = $vmfw_conf->{aliases}; + $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases); + + $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset}; my $rules = $vmfw_conf->{rules} || []; - if (scalar(@$rules)) { + if ($rules && scalar(@$rules)) { $raw .= "[RULES]\n\n"; $raw .= &$format_rules($rules, 1); $raw .= "\n"; } - my $filename = "/etc/pve/firewall/$vmid.fw"; + mkdir $pvefw_conf_dir; + + my $filename = "$pvefw_conf_dir/$vmid.fw"; PVE::Tools::file_set_contents($filename, $raw); } sub read_vm_firewall_configs { - my ($vmdata, $dir) = @_; + my ($cluster_conf, $vmdata, $dir, $verbose) = @_; my $vmfw_configs = {}; - foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) { - my $vmfw_conf = load_vmfw_conf($vmid, $dir); + foreach my $vmid (keys %{$vmdata->{qemu}}) { + my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose); + next if !$vmfw_conf->{options}; # skip if file does not exists + $vmfw_configs->{$vmid} = $vmfw_conf; + } + foreach my $vmid (keys %{$vmdata->{openvz}}) { + my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose); next if !$vmfw_conf->{options}; # skip if file does not exists $vmfw_configs->{$vmid} = $vmfw_conf; } @@ -2342,29 +2832,35 @@ sub get_option_log_level { } sub generate_std_chains { - my ($ruleset, $options) = @_; + my ($ruleset, $options, $ipversion) = @_; + + my $std_chains = $pve_std_chains->{$ipversion} || die "internal error"; my $loglevel = get_option_log_level($options, 'smurf_log_level'); - # same as shorewall smurflog. - my $chain = 'PVEFW-smurflog'; - $pve_std_chains->{$chain} = []; + my $chain; - push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel; - push @{$pve_std_chains->{$chain}}, "-j DROP"; + if ($ipversion == 4) { + # same as shorewall smurflog. + $chain = 'PVEFW-smurflog'; + $std_chains->{$chain} = []; + + push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel; + push @{$std_chains->{$chain}}, "-j DROP"; + } # same as shorewall logflags action. $loglevel = get_option_log_level($options, 'tcp_flags_log_level'); $chain = 'PVEFW-logflags'; - $pve_std_chains->{$chain} = []; + $std_chains->{$chain} = []; # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG) - push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel; - push @{$pve_std_chains->{$chain}}, "-j DROP"; + push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel; + push @{$std_chains->{$chain}}, "-j DROP"; - foreach my $chain (keys %$pve_std_chains) { + foreach my $chain (keys %$std_chains) { ruleset_create_chain($ruleset, $chain); - foreach my $rule (@{$pve_std_chains->{$chain}}) { + foreach my $rule (@{$std_chains->{$chain}}) { if (ref($rule)) { ruleset_generate_rule($ruleset, $chain, $rule); } else { @@ -2375,55 +2871,77 @@ sub generate_std_chains { } sub generate_ipset_chains { - my ($ipset_ruleset, $fw_conf) = @_; + my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_; foreach my $ipset (keys %{$fw_conf->{ipset}}) { - generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases}); + my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset); + generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf); } } sub generate_ipset { - my ($ipset_ruleset, $name, $options, $aliases) = @_; + my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_; - my $hashsize = scalar(@$options); - if ($hashsize <= 64) { - $hashsize = 64; - } else { - $hashsize = round_powerof2($hashsize); - } + die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name}); - push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize"; + $ipset_ruleset->{$name} = ["create $name list:set size 4"]; # remove duplicates my $nethash = {}; foreach my $entry (@$options) { - my $cidr = $entry->{cidr}; - if ($cidr =~ m/^${ip_alias_pattern}$/) { - my $alias = lc($cidr); - if ($aliases->{$alias}) { - $entry->{cidr} = $aliases->{$alias}->{cidr}; - $nethash->{$entry->{cidr}} = $entry; + next if $entry->{errors}; # skip entries with errors + eval { + my ($cidr, $ipversion); + if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) { + ($cidr, $ipversion) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr}); + } else { + ($cidr, $ipversion) = parse_ip_or_cidr($entry->{cidr}); + } + #http://backreference.org/2013/03/01/ipv6-address-normalization/ + if ($ipversion == 6) { + my $ipv6 = inet_pton(AF_INET6, lc($cidr)); + $cidr = inet_ntop(AF_INET6, $ipv6); + $cidr =~ s|/128$||; } else { - warn "no such alias '$cidr'\n" if !$aliases->{$alias}; + $cidr =~ s|/32$||; } + + $nethash->{$ipversion}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} }; + }; + warn $@ if $@; + } + + foreach my $ipversion (sort keys %$nethash) { + my $data = $nethash->{$ipversion}; + my $subname = "$name-v$ipversion"; + + my $hashsize = scalar(@$options); + if ($hashsize <= 64) { + $hashsize = 64; } else { - $nethash->{$entry->{cidr}} = $entry; + $hashsize = round_powerof2($hashsize); } - } - foreach my $cidr (sort keys %$nethash) { - my $entry = $nethash->{$cidr}; + my $family = $ipversion == "6" ? "inet6" : "inet"; - my $cmd = "add $name $cidr"; - if ($entry->{nomatch}) { - if ($feature_ipset_nomatch) { - push @{$ipset_ruleset->{$name}}, "$cmd nomatch"; + $ipset_ruleset->{$subname} = ["create $subname hash:net family $family hashsize $hashsize maxelem $hashsize"]; + + foreach my $cidr (sort keys %$data) { + my $entry = $data->{$cidr}; + + my $cmd = "add $subname $cidr"; + if ($entry->{nomatch}) { + if ($feature_ipset_nomatch) { + push @{$ipset_ruleset->{$subname}}, "$cmd nomatch"; + } else { + warn "ignore !$cidr - nomatch not supported by kernel\n"; + } } else { - warn "ignore !$cidr - nomatch not supported by kernel\n"; + push @{$ipset_ruleset->{$subname}}, $cmd; } - } else { - push @{$ipset_ruleset->{$name}}, $cmd; } + + push @{$ipset_ruleset->{$name}}, "add $name $subname"; } } @@ -2436,13 +2954,13 @@ sub round_powerof2 { } sub load_clusterfw_conf { - my ($filename) = @_; + my ($filename, $verbose) = @_; $filename = $clusterfw_conf_filename if !defined($filename); my $cluster_conf = {}; if (my $fh = IO::File->new($filename, O_RDONLY)) { - $cluster_conf = parse_cluster_fw_rules($filename, $fh); + $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose); } return $cluster_conf; @@ -2454,54 +2972,47 @@ sub save_clusterfw_conf { my $raw = ''; my $options = $cluster_conf->{options}; - $raw .= &$format_options($options) if scalar(keys %$options); + $raw .= &$format_options($options) if $options && scalar(keys %$options); my $aliases = $cluster_conf->{aliases}; - $raw .= &$format_aliases($aliases) if scalar(keys %$aliases); - - foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) { - if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) { - my $utf8comment = encode('utf8', $comment); - $raw .= "[IPSET $ipset] # $utf8comment\n\n"; - } else { - $raw .= "[IPSET $ipset]\n\n"; - } - my $options = $cluster_conf->{ipset}->{$ipset}; - $raw .= &$format_ipset($options); - $raw .= "\n"; - } + $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases); + $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset}; + my $rules = $cluster_conf->{rules}; - if (scalar(@$rules)) { + if ($rules && scalar(@$rules)) { $raw .= "[RULES]\n\n"; $raw .= &$format_rules($rules, 1); $raw .= "\n"; } - foreach my $group (sort keys %{$cluster_conf->{groups}}) { - my $rules = $cluster_conf->{groups}->{$group}; - if (my $comment = $cluster_conf->{group_comments}->{$group}) { - my $utf8comment = encode('utf8', $comment); - $raw .= "[group $group] # $utf8comment\n\n"; - } else { - $raw .= "[group $group]\n\n"; - } + if ($cluster_conf->{groups}) { + foreach my $group (sort keys %{$cluster_conf->{groups}}) { + my $rules = $cluster_conf->{groups}->{$group}; + if (my $comment = $cluster_conf->{group_comments}->{$group}) { + my $utf8comment = encode('utf8', $comment); + $raw .= "[group $group] # $utf8comment\n\n"; + } else { + $raw .= "[group $group]\n\n"; + } - $raw .= &$format_rules($rules, 0); - $raw .= "\n"; + $raw .= &$format_rules($rules, 0); + $raw .= "\n"; + } } + mkdir $pvefw_conf_dir; PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw); } sub load_hostfw_conf { - my ($filename) = @_; + my ($cluster_conf, $filename, $verbose) = @_; $filename = $hostfw_conf_filename if !defined($filename); my $hostfw_conf = {}; if (my $fh = IO::File->new($filename, O_RDONLY)) { - $hostfw_conf = parse_host_fw_rules($filename, $fh); + $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose); } return $hostfw_conf; } @@ -2512,10 +3023,10 @@ sub save_hostfw_conf { my $raw = ''; my $options = $hostfw_conf->{options}; - $raw .= &$format_options($options) if scalar(keys %$options); + $raw .= &$format_options($options) if $options && scalar(keys %$options); my $rules = $hostfw_conf->{rules}; - if (scalar(@$rules)) { + if ($rules && scalar(@$rules)) { $raw .= "[RULES]\n\n"; $raw .= &$format_rules($rules, 1); $raw .= "\n"; @@ -2525,32 +3036,51 @@ sub save_hostfw_conf { } sub compile { - my ($cluster_conf, $hostfw_conf, $vmdata) = @_; + my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_; my $vmfw_configs; if ($vmdata) { # test mode my $testdir = $vmdata->{testdir} || die "no test directory specified"; my $filename = "$testdir/cluster.fw"; - die "missing test file '$filename'\n" if ! -f $filename; - $cluster_conf = load_clusterfw_conf($filename); + $cluster_conf = load_clusterfw_conf($filename, $verbose); $filename = "$testdir/host.fw"; - die "missing test file '$filename'\n" if ! -f $filename; - $hostfw_conf = load_hostfw_conf($filename); + $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose); - $vmfw_configs = read_vm_firewall_configs($vmdata, $testdir); + $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose); } else { # normal operation - $cluster_conf = load_clusterfw_conf() if !$cluster_conf; + $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf; - $hostfw_conf = load_hostfw_conf() if !$hostfw_conf; + $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf; $vmdata = read_local_vm_config(); - $vmfw_configs = read_vm_firewall_configs($vmdata); + $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose); } + my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose); + my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose); + + return ($ruleset, $ipset_ruleset, $rulesetv6); +} + +sub compile_iptables_filter { + my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_; $cluster_conf->{ipset}->{venet0} = []; + my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0'); + + my $localnet; + if ($cluster_conf->{aliases}->{local_network}) { + $localnet = $cluster_conf->{aliases}->{local_network}->{cidr}; + } else { + $localnet = local_network() || '127.0.0.0/8'; + $cluster_conf->{aliases}->{local_network} = { cidr => $localnet }; + } + + push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet }; + + return ({}, {}) if !$cluster_conf->{options}->{enable}; my $ruleset = {}; @@ -2566,12 +3096,13 @@ sub compile { ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT"); + ruleset_create_chain($ruleset, "PVEFW-VENET-OUT"); - ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT"); - ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT"); + ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT"); + ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT"); ruleset_create_chain($ruleset, "PVEFW-FWBR-IN"); - ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel); + ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel); ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN"); @@ -2579,85 +3110,103 @@ sub compile { ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT"); ruleset_create_chain($ruleset, "PVEFW-VENET-IN"); - ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel); + ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $ipversion, $loglevel); - ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN"); + ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN"); - generate_std_chains($ruleset, $hostfw_options); + generate_std_chains($ruleset, $hostfw_options, $ipversion); my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0)); - enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable; + my $ipset_ruleset = {}; + + # currently pveproxy don't works with ipv6, so let's generate host fw ipv4 only for the moment + if ($hostfw_enable && ($ipversion == 4)) { + eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); }; + warn $@ if $@; # just to be sure - should not happen + } - ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN"); + ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN"); # generate firewall rules for QEMU VMs foreach my $vmid (keys %{$vmdata->{qemu}}) { - my $conf = $vmdata->{qemu}->{$vmid}; - my $vmfw_conf = $vmfw_configs->{$vmid}; - next if !$vmfw_conf; - next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0); + eval { + my $conf = $vmdata->{qemu}->{$vmid}; + my $vmfw_conf = $vmfw_configs->{$vmid}; + return if !$vmfw_conf; - foreach my $netid (keys %$conf) { - next if $netid !~ m/^net(\d+)$/; - my $net = PVE::QemuServer::parse_net($conf->{$netid}); - next if !$net->{firewall}; - my $iface = "tap${vmid}i$1"; + generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf); - my $macaddr = $net->{macaddr}; - generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, - $vmfw_conf, $vmid, 'IN'); - generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, - $vmfw_conf, $vmid, 'OUT'); - } + foreach my $netid (keys %$conf) { + next if $netid !~ m/^net(\d+)$/; + my $net = PVE::QemuServer::parse_net($conf->{$netid}); + next if !$net->{firewall}; + my $iface = "tap${vmid}i$1"; + + my $macaddr = $net->{macaddr}; + generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, + $vmfw_conf, $vmid, 'IN', $ipversion); + generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, + $vmfw_conf, $vmid, 'OUT', $ipversion); + } + }; + warn $@ if $@; # just to be sure - should not happen } # generate firewall rules for OpenVZ containers foreach my $vmid (keys %{$vmdata->{openvz}}) { - my $conf = $vmdata->{openvz}->{$vmid}; + eval { + my $conf = $vmdata->{openvz}->{$vmid}; - my $vmfw_conf = $vmfw_configs->{$vmid}; - next if !$vmfw_conf; - next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0); + my $vmfw_conf = $vmfw_configs->{$vmid}; + return if !$vmfw_conf; - if ($conf->{ip_address} && $conf->{ip_address}->{value}) { - my $ip = $conf->{ip_address}->{value}; - $ip =~ s/\s+/,/g; - parse_address_list($ip); # make sure we have a valid $ip list + generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf); - my @ips = split(',', $ip); + if ($vmfw_conf->{options}->{enable}) { + if ($conf->{ip_address} && $conf->{ip_address}->{value}) { + my $ip = $conf->{ip_address}->{value}; + $ip =~ s/\s+/,/g; - foreach my $singleip (@ips) { - my $venet0ipset = {}; - $venet0ipset->{cidr} = $singleip; - push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset; - } + my @ips = (); - generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN'); - generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT'); - } + foreach my $singleip (split(',', $ip)) { + my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list + push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip }; + push @ips, $singleip if $singleip_ver == $ipversion; + } - if ($conf->{netif} && $conf->{netif}->{value}) { - my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value}); - foreach my $netid (keys %$netif) { - my $d = $netif->{$netid}; + if (scalar(@ips)) { + my $ip_list = join(',', @ips); + generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN', $ipversion); + generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT', $ipversion); + } + } + } - my $macaddr = $d->{mac}; - my $iface = $d->{host_ifname}; - generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, - $vmfw_conf, $vmid, 'IN'); - generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, - $vmfw_conf, $vmid, 'OUT'); + if ($conf->{netif} && $conf->{netif}->{value}) { + my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value}); + foreach my $netid (keys %$netif) { + my $d = $netif->{$netid}; + my $bridge = $d->{bridge}; + next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ? + my $macaddr = $d->{mac}; + my $iface = $d->{host_ifname}; + generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, + $vmfw_conf, $vmid, 'IN', $ipversion); + generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr, + $vmfw_conf, $vmid, 'OUT', $ipversion); + } } - } + }; + warn $@ if $@; # just to be sure - should not happen } if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){ ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS"); } - my $ipset_ruleset = {}; - generate_ipset_chains($ipset_ruleset, $cluster_conf); + generate_ipset_chains($ipset_ruleset, undef, $cluster_conf); return ($ruleset, $ipset_ruleset); } @@ -2708,11 +3257,11 @@ sub print_sig_rule { } sub get_ruleset_cmdlist { - my ($ruleset, $verbose) = @_; + my ($ruleset, $verbose, $iptablescmd) = @_; my $cmdlist = "*filter\n"; # we pass this to iptables-restore; - my ($active_chains, $hooks) = iptables_get_chains(); + my ($active_chains, $hooks) = iptables_get_chains($iptablescmd); my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose); # create missing chains first @@ -2725,8 +3274,9 @@ sub get_ruleset_cmdlist { } foreach my $h (qw(INPUT OUTPUT FORWARD)) { - if (!$hooks->{$h}) { - $cmdlist .= "-A $h -j PVEFW-$h\n"; + my $chain = "PVEFW-$h"; + if ($ruleset->{$chain} && !$hooks->{$h}) { + $cmdlist .= "-A $h -j $chain\n"; } } @@ -2785,7 +3335,22 @@ sub get_ipset_cmdlist { } } - foreach my $chain (sort keys %$ruleset) { + # create -v4 and -v6 chains first + foreach my $chain (keys %$ruleset) { + next if $chain !~ m/-v[46]$/; + my $stat = $statushash->{$chain}; + die "internal error" if !$stat; + + if ($stat->{action} eq 'create') { + foreach my $cmd (@{$ruleset->{$chain}}) { + $cmdlist .= "$cmd\n"; + } + } + } + + # then create list chains which use above -v4 and -v6 chains + foreach my $chain (keys %$ruleset) { + next if $chain =~ m/-v[46]$/; my $stat = $statushash->{$chain}; die "internal error" if !$stat; @@ -2794,6 +3359,11 @@ sub get_ipset_cmdlist { $cmdlist .= "$cmd\n"; } } + } + + foreach my $chain (keys %$ruleset) { + my $stat = $statushash->{$chain}; + die "internal error" if !$stat; if ($stat->{action} eq 'update') { my $chain_swap = $chain."_swap"; @@ -2806,11 +3376,21 @@ sub get_ipset_cmdlist { $cmdlist .= "flush $chain_swap\n"; $cmdlist .= "destroy $chain_swap\n"; } + } + + # remove unused list chains first + foreach my $chain (keys %$statushash) { + next if $statushash->{$chain}->{action} ne 'delete'; + next if $chain !~ m/-v[46]$/; + $delete_cmdlist .= "flush $chain\n"; + $delete_cmdlist .= "destroy $chain\n"; } + # the remove unused -v4 -v6 chains foreach my $chain (keys %$statushash) { next if $statushash->{$chain}->{action} ne 'delete'; + next if $chain =~ m/-v[46]$/; $delete_cmdlist .= "flush $chain\n"; $delete_cmdlist .= "destroy $chain\n"; @@ -2822,7 +3402,7 @@ sub get_ipset_cmdlist { } sub apply_ruleset { - my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_; + my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_; enable_bridge_firewall(); @@ -2830,6 +3410,7 @@ sub apply_ruleset { get_ipset_cmdlist($ipset_ruleset, undef, $verbose); my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose); + my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables"); if ($verbose) { if ($ipset_changes) { @@ -2842,12 +3423,31 @@ sub apply_ruleset { print "iptables changes:\n"; print $cmdlist; } + + if ($changesv6) { + print "ip6tables changes:\n"; + print $cmdlistv6; + } } + my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1"; + PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || ''); + ipset_restore_cmdlist($ipset_create_cmdlist); + $tmpfile = "$pve_fw_status_dir/ip4cmdlist"; + PVE::Tools::file_set_contents($tmpfile, $cmdlist || ''); + iptables_restore_cmdlist($cmdlist); + $tmpfile = "$pve_fw_status_dir/ip6cmdlist"; + PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || ''); + + ip6tables_restore_cmdlist($cmdlistv6); + + $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2"; + PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || ''); + ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist; # test: re-read status and check if everything is up to date @@ -2863,6 +3463,17 @@ sub apply_ruleset { } } + my $active_chainsv6 = iptables_get_chains("ip6tables"); + my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0); + + foreach my $chain (sort keys %$rulesetv6) { + my $stat = $statushashv6->{$chain}; + if ($stat->{action} ne 'exists') { + warn "unable to update chain '$chain'\n"; + $errors = 1; + } + } + die "unable to apply firewall changes\n" if $errors; update_nf_conntrack_max($hostfw_conf); @@ -2907,7 +3518,16 @@ sub update_nf_conntrack_tcp_timeout_established { sub remove_pvefw_chains { - my ($chash, $hooks) = iptables_get_chains(); + PVE::Firewall::remove_pvefw_chains_iptables("iptables"); + PVE::Firewall::remove_pvefw_chains_iptables("ip6tables"); + PVE::Firewall::remove_pvefw_chains_ipset(); + +} + +sub remove_pvefw_chains_iptables { + my ($iptablescmd) = @_; + + my ($chash, $hooks) = iptables_get_chains($iptablescmd); my $cmdlist = "*filter\n"; foreach my $h (qw(INPUT OUTPUT FORWARD)) { @@ -2925,7 +3545,33 @@ sub remove_pvefw_chains { } $cmdlist .= "COMMIT\n"; - iptables_restore_cmdlist($cmdlist); + if($iptablescmd eq "ip6tables") { + ip6tables_restore_cmdlist($cmdlist); + } else { + iptables_restore_cmdlist($cmdlist); + } +} + +sub remove_pvefw_chains_ipset { + + my $ipset_chains = ipset_get_chains(); + + my $sub_cmdlist = ""; + my $cmdlist = ""; + + foreach my $chain (keys %$ipset_chains) { + if ($chain =~ m/^PVEFW-\S+\-(v4|v6)$/) { + $sub_cmdlist .= "flush $chain\n"; + $sub_cmdlist .= "destroy $chain\n"; + }else{ + $cmdlist .= "flush $chain\n"; + $cmdlist .= "destroy $chain\n"; + } + } + + $cmdlist .= $sub_cmdlist; + + ipset_restore_cmdlist($cmdlist) if $cmdlist; } sub init { @@ -2939,28 +3585,21 @@ sub init { } sub update { - my ($verbose) = @_; - my $code = sub { my $cluster_conf = load_clusterfw_conf(); my $cluster_options = $cluster_conf->{options}; - my $enable = $cluster_options->{enable}; - - die "Firewall is disabled - cannot start\n" if !$enable; - - if (!$enable) { + if (!$cluster_options->{enable}) { PVE::Firewall::remove_pvefw_chains(); - print "Firewall disabled\n" if $verbose; return; } my $hostfw_conf = load_hostfw_conf(); - my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf); + my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf); - apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose); + apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6); }; run_locked($code);