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 PVE::Network;
+use PVE::SafeSyslog;
use File::Basename;
use File::Path;
use IO::File;
use Net::IP;
-use PVE::Tools qw(run_command lock_file);
+use PVE::Tools qw(run_command lock_file dir_glob_foreach);
use Encode;
+use Storable qw(dclone);
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
+# dynamically include PVE::QemuServer and PVE::LXC
# to avoid dependency problems
my $have_qemu_server;
eval {
require PVE::QemuServer;
+ require PVE::QemuConfig;
$have_qemu_server = 1;
};
-my $have_pve_manager;
+my $have_lxc;
eval {
- require PVE::OpenVZ;
- $have_pve_manager = 1;
+ require PVE::LXC;
+ $have_lxc = 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 = 18;
+
+my $PROTOCOLS_WITH_PORTS = {
+ udp => 1, 17 => 1,
+ udplite => 1, 136 => 1,
+ tcp => 1, 6 => 1,
+ dccp => 1, 33 => 1,
+ sctp => 1, 132 => 1,
+};
+
+PVE::JSONSchema::register_format('IPorCIDR', \&pve_verify_ip_or_cidr);
+sub pve_verify_ip_or_cidr {
my ($cidr, $noerr) = @_;
- if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
- return $cidr if Net::IP->new($cidr);
+ if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
+ return $cidr if Net::IP->new($cidr);
return undef if $noerr;
die Net::IP::Error() . "\n";
}
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 => $max_ipset_name_length,
+});
+
+PVE::JSONSchema::register_standard_option('pve-fw-alias', {
+ description => "Alias name.",
+ type => 'string',
+ pattern => $ip_alias_pattern,
minLength => 2,
- maxLength => 20,
+ maxLength => $max_alias_name_length,
});
PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
description => "Log level.",
- type => 'string',
+ type => 'string',
enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
optional => 1,
});
-my $security_group_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_pattern,
+ pattern => $security_group_name_pattern,
minLength => 2,
- maxLength => 20,
+ maxLength => $max_group_name_length,
});
my $feature_ipset_nomatch = 0;
};
-use Data::Dumper;
-
my $nodename = PVE::INotify::nodename();
my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
-my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
-my $default_log_level = 'info';
+my $default_log_level = 'nolog'; # avoid logs by default
my $log_level_hash = {
debug => 7,
emerg => 0,
};
+# %rule
+#
+# name => optional
+# enable => [0|1]
+# action =>
+# proto =>
+# sport => port[,port[,port]].. or port:port
+# dport => port[,port[,port]].. or port:port
+# log => optional, loglevel
+# logmsg => optional, logmsg - overwrites default
+# iface_in => incomin interface
+# iface_out => outgoing interface
+# match => optional, overwrites generation of match
+# target => optional, overwrites action
+
+# we need to overwrite some macros for ipv6
+my $pve_ipv6fw_macros = {
+ 'Ping' => [
+ { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
+ ],
+ 'NeighborDiscovery' => [
+ "IPv6 neighbor solicitation, neighbor and router advertisement",
+ { action => 'PARAM', proto => 'icmpv6', dport => 'router-solicitation' },
+ { action => 'PARAM', proto => 'icmpv6', dport => 'router-advertisement' },
+ { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-solicitation' },
+ { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-advertisement' },
+ ],
+ 'DHCPv6' => [
+ "DHCPv6 traffic",
+ { action => 'PARAM', proto => 'udp', dport => '546:547', sport => '546:547' },
+ ],
+ 'Trcrt' => [
+ { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
+ { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
+ ],
+ };
+
# imported/converted from: /usr/share/shorewall/macro.*
my $pve_fw_macros = {
'Amanda' => [
{ action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
{ action => 'PARAM', proto => 'udp', dport => '6881' },
],
+ 'Ceph' => [
+ "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
+ { action => 'PARAM', proto => 'tcp', dport => '6789' },
+ { action => 'PARAM', proto => 'tcp', dport => '6800:7300' },
+ ],
'CVS' => [
"Concurrent Versions System pserver traffic",
{ action => 'PARAM', proto => 'tcp', dport => '2401' },
{ action => 'PARAM', proto => 'tcp', dport => '6277' },
],
'DHCPfwd' => [
- "Forwarded DHCP traffic (bidirectional)",
+ "Forwarded DHCP traffic",
{ action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '67:68', sport => '67:68' },
],
'DNS' => [
"Domain Name System traffic (upd and tcp)",
{ action => 'PARAM', proto => 'udp', dport => '1080' },
],
'GRE' => [
- "Generic Routing Encapsulation tunneling protocol (bidirectional)",
+ "Generic Routing Encapsulation tunneling protocol",
{ action => 'PARAM', proto => '47' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
],
'Git' => [
"Git distributed revision control traffic",
{ action => 'PARAM', proto => 'tcp', dport => '993' },
],
'IPIP' => [
- "IPIP capsulation traffic (bidirectional)",
+ "IPIP capsulation traffic",
{ action => 'PARAM', proto => '94' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '94' },
],
'IPsec' => [
- "IPsec traffic (bidirectional)",
+ "IPsec traffic",
{ action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
{ action => 'PARAM', proto => '50' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
],
'IPsecah' => [
- "IPsec authentication (AH) traffic (bidirectional)",
+ "IPsec authentication (AH) traffic",
{ action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
{ action => 'PARAM', proto => '51' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '51' },
],
'IPsecnat' => [
- "IPsec traffic and Nat-Traversal (bidirectional)",
+ "IPsec traffic and Nat-Traversal",
{ action => 'PARAM', proto => 'udp', dport => '500' },
{ action => 'PARAM', proto => 'udp', dport => '4500' },
{ action => 'PARAM', proto => '50' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '4500' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
],
'IRC' => [
"Internet Relay Chat traffic",
'L2TP' => [
"Layer 2 Tunneling Protocol traffic",
{ action => 'PARAM', proto => 'udp', dport => '1701' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1701' },
],
'LDAP' => [
"Lightweight Directory Access Protocol traffic",
{ action => 'PARAM', proto => 'tcp', dport => '465' },
{ action => 'PARAM', proto => 'tcp', dport => '587' },
],
+ 'MDNS' => [
+ "Multicast DNS",
+ { action => 'PARAM', proto => 'udp', dport => '5353' },
+ ],
'Munin' => [
"Munin networked resource monitoring traffic",
{ action => 'PARAM', proto => 'tcp', dport => '4949' },
"Network Time Protocol (ntpd)",
{ action => 'PARAM', proto => 'udp', dport => '123' },
],
- 'NTPbi' => [
- "Bi-directional NTP (for NTP peers)",
- { action => 'PARAM', proto => 'udp', dport => '123' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '123' },
- ],
'OSPF' => [
"OSPF multicast traffic",
{ action => 'PARAM', proto => '89' },
'PPtP' => [
"Point-to-Point Tunneling Protocol",
{ action => 'PARAM', proto => '47' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
{ action => 'PARAM', proto => 'tcp', dport => '1723' },
],
'Ping' => [
"Microsoft Remote Desktop Protocol traffic",
{ action => 'PARAM', proto => 'tcp', dport => '3389' },
],
- 'RIPbi' => [
+ 'RIP' => [
"Routing Information Protocol (bidirectional)",
{ action => 'PARAM', proto => 'udp', dport => '520' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '520' },
],
'RNDC' => [
"BIND remote management protocol",
{ action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
{ action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
],
- 'SMBBI' => [
- "Microsoft SMB traffic (bidirectional)",
- { action => 'PARAM', proto => 'udp', dport => '135,445' },
- { action => 'PARAM', proto => 'udp', dport => '137:139' },
- { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
- { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '135,445' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '137:139' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1024:65535', sport => '137' },
- { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'tcp', dport => '135,139,445' },
- ],
'SMBswat' => [
"Samba Web Administration Tool",
{ action => 'PARAM', proto => 'tcp', dport => '901' },
{ 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",
my $pve_fw_parsed_macros;
my $pve_fw_macro_descr;
+my $pve_fw_macro_ipversion = {};
my $pve_fw_preferred_macro_names = {};
-my $pve_std_chains = {
+my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
+my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
+
+my $pve_std_chains = {};
+my $pve_std_chains_conf = {};
+$pve_std_chains_conf->{4} = {
'PVEFW-SET-ACCEPT-MARK' => [
- "-j MARK --set-mark 1",
+ { target => "-j MARK --set-mark $FWACCEPTMARK_ON" },
],
'PVEFW-DropBroadcast' => [
# same as shorewall 'Broadcast'
{ action => 'DROP', dsttype => 'BROADCAST' },
{ action => 'DROP', source => '224.0.0.0/4' },
{ action => 'DROP', proto => 'icmp' },
- "-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",
+ { match => '-p tcp', target => '-j REJECT --reject-with tcp-reset' },
+ { match => '-p udp', target => '-j REJECT --reject-with icmp-port-unreachable' },
+ { match => '-p icmp', target => '-j REJECT --reject-with icmp-host-unreachable' },
+ { target => '-j REJECT --reject-with icmp-host-prohibited' },
],
'PVEFW-Drop' => [
# same as shorewall 'Drop', which is equal to DROP,
{ action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
{ action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
# Drop packets with INVALID state
- "-m conntrack --ctstate INVALID -j DROP",
+ { action => 'DROP', match => '-m conntrack --ctstate INVALID', },
# 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 => '135,445' },
+ { 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 => 'tcp', dport => '135,139,445' },
{ 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",
+ { action => 'DROP', match => '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
# Drop DNS replies
{ action => 'DROP', proto => 'udp', sport => 53 },
],
{ action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
{ action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
# Drop packets with INVALID state
- "-m conntrack --ctstate INVALID -j DROP",
+ { action => 'DROP', match => '-m conntrack --ctstate INVALID', },
# Drop Microsoft SMB noise
- { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
+ { action => 'PVEFW-reject', proto => 'udp', dport => '135,445' },
{ 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 => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445' },
{ 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",
+ { action => 'DROP', match => '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
# 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",
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags SYN,RST SYN,RST', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN', target => '-g PVEFW-logflags' },
],
'PVEFW-smurfs' => [
# same as shorewall smurfs action
# Filter packets for smurfs (packets with a broadcast address as the source).
- "-s 0.0.0.0/32 -j RETURN",
- "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
- "-s 224.0.0.0/4 -g PVEFW-smurflog",
+ { match => '-s 0.0.0.0/32', target => '-j RETURN' }, # allow DHCP
+ { match => '-m addrtype --src-type BROADCAST', target => '-g PVEFW-smurflog' },
+ { match => '-s 224.0.0.0/4', target => '-g PVEFW-smurflog' },
+ ],
+ 'PVEFW-smurflog' => [
+ { action => 'DROP', logmsg => 'DROP: ' },
+ ],
+ 'PVEFW-logflags' => [
+ { action => 'DROP', logmsg => 'DROP: ' },
+ ],
+};
+
+$pve_std_chains_conf->{6} = {
+ 'PVEFW-SET-ACCEPT-MARK' => [
+ { target => "-j MARK --set-mark $FWACCEPTMARK_ON" },
+ ],
+ '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' },
+ { match => '-p tcp', target => '-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
+ { action => 'DROP', match => '-m conntrack --ctstate INVALID', },
+ # Drop Microsoft SMB noise
+ { action => 'DROP', proto => 'udp', dport => '135,445' },
+ { action => 'DROP', proto => 'udp', dport => '137:139'},
+ { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
+ { action => 'DROP', proto => 'tcp', dport => '135,139,445' },
+ { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
+ # Drop new/NotSyn traffic so that it doesn't get logged
+ { action => 'DROP', match => '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
+ # 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
+ { action => 'DROP', match => '-m conntrack --ctstate INVALID', },
+ # Drop Microsoft SMB noise
+ { action => 'PVEFW-reject', proto => 'udp', dport => '135,445' },
+ { 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' },
+ { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
+ # Drop new/NotSyn traffic so that it doesn't get logged
+ { action => 'DROP', match => '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
+ # 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
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags SYN,RST SYN,RST', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN', target => '-g PVEFW-logflags' },
+ { match => '-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN', target => '-g PVEFW-logflags' },
+ ],
+ 'PVEFW-logflags' => [
+ { action => 'DROP', logmsg => 'DROP: ' },
],
};
'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,
+ 'neighbor-solicitation' => 1,
+ 'neighbour-solicitation' => 1,
+ 'neighbor-advertisement' => 1,
+ 'neighbour-advertisement' => 1,
+ 'redirect' => 1,
+};
+
sub init_firewall_macros {
$pve_fw_parsed_macros = {};
- foreach my $k (keys %$pve_fw_macros) {
+ my $parse = sub {
+ my ($k, $macro) = @_;
my $lc_name = lc($k);
- my $macro = $pve_fw_macros->{$k};
- if (!ref($macro->[0])) {
- $pve_fw_macro_descr->{$k} = shift @$macro;
+ $pve_fw_macro_ipversion->{$k} = 0;
+ while (!ref($macro->[0])) {
+ my $desc = shift @$macro;
+ if ($desc eq 'ipv4only') {
+ $pve_fw_macro_ipversion->{$k} = 4;
+ } elsif ($desc eq 'ipv6only') {
+ $pve_fw_macro_ipversion->{$k} = 6;
+ } else {
+ $pve_fw_macro_descr->{$k} = $desc;
+ }
}
$pve_fw_preferred_macro_names->{$lc_name} = $k;
$pve_fw_parsed_macros->{$k} = $macro;
+ };
+
+ foreach my $k (keys %$pve_fw_macros) {
+ &$parse($k, $pve_fw_macros->{$k});
+ }
+
+ foreach my $k (keys %$pve_ipv6fw_macros) {
+ next if $pve_fw_parsed_macros->{$k};
+ &$parse($k, $pve_ipv6fw_macros->{$k});
+ $pve_fw_macro_ipversion->{$k} = 6;
}
}
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 $__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 $isv6 = $testip->version == 6;
+ my $routes = $isv6 ? PVE::ProcFSTools::read_proc_net_ipv6_route()
+ : PVE::ProcFSTools::read_proc_net_route();
+ foreach my $entry (@$routes) {
+ my $mask;
+ if ($isv6) {
+ $mask = $entry->{prefix};
+ next if !$mask; # skip the default route...
+ } else {
+ $mask = $PVE::Network::ipv4_mask_hash_localnet->{$entry->{mask}};
+ next if !defined($mask);
+ }
+ my $cidr = "$entry->{dest}/$mask";
+ my $testnet = Net::IP->new($cidr);
+ my $overlap = $testnet->overlaps($testip);
+ if ($overlap == $Net::IP::IP_B_IN_A_OVERLAP ||
+ $overlap == $Net::IP::IP_IDENTICAL)
+ {
+ $__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("PVEFW-") - length("_swap");
+
+sub compute_ipset_chain_name {
+ my ($vmid, $ipset_name, $ipversion) = @_;
+
+ $vmid = 0 if !defined($vmid);
+
+ my $id = "$vmid-${ipset_name}-v$ipversion";
+
+ if (length($id) > $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
+ 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;
- foreach my $elem (split(/,/, $str)) {
+ my $ipversion;
+
+ my @elements = split(/,/, $str);
+ die "extraneous commas in list\n" if $str ne join(',', @elements);
+ foreach my $elem (@elements) {
$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 {
- my ($str) = @_;
+ my ($str, $dport) = @_;
my $services = PVE::Firewall::get_etc_services();
my $count = 0;
my $icmp_port = 0;
- foreach my $item (split(/,/, $str)) {
+ my @elements = split(/,/, $str);
+ die "extraneous commas in list\n" if $str ne join(',', @elements);
+ foreach my $item (@elements) {
$count++;
if ($item =~ m/^(\d+):(\d+)$/) {
my ($port1, $port2) = ($1, $2);
my $port = $1;
die "invalid port '$port'\n" if $port > 65535;
} else {
- if ($icmp_type_names->{$item}) {
+ if ($dport && $icmp_type_names->{$item}) {
+ $icmp_port = 1;
+ } elsif ($dport && $icmpv6_type_names->{$item}) {
$icmp_port = 1;
} else {
- die "invalid port '$item'\n" if !$services->{byname}->{$item};
+ die "invalid port '$item'\n" if !$services->{byname}->{$item};
}
}
}
return $count;
}
-PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
-sub pve_fw_verify_port_spec {
+PVE::JSONSchema::register_format('pve-fw-sport-spec', \&pve_fw_verify_sport_spec);
+sub pve_fw_verify_sport_spec {
+ my ($portstr) = @_;
+
+ parse_port_name_number_or_range($portstr, 0);
+
+ return $portstr;
+}
+
+PVE::JSONSchema::register_format('pve-fw-dport-spec', \&pve_fw_verify_dport_spec);
+sub pve_fw_verify_dport_spec {
my ($portstr) = @_;
- parse_port_name_number_or_range($portstr);
+ parse_port_name_number_or_range($portstr, 1);
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);
$sha->add($k, ':', $v, "\n");
}
- my $digest = $sha->b64digest;
+ my $digest = $sha->hexdigest;
$res->{digest} = $digest;
my $v = $entry->{$k};
next if !defined($v);
$data->{$k} = $v;
- $sha->add($k, ':', $v, "\n");
+ # Note: digest ignores refs ($rule->{errors})
+ # since Digest::SHA expects a series of bytes,
+ # we have to encode the value here to prevent errors when
+ # using utf8 characters (eg. in comments)
+ $sha->add($k, ':', encode_utf8($v), "\n") if !ref($v); ;
}
push @$res, $data;
}
- my $digest = $sha->b64digest;
+ my $digest = $sha->hexdigest;
foreach my $entry (@$res) {
$entry->{digest} = $digest;
return wantarray ? ($res, $digest) : $res;
}
+our $cluster_option_properties = {
+ enable => {
+ description => "Enable or disable the firewall cluster wide.",
+ type => 'integer',
+ minimum => 0,
+ optional => 1,
+ },
+ policy_in => {
+ description => "Input policy.",
+ type => 'string',
+ optional => 1,
+ enum => ['ACCEPT', 'REJECT', 'DROP'],
+ },
+ policy_out => {
+ description => "Output policy.",
+ type => 'string',
+ optional => 1,
+ enum => ['ACCEPT', 'REJECT', 'DROP'],
+ },
+};
+
+our $host_option_properties = {
+ enable => {
+ description => "Enable host firewall rules.",
+ type => 'boolean',
+ optional => 1,
+ },
+ log_level_in => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for incoming traffic." }),
+ log_level_out => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for outgoing traffic." }),
+ tcp_flags_log_level => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for illegal tcp flags filter." }),
+ smurf_log_level => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for SMURFS filter." }),
+ nosmurfs => {
+ description => "Enable SMURFS filter.",
+ type => 'boolean',
+ optional => 1,
+ },
+ tcpflags => {
+ description => "Filter illegal combinations of TCP flags.",
+ type => 'boolean',
+ optional => 1,
+ },
+ nf_conntrack_max => {
+ description => "Maximum number of tracked connections.",
+ type => 'integer',
+ optional => 1,
+ minimum => 32768,
+ },
+ nf_conntrack_tcp_timeout_established => {
+ description => "Conntrack established timeout.",
+ type => 'integer',
+ optional => 1,
+ minimum => 7875,
+ },
+ ndp => {
+ description => "Enable NDP.",
+ type => 'boolean',
+ optional => 1,
+ },
+};
+
+our $vm_option_properties = {
+ enable => {
+ description => "Enable/disable firewall rules.",
+ type => 'boolean',
+ optional => 1,
+ },
+ macfilter => {
+ description => "Enable/disable MAC address filter.",
+ type => 'boolean',
+ optional => 1,
+ },
+ dhcp => {
+ description => "Enable DHCP.",
+ type => 'boolean',
+ optional => 1,
+ },
+ ndp => {
+ description => "Enable NDP.",
+ type => 'boolean',
+ optional => 1,
+ },
+ radv => {
+ description => "Allow sending Router Advertisement.",
+ type => 'boolean',
+ optional => 1,
+ },
+ ipfilter => {
+ description => "Enable default IP filters. " .
+ "This is equivalent to adding an empty ipfilter-net<id> ipset " .
+ "for every interface. Such ipsets implicitly contain sane default " .
+ "restrictions such as restricting IPv6 link local addresses to " .
+ "the one derived from the interface's MAC address. For containers " .
+ "the configured IP addresses will be implicitly added.",
+ type => 'boolean',
+ optional => 1,
+ },
+ policy_in => {
+ description => "Input policy.",
+ type => 'string',
+ optional => 1,
+ enum => ['ACCEPT', 'REJECT', 'DROP'],
+ },
+ policy_out => {
+ description => "Output policy.",
+ type => 'string',
+ optional => 1,
+ enum => ['ACCEPT', 'REJECT', 'DROP'],
+ },
+ log_level_in => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for incoming traffic." }),
+ log_level_out => get_standard_option('pve-fw-loglevel', {
+ description => "Log level for outgoing traffic." }),
+
+};
+
+
+my $addr_list_descr = "This can refer to a single IP address, an IP set ('+ipsetname') or an IP alias definition. You can also specify an address range like '20.34.101.207-201.3.9.99', or a list of IP addresses and networks (entries are separated by comma). Please do not mix IPv4 and IPv6 addresses inside such lists.";
+
+my $port_descr = "You can use service names or simple numbers (0-65535), as defined in '/etc/services'. Port ranges can be specified with '\\d+:\\d+', for example '80:85', and you can use comma separated list to match several ports or ranges.";
+
my $rule_properties = {
pos => {
description => "Update rule at position <pos>.",
},
digest => get_standard_option('pve-config-digest'),
type => {
+ description => "Rule type.",
type => 'string',
optional => 1,
enum => ['in', 'out', 'group'],
description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
type => 'string',
optional => 1,
- pattern => $security_group_pattern,
+ pattern => $security_group_name_pattern,
maxLength => 20,
minLength => 2,
},
macro => {
+ description => "Use predefined standard macro.",
type => 'string',
optional => 1,
maxLength => 128,
},
- iface => get_standard_option('pve-iface', { optional => 1 }),
+ iface => get_standard_option('pve-iface', {
+ description => "Network interface name. You have to use network configuration key names for VMs and containers ('net\\d+'). Host related rules can use arbitrary strings.",
+ optional => 1
+ }),
source => {
- type => 'string', format => 'pve-fw-v4addr-spec',
+ description => "Restrict packet source address. $addr_list_descr",
+ type => 'string', format => 'pve-fw-addr-spec',
optional => 1,
},
dest => {
- type => 'string', format => 'pve-fw-v4addr-spec',
+ description => "Restrict packet destination address. $addr_list_descr",
+ type => 'string', format => 'pve-fw-addr-spec',
optional => 1,
},
proto => {
+ description => "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
type => 'string', format => 'pve-fw-protocol-spec',
optional => 1,
},
enable => {
- type => 'boolean',
+ description => "Flag to enable/disable a rule.",
+ type => 'integer',
+ minimum => 0,
optional => 1,
},
sport => {
- type => 'string', format => 'pve-fw-port-spec',
+ description => "Restrict TCP/UDP source port. $port_descr",
+ type => 'string', format => 'pve-fw-sport-spec',
optional => 1,
},
dport => {
- type => 'string', format => 'pve-fw-port-spec',
+ description => "Restrict TCP/UDP destination port. $port_descr",
+ type => 'string', format => 'pve-fw-dport-spec',
optional => 1,
},
comment => {
+ description => "Descriptive comment.",
type => 'string',
optional => 1,
},
sub delete_rule_properties {
my ($rule, $delete_str) = @_;
-
+
foreach my $opt (PVE::Tools::split_list($delete_str)) {
raise_param_exc({ 'delete' => "no such property ('$opt')"})
if !defined($rule_properties->{$opt});
}
my $apply_macro = sub {
- my ($macro_name, $param, $verify) = @_;
+ my ($macro_name, $param, $verify, $ipversion) = @_;
my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
+ if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
+ $macro_rules = $pve_ipv6fw_macros->{$macro_name};
+ }
+
+ # skip macros which are specific to another ipversion
+ if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
+ return if $ipversion != $required;
+ }
+
my $rules = [];
foreach my $templ (@$macro_rules) {
if (!defined($v)) {
my $msg = "missing parameter '$k' in macro '$macro_name'";
- raise_param_exc({ macro => $msg }) if $verify;
+ raise_param_exc({ macro => $msg }) if $verify;
die "$msg\n";
}
$rule->{$k} = $v;
if (defined($rule->{$k})) {
if ($rule->{$k} ne $param->{$k}) {
my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
- raise_param_exc({ $k => $msg }) if $verify;
+ raise_param_exc({ $k => $msg }) if $verify;
die "$msg\n";
}
} else {
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_pattern}$/;
- } else {
- raise_param_exc({ type => "unknown rule type '$type'"});
- }
-
- # fixme: verify $rule->{iface}?
+ my $allow_iface = $rule_env_iface_lookup->{$rule_env};
+ die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
- 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;
- }
+ my $errors = $rule->{errors} || {};
- if ($rule->{dport}) {
- eval { parse_port_name_number_or_range($rule->{dport}); };
- raise_param_exc({ dport => $@ }) if $@;
- }
+ my $error_count = 0;
- if ($rule->{sport}) {
- eval { parse_port_name_number_or_range($rule->{sport}); };
- raise_param_exc({ sport => $@ }) if $@;
- }
+ my $add_error = sub {
+ my ($param, $msg) = @_;
+ chomp $msg;
+ raise_param_exc({ $param => $msg }) if !$noerr;
+ $error_count++;
+ $errors->{$param} = $msg if !$errors->{$param};
+ };
- if ($rule->{source}) {
- eval { parse_address_list($rule->{source}); };
- raise_param_exc({ source => $@ }) if $@;
- }
+ 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;
+ }
+ };
- if ($rule->{dest}) {
- eval { parse_address_list($rule->{dest}); };
- raise_param_exc({ dest => $@ }) if $@;
- }
+ my $check_ipset_or_alias_property = sub {
+ my ($name, $expected_ipversion) = @_;
- if ($rule->{macro}) {
- &$apply_macro($rule->{macro}, $rule, 1);
- }
+ 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 ? $fw_conf->{aliases}->{$alias} : undef;
+ $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}); };
+ &$add_error('iface', $@) if $@;
+ if ($rule_env eq 'vm' || $rule_env eq 'ct') {
+ &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
+ if $rule->{iface} !~ m/^net(\d+)$/;
+ }
+ }
+
+ if ($rule->{macro}) {
+ 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}, 1); };
+ &$add_error('dport', $@) if $@;
+ my $proto = $rule->{proto};
+ &$add_error('proto', "missing property - 'dport' requires this property")
+ if !$proto;
+ &$add_error('dport', "protocol '$proto' does not support ports")
+ if !$PROTOCOLS_WITH_PORTS->{$proto} &&
+ $proto ne 'icmp' && $proto ne 'icmpv6'; # special cases
+ }
+
+ if ($rule->{sport}) {
+ eval { parse_port_name_number_or_range($rule->{sport}, 0); };
+ &$add_error('sport', $@) if $@;
+ my $proto = $rule->{proto};
+ &$add_error('proto', "missing property - 'sport' requires this property")
+ if !$proto;
+ &$add_error('sport', "protocol '$proto' does not support ports")
+ if !$PROTOCOLS_WITH_PORTS->{$proto};
+ }
+
+ if ($rule->{source}) {
+ 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 {
+ my $dest_ipversion = parse_address_list($rule->{dest});
+ &$set_ip_version($dest_ipversion);
+ };
+ &$add_error('dest', $@) if $@;
+ &$check_ipset_or_alias_property('dest', $ipversion);
+ }
+
+ $rule->{ipversion} = $ipversion if $ipversion;
+
+ if ($rule->{macro} && !$error_count) {
+ eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
+ 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;
return $rule;
}
} 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;
$bridge_firewall_enabled = 1;
}
-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("/sbin/ipset restore", input => $cmdlist, errmsg => "ipset_restore_cmdlist");
}
sub iptables_get_chains {
+ my ($iptablescmd) = @_;
+
+ $iptablescmd = "iptables" if !$iptablescmd;
my $res = {};
return 1 if $name =~ m/^PVEFW-\S+$/;
- return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
+ return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
- return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
+ return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
- return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
-
- return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
- return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
+ return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
+ return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
return undef;
};
}
};
- run_command("/sbin/iptables-save", outfunc => $parser);
+ run_command("/sbin/$iptablescmd-save", outfunc => $parser);
return wantarray ? ($res, $hooks) : $res;
}
}
};
- run_command("/usr/sbin/ipset save", outfunc => $parser);
+ run_command("/sbin/ipset save", outfunc => $parser);
# compute digest for each chain
foreach my $chain (keys %$chains) {
return $res;
}
-sub ruleset_generate_cmdstr {
- my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
+# substitude action of rule according to action hash
+sub rule_substitude_action {
+ my ($rule, $actions) = @_;
+
+ if (my $action = $rule->{action}) {
+ $rule->{action} = $actions->{$action} if defined($actions->{$action});
+ }
+}
+
+# generate a src or dst match
+# $dir(ection) is either d or s
+sub ipt_gen_src_or_dst_match {
+ my ($adr, $dir, $ipversion, $cluster_conf, $fw_conf) = @_;
+
+ my $srcdst;
+ if ($dir eq 's') {
+ $srcdst = "src";
+ } elsif ($dir eq 'd') {
+ $srcdst = "dst";
+ } else {
+ die "ipt_gen_src_or_dst_match: invalid direction $dir \n";
+ }
+
+ my $match;
+ if ($adr =~ m/^\+/) {
+ if ($adr =~ m/^\+(${ipset_name_pattern})$/) {
+ my $name = $1;
+ my $ipset_chain;
+ if ($fw_conf && $fw_conf->{ipset}->{$name}) {
+ $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
+ } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
+ $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
+ } else {
+ die "no such ipset '$name'\n";
+ }
+ $match = "-m set --match-set ${ipset_chain} ${srcdst}";
+ } else {
+ die "invalid security group name '$adr'\n";
+ }
+ } elsif ($adr =~ m/^${ip_alias_pattern}$/){
+ my $alias = lc($adr);
+ my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
+ $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
+ die "no such alias '$adr'\n" if !$e;
+ $match = "-${dir} $e->{cidr}";
+ } elsif ($adr =~ m/\-/){
+ $match = "-m iprange --${srcdst}-range $adr";
+ } else {
+ $match = "-${dir} $adr";
+ }
+
+ return $match;
+}
+
+# convert a %rule to an array of iptables commands
+sub ipt_rule_to_cmds {
+ my ($rule, $chain, $ipversion, $cluster_conf, $fw_conf, $vmid) = @_;
+
+ die "ipt_rule_to_cmds unable to handle macro" if $rule->{macro}; #should not happen
+
+ my @match = ();
+
+ if (defined $rule->{match}) {
+ push @match, $rule->{match};
+ } else {
+ push @match, "-i $rule->{iface_in}" if $rule->{iface_in};
+ push @match, "-o $rule->{iface_out}" if $rule->{iface_out};
+
+ if ($rule->{source}) {
+ push @match, ipt_gen_src_or_dst_match($rule->{source}, 's', $ipversion, $cluster_conf, $fw_conf);
+ }
+ if ($rule->{dest}) {
+ push @match, ipt_gen_src_or_dst_match($rule->{dest}, 'd', $ipversion, $cluster_conf, $fw_conf);
+ }
+
+ if (my $proto = $rule->{proto}) {
+ push @match, "-p $proto";
+
+ my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}, 1) : 0;
+ my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}, 0) : 0;
+
+ my $multiport = 0;
+ $multiport++ if $nbdport > 1;
+ $multiport++ if $nbsport > 1;
+
+ push @match, "--match multiport" if $multiport;
+
+ die "multiport: option '--sports' cannot be used together with '--dports'\n"
+ if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
+
+ if ($rule->{dport}) {
+ 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}});
+ 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}});
+ push @match, "-m icmpv6 --icmpv6-type $rule->{dport}";
+ } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
+ die "protocol $proto does not have ports\n";
+ } else {
+ if ($nbdport > 1) {
+ if ($multiport == 2) {
+ push @match, "--ports $rule->{dport}";
+ } else {
+ push @match, "--dports $rule->{dport}";
+ }
+ } else {
+ push @match, "--dport $rule->{dport}";
+ }
+ }
+ }
+
+ if ($rule->{sport}) {
+ die "protocol $proto does not have ports\n"
+ if !$PROTOCOLS_WITH_PORTS->{$proto};
+ if ($nbsport > 1) {
+ push @match, "--sports $rule->{sport}" if $multiport != 2;
+ } else {
+ push @match, "--sport $rule->{sport}";
+ }
+ }
+ } elsif ($rule->{dport} || $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 @match, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
+ }
+ my $matchstr = scalar(@match) ? join(' ', @match) : "";
+
+ my $targetstr;
+ if (defined $rule->{target}) {
+ $targetstr = $rule->{target};
+ } else {
+ my $action = (defined $rule->{action}) ? $rule->{action} : "";
+ my $goto = 1 if $action eq 'PVEFW-SET-ACCEPT-MARK';
+ $targetstr = ($goto) ? "-g $action" : "-j $action";
+ }
+
+ my @iptcmds;
+ if (defined $rule->{log} && $rule->{log}) {
+ my $logaction = get_log_rule_base($chain, $vmid, $rule->{logmsg}, $rule->{log});
+ push @iptcmds, "-A $chain $matchstr $logaction";
+ }
+ push @iptcmds, "-A $chain $matchstr $targetstr";
+ return @iptcmds;
+}
+
+sub ruleset_generate_match {
+ my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
return if defined($rule->{enable}) && !$rule->{enable};
+ return if $rule->{errors};
+
+ return $rule->{match} if defined $rule->{match};
die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
- my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
- my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
+ my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}, 1) : 0;
+ my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}, 0) : 0;
my @cmd = ();
my $source = $rule->{source};
my $dest = $rule->{dest};
- if ($source) {
- if ($source =~ m/^(\+)(\S+)$/) {
- die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
- push @cmd, "-m set --match-set PVEFW-$2 src";
-
- } elsif ($source =~ m/\-/){
- push @cmd, "-m iprange --src-range $source";
+ push @cmd, ipt_gen_src_or_dst_match($source, 's', $ipversion, $cluster_conf, $fw_conf) if $source;
+ push @cmd, ipt_gen_src_or_dst_match($dest, 'd', $ipversion, $cluster_conf, $fw_conf) if $dest;
- } else {
- push @cmd, "-s $source";
- }
- }
-
- if ($dest) {
- if ($dest =~ m/^(\+)(\S+)$/) {
- die "no such ipset $2" if !$cluster_conf->{ipset}->{$2};
- push @cmd, "-m set --match-set PVEFW-$2 dst";
-
- } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
- push @cmd, "-m iprange --dst-range $dest";
-
- } else {
- push @cmd, "-d $dest";
- }
- }
-
- if ($rule->{proto}) {
- push @cmd, "-p $rule->{proto}";
+ if (my $proto = $rule->{proto}) {
+ push @cmd, "-p $proto";
my $multiport = 0;
$multiport++ if $nbdport > 1;
if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
if ($rule->{dport}) {
- if ($rule->{proto} && $rule->{proto} eq 'icmp') {
+ if ($proto eq 'icmp') {
# Note: we use dport to store --icmp-type
- die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
+ die "unknown icmp-type '$rule->{dport}'\n"
+ if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
push @cmd, "-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}});
+ push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
+ } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
+ die "protocol $proto does not have ports\n";
} else {
if ($nbdport > 1) {
if ($multiport == 2) {
}
if ($rule->{sport}) {
+ die "protocol $proto does not have ports\n"
+ if !$PROTOCOLS_WITH_PORTS->{$proto};
if ($nbsport > 1) {
push @cmd, "--sports $rule->{sport}" if $multiport != 2;
} else {
}
}
} 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};
+ return scalar(@cmd) ? join(' ', @cmd) : undef;
+}
+
+sub ruleset_generate_action {
+ my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
+
+ return $rule->{target} if defined $rule->{target};
+
+ my @cmd = ();
+
if (my $action = $rule->{action}) {
$action = $actions->{$action} if defined($actions->{$action});
$goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
}
sub ruleset_generate_rule {
- my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
+ my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
my $rules;
if ($rule->{macro}) {
- $rules = &$apply_macro($rule->{macro}, $rule);
+ $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
} else {
$rules = [ $rule ];
}
- foreach my $tmp (@$rules) {
- if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
- ruleset_addrule($ruleset, $chain, $cmdstr);
- }
+ # update all or nothing
+ my @ipt_rule_cmds;
+ foreach my $r (@$rules) {
+ push @ipt_rule_cmds, ipt_rule_to_cmds($r, $chain, $ipversion, $cluster_conf, $fw_conf);
+ }
+ foreach my $c (@ipt_rule_cmds) {
+ ruleset_add_ipt_cmd($ruleset, $chain, $c);
}
}
sub ruleset_generate_rule_insert {
- my ($ruleset, $chain, $rule, $actions, $goto) = @_;
+ my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
die "implement me" if $rule->{macro}; # not implemented, because not needed so far
- if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
- ruleset_insertrule($ruleset, $chain, $cmdstr);
+ my $match = ruleset_generate_match($ruleset, $chain, $ipversion, $rule, $actions, $goto);
+ my $action = ruleset_generate_action($ruleset, $chain, $ipversion, $rule, $actions, $goto);
+ if (defined $match && defined $action) {
+ ruleset_insertrule($ruleset, $chain, $match, $action);
}
}
return $ruleset->{$chain} ? 1 : undef;
}
+# add an iptables command (like generated by ipt_rule_to_cmds) to a chain
+sub ruleset_add_ipt_cmd {
+ my ($ruleset, $chain, $iptcmd) = @_;
+
+ die "no such chain '$chain'\n" if !$ruleset->{$chain};
+
+ push @{$ruleset->{$chain}}, $iptcmd;
+}
+
sub ruleset_addrule {
- my ($ruleset, $chain, $rule) = @_;
+ my ($ruleset, $chain, $match, $action, $log, $logmsg, $vmid) = @_;
die "no such chain '$chain'\n" if !$ruleset->{$chain};
- push @{$ruleset->{$chain}}, "-A $chain $rule";
+ if (defined($log) && $log) {
+ my $logaction = get_log_rule_base($chain, $vmid, $logmsg, $log);
+ push @{$ruleset->{$chain}}, "-A $chain $match $logaction";
+ }
+ push @{$ruleset->{$chain}}, "-A $chain $match $action";
}
sub ruleset_insertrule {
- my ($ruleset, $chain, $rule) = @_;
+ my ($ruleset, $chain, $match, $action, $log) = @_;
die "no such chain '$chain'\n" if !$ruleset->{$chain};
- unshift @{$ruleset->{$chain}}, "-A $chain $rule";
+ unshift @{$ruleset->{$chain}}, "-A $chain $match $action";
}
sub get_log_rule_base {
my ($chain, $vmid, $msg, $loglevel) = @_;
- die "internal error - no log level" if !defined($loglevel);
-
$vmid = 0 if !defined($vmid);
+ $msg = "" if !defined($msg);
# Note: we use special format for prefix to pass further
- # info to log daemon (VMID, LOGVELEL and CHAIN)
+ # info to log daemon (VMID, LOGLEVEL and CHAIN)
return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
}
-sub ruleset_addlog {
- my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
-
- return if !defined($loglevel);
-
- my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
+sub ruleset_add_chain_policy {
+ my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
- $logrule = "$rule $logrule" if defined($rule);
+ if ($policy eq 'ACCEPT') {
- ruleset_addrule($ruleset, $chain, $logrule)
-}
+ my $rule = { action => 'ACCEPT' };
+ rule_substitude_action($rule, { ACCEPT => $accept_action});
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
-sub generate_bridge_chains {
- my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
+ } elsif ($policy eq 'DROP') {
- my $options = $hostfw_conf->{options} || {};
+ ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Drop");
- die "error: detected direct route to bridge '$bridge'\n"
- if !$options->{allow_bridge_route} && $routing_table->{$bridge};
+ ruleset_addrule($ruleset, $chain, "", "-j DROP", $loglevel, "policy $policy: ", $vmid);
+ } elsif ($policy eq 'REJECT') {
+ ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Reject");
- if (!ruleset_chain_exist($ruleset, "$bridge-FW")) {
- ruleset_create_chain($ruleset, "$bridge-FW");
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -m physdev --physdev-is-out -j $bridge-FW");
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -m physdev --physdev-is-in -j $bridge-FW");
+ ruleset_addrule($ruleset, $chain, "", "-g PVEFW-reject", $loglevel, "policy $policy:", $vmid);
+ } else {
+ # should not happen
+ die "internal error: unknown policy '$policy'";
}
+}
- if (!ruleset_chain_exist($ruleset, "$bridge-OUT")) {
- ruleset_create_chain($ruleset, "$bridge-OUT");
- ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-in -j $bridge-OUT");
- ruleset_insertrule($ruleset, "PVEFW-INPUT", "-i $bridge -m physdev --physdev-is-in -j $bridge-OUT");
- }
+sub ruleset_chain_add_ndp {
+ my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
+ return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
- if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
- ruleset_create_chain($ruleset, "$bridge-IN");
- ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j $bridge-IN");
- ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
- # accept traffic to unmanaged bridge ports
- ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-out -j ACCEPT ");
+ ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-solicitation", $accept);
+ if ($direction ne 'OUT' || $options->{radv}) {
+ ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", $accept);
}
+ ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-solicitation", $accept);
+ ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-advertisement", $accept);
}
-sub ruleset_add_chain_policy {
- my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
-
- if ($policy eq 'ACCEPT') {
+sub ruleset_chain_add_conn_filters {
+ my ($ruleset, $chain, $accept) = @_;
- ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
- { ACCEPT => $accept_action});
-
- } elsif ($policy eq 'DROP') {
-
- ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
+ ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID", "-j DROP");
+ ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED", "-j $accept");
+}
- ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
+sub ruleset_chain_add_input_filters {
+ my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
- ruleset_addrule($ruleset, $chain, "-j DROP");
- } elsif ($policy eq 'REJECT') {
- ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
+ if ($cluster_conf->{ipset}->{blacklist}){
+ if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
+ ruleset_create_chain($ruleset, "PVEFW-blacklist");
+ ruleset_addrule($ruleset, "PVEFW-blacklist", "", "-j DROP", $loglevel, "DROP: ");
+ }
+ my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
+ ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src", "-j PVEFW-blacklist");
+ }
- ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
+ if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
+ if ($ipversion == 4) {
+ ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW", "-j PVEFW-smurfs");
+ }
+ }
- ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
- } else {
- # should not happen
- die "internal error: unknown policy '$policy'";
+ if ($options->{tcpflags}) {
+ ruleset_addrule($ruleset, $chain, "-p tcp", "-j PVEFW-tcpflags");
}
}
sub ruleset_create_vm_chain {
- my ($ruleset, $chain, $options, $host_options, $macaddr, $direction) = @_;
+ my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
ruleset_create_chain($ruleset, $chain);
my $accept = generate_nfqueue($options);
- if (!(defined($host_options->{nosmurfs}) && $host_options->{nosmurfs} == 0)) {
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
+ if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
+ if ($ipversion == 4) {
+ if ($direction eq 'OUT') {
+ ruleset_generate_rule($ruleset, $chain, $ipversion,
+ { action => 'PVEFW-SET-ACCEPT-MARK',
+ proto => 'udp', sport => 68, dport => 67 });
+ } else {
+ ruleset_generate_rule($ruleset, $chain, $ipversion,
+ { action => 'ACCEPT',
+ proto => 'udp', sport => 67, dport => 68 });
+ }
+ } elsif ($ipversion == 6) {
+ if ($direction eq 'OUT') {
+ ruleset_generate_rule($ruleset, $chain, $ipversion,
+ { action => 'PVEFW-SET-ACCEPT-MARK',
+ proto => 'udp', sport => 546, dport => 547 });
+ } else {
+ ruleset_generate_rule($ruleset, $chain, $ipversion,
+ { action => 'ACCEPT',
+ proto => 'udp', sport => 547, dport => 546 });
+ }
+ }
+
}
- if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
- if ($direction eq 'OUT') {
- ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
- proto => 'udp', sport => 68, dport => 67 });
- } else {
- ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
- proto => 'udp', sport => 67, dport => 68 });
+ if ($direction eq 'OUT') {
+ if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
+ ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr", "-j DROP");
+ }
+ if ($ipversion == 6 && !$options->{radv}) {
+ ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", "-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 $FWACCEPTMARK_OFF"); # clear mark
}
- if ($host_options->{tcpflags}) {
- ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
+ my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j $accept";
+ ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
+}
+
+sub ruleset_add_group_rule {
+ 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, $ipversion);
}
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
- if ($direction eq 'OUT') {
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
+ 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}) {
+ ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in}", "-j $group_chain");
} else {
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
+ ruleset_addrule($ruleset, $chain, "", "-j $group_chain");
}
- if ($direction eq 'OUT') {
- if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
- ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
- }
- ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
- }
+ ruleset_addrule($ruleset, $chain, "-m mark --mark $FWACCEPTMARK_ON", "-j $action");
}
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);
+ my $in_accept = generate_nfqueue($options);
+
foreach my $rule (@$rules) {
next if $rule->{iface} && $rule->{iface} ne $netid;
- next if !$rule->{enable};
- if ($rule->{type} eq 'group') {
- my $group_chain = "GROUP-$rule->{action}-$direction";
- if(!ruleset_chain_exist($ruleset, $group_chain)){
- generate_group_rules($ruleset, $cluster_conf, $rule->{action});
- }
- ruleset_addrule($ruleset, $chain, "-j $group_chain");
- if ($direction eq 'OUT'){
- ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j RETURN");
- }else{
- my $accept = generate_nfqueue($options);
- ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $accept");
- }
+ 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, $ipversion);
} else {
next if $rule->{type} ne $lc_direction;
- if ($direction eq 'OUT') {
- ruleset_generate_rule($ruleset, $chain, $rule,
- { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
- } else {
- my $accept = generate_nfqueue($options);
- ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" }, undef, $cluster_conf);
- }
+ eval {
+ if ($direction eq 'OUT') {
+ rule_substitude_action($rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef,
+ undef, $cluster_conf, $vmfw_conf);
+ } else {
+ rule_substitude_action($rule, { ACCEPT => $in_accept , REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef,
+ undef, $cluster_conf, $vmfw_conf);
+ }
+ };
+ warn $@ if $@;
}
}
}
sub generate_nfqueue {
my ($options) = @_;
- my $action = "";
- if($options->{ips}){
- $action = "NFQUEUE";
- if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
- if(defined($3) && defined($1)) {
+ if ($options->{ips}) {
+ my $action = "NFQUEUE";
+ if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
+ if (defined($3) && defined($1)) {
$action .= " --queue-balance $1:$3";
- }elsif (defined($1)) {
+ } elsif (defined($1)) {
$action .= " --queue-num $1";
}
}
$action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
- }else{
- $action = "ACCEPT";
+ return $action;
+ } else {
+ return "ACCEPT";
}
-
- return $action;
}
sub ruleset_generate_vm_ipsrules {
- my ($ruleset, $options, $direction, $iface, $bridge) = @_;
+ my ($ruleset, $options, $direction, $iface) = @_;
if ($options->{ips} && $direction eq 'IN') {
my $nfqueue = generate_nfqueue($options);
- if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
+ if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
ruleset_create_chain($ruleset, "PVEFW-IPS");
}
- if (!ruleset_chain_exist($ruleset, "$bridge-IPS")) {
- ruleset_create_chain($ruleset, "$bridge-IPS");
- ruleset_insertrule($ruleset, "PVEFW-IPS", "-o $bridge -m physdev --physdev-is-out -j $bridge-IPS");
- }
-
- ruleset_addrule($ruleset, "$bridge-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
- }
-}
-
-sub generate_venet_rules_direction {
- my ($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
-
- parse_address_list($ip); # make sure we have a valid $ip list
-
- my $lc_direction = lc($direction);
-
- my $rules = $vmfw_conf->{rules};
-
- my $options = $vmfw_conf->{options};
- my $hostfw_options = $vmfw_conf->{options};
- my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
-
- my $chain = "venet0-$vmid-$direction";
-
- ruleset_create_vm_chain($ruleset, $chain, $options, $hostfw_options, undef, $direction);
-
- ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
-
- # 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, $chain, $vmid, $policy, $loglevel, $accept_action);
-
- # plug into FORWARD, INPUT and OUTPUT chain
- if ($direction eq 'OUT') {
- ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
- action => $chain,
- source => $ip,
- iface_in => 'venet0'});
-
- ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
- action => $chain,
- source => $ip,
- iface_in => 'venet0'});
- } else {
- ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
- action => $chain,
- dest => $ip,
- iface_out => 'venet0'});
-
- ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
- action => $chain,
- dest => $ip,
- iface_out => 'venet0'});
+ ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged", "-j $nfqueue");
}
}
sub generate_tap_rules_direction {
- my ($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
+ my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
my $lc_direction = lc($direction);
my $rules = $vmfw_conf->{rules};
my $options = $vmfw_conf->{options};
- my $hostfw_options = $hostfw_conf->{options};
my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
my $tapchain = "$iface-$direction";
- ruleset_create_vm_chain($ruleset, $tapchain, $options, $hostfw_options, $macaddr, $direction);
+ my $ipfilter_name = compute_ipfilter_ipset_name($netid);
+ my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
+ if $options->{ipfilter} || $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, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
- ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
+ 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, $ipversion, $vmid, $policy, $loglevel, $accept_action);
+ } else {
+ my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
+ ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
+ }
# plug the tap chain to bridge chain
if ($direction eq 'IN') {
- ruleset_insertrule($ruleset, "$bridge-IN",
- "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
+ ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
+ "-m physdev --physdev-is-bridged --physdev-out $iface", "-j $tapchain");
} else {
- ruleset_insertrule($ruleset, "$bridge-OUT",
- "-m physdev --physdev-in $iface -j $tapchain");
+ ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
+ "-m physdev --physdev-is-bridged --physdev-in $iface", "-j $tapchain");
}
}
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};
my $loglevel = get_option_log_level($options, "log_level_in");
- if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
- }
-
- if ($options->{tcpflags}) {
- ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
- }
+ ruleset_addrule($ruleset, $chain, "-i lo", "-j ACCEPT");
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
- ruleset_addrule($ruleset, $chain, "-i lo -j 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
+ ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
+ ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
+ ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $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->{type} ne 'in';
- ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
+ next if !$rule->{enable} || $rule->{errors};
+ next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
+
+ $rule->{iface_in} = $rule->{iface} if $rule->{iface};
+
+ eval {
+ if ($rule->{type} eq 'group') {
+ ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
+ } elsif ($rule->{type} eq 'in') {
+ rule_substitude_action($rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef,
+ 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", $ipversion);
+ 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 = $cluster_conf->{aliases}->{local_network}->{cidr};
+ my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
+
+ # corosync
+ if ($localnet && ($ipversion == $localnet_ver)) {
+ my $corosync_rule = "-p udp --dport 5404:5405";
+ ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule", "-j $accept_action");
+ ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
}
# 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);
+ ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
# host outbound firewall
$chain = "PVEFW-HOST-OUT";
$loglevel = get_option_log_level($options, "log_level_out");
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
- ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
- ruleset_addrule($ruleset, $chain, "-o lo -j 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
+ ruleset_addrule($ruleset, $chain, "-o lo", "-j ACCEPT");
+
+ ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
# we use RETURN because we may want to check other thigs later
$accept_action = 'RETURN';
+ ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j $accept_action");
+
+ 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->{type} ne 'out';
- ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
+ next if !$rule->{enable} || $rule->{errors};
+ next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
+
+ $rule->{iface_out} = $rule->{iface} if $rule->{iface};
+ eval {
+ if ($rule->{type} eq 'group') {
+ ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
+ } elsif ($rule->{type} eq 'out') {
+ rule_substitude_action($rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef,
+ undef, $cluster_conf, $hostfw_conf);
+ }
+ };
+ warn $@ if $@;
+ delete $rule->{iface_out};
+ }
+
+ # allow standard traffic on cluster network
+ if ($localnet && ($ipversion == $localnet_ver)) {
+ 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";
+ ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule", "-j $accept_action");
+ ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
}
# implement output policy
$policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
- ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
+ ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
- ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
- ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
+ ruleset_addrule($ruleset, "PVEFW-OUTPUT", "", "-j PVEFW-HOST-OUT");
+ ruleset_addrule($ruleset, "PVEFW-INPUT", "", "-j PVEFW-HOST-IN");
}
sub generate_group_rules {
- my ($ruleset, $cluster_conf, $group) = @_;
- die "no such security group '$group'\n" if !$cluster_conf->{groups}->{$group};
+ my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
my $rules = $cluster_conf->{groups}->{$group};
+ if (!$rules) {
+ warn "no such security group '$group'\n";
+ $rules = []; # create empty chain
+ }
+
my $chain = "GROUP-${group}-IN";
ruleset_create_chain($ruleset, $chain);
- ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
+ ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
foreach my $rule (@$rules) {
next if $rule->{type} ne 'in';
- ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
+ next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
+ rule_substitude_action($rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef, undef, $cluster_conf);
}
$chain = "GROUP-${group}-OUT";
ruleset_create_chain($ruleset, $chain);
- ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
+ ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
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,
- { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
+ rule_substitude_action($rule, { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" });
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule, undef,
+ undef, $cluster_conf);
}
}
$valid_netdev_names->{"net$i"} = 1;
}
+sub get_mark_values {
+ my ($value, $mask) = @_;
+ $value = hex($value) if $value =~ /^0x/;
+ $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
+ $mask = 0xffffffff if !defined($mask);
+ return ($value, $mask);
+}
+
sub parse_fw_rule {
- my ($line, $need_iface, $allow_groups) = @_;
+ my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
- my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
+ my $orig_line = $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;
- my @data = split(/\s+/, $line);
- my $expected_elements = $need_iface ? 8 : 7;
+ $line =~ s/^(\S+)\s+(\S+)\s*// ||
+ die "unable to parse rule: $line\n";
- die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
+ $rule->{type} = lc($1);
+ $rule->{action} = $2;
- if ($need_iface) {
- ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
- } else {
- ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
+ if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
+ if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
+ $rule->{macro} = $1;
+ $rule->{action} = $2;
+ }
}
- die "incomplete rule\n" if ! ($type && $action);
+ while (length($line)) {
+ if ($line =~ s/^-i (\S+)\s*//) {
+ $rule->{iface} = $1;
+ next;
+ }
- my $macro;
+ last if $rule->{type} eq 'group';
- $type = lc($type);
+ if ($line =~ s/^-p (\S+)\s*//) {
+ $rule->{proto} = $1;
+ next;
+ }
- 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";
+ if ($line =~ s/^-dport (\S+)\s*//) {
+ $rule->{dport} = $1;
+ next;
}
- } elsif ($type eq 'group') {
- die "wrong number of rule elements\n" if scalar(@data) != 3;
- die "groups disabled\n" if !$allow_groups;
- die "invalid characters in group name\n" if $action !~ m/^${security_group_pattern}$/;
- } else {
- die "unknown rule type '$type'\n";
- }
+ if ($line =~ s/^-sport (\S+)\s*//) {
+ $rule->{sport} = $1;
+ next;
+ }
+ if ($line =~ s/^-source (\S+)\s*//) {
+ $rule->{source} = $1;
+ next;
+ }
+ if ($line =~ s/^-dest (\S+)\s*//) {
+ $rule->{dest} = $1;
+ next;
+ }
- if ($need_iface) {
- $iface = undef if $iface && $iface eq '-';
+ last;
}
- $proto = undef if $proto && $proto eq '-';
- pve_fw_verify_protocol_spec($proto) if $proto;
-
- $source = undef if $source && $source eq '-';
- $dest = undef if $dest && $dest eq '-';
-
- $dport = undef if $dport && $dport eq '-';
- $sport = undef if $sport && $sport eq '-';
+ die "unable to parse rule parameters: $line\n" if length($line);
- parse_port_name_number_or_range($dport) if defined($dport);
- parse_port_name_number_or_range($sport) if defined($sport);
-
- parse_address_list($source) if $source;
- parse_address_list($dest) if $dest;
+ $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
+ if ($rule->{errors}) {
+ # The verbose flag really means we're running from the CLI and want
+ # output on the console - in the other case we really want such errors
+ # to go into the syslog instead.
+ my $log = $verbose ? sub { warn @_ } : sub { syslog(err => @_) };
+ $log->("$prefix - errors in rule parameters: $orig_line\n");
+ foreach my $p (keys %{$rule->{errors}}) {
+ $log->(" $p: $rule->{errors}->{$p}\n");
+ }
+ }
- return {
- type => $type,
- enable => $enable,
- comment => $comment,
- action => $action,
- macro => $macro,
- iface => $iface,
- source => $source,
- dest => $dest,
- proto => $proto,
- dport => $dport,
- sport => $sport,
- };
+ return $rule;
}
sub parse_vmfw_option {
my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
- if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
+ if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
$opt = lc($1);
$value = int($2);
} elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
$opt = lc($1);
$value = $2;
} else {
- chomp $line;
die "can't parse option '$line'\n"
}
my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
- if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
+ if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
$opt = lc($1);
$value = int($2);
} elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
$opt = lc($1);
$value = int($2);
} else {
- chomp $line;
die "can't parse option '$line'\n"
}
my ($opt, $value);
- if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
+ if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
$opt = lc($1);
$value = int($2);
+ if (($value > 1) && ((time() - $value) > 60)) {
+ $value = 0
+ }
} elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
$opt = lc($1);
$value = uc($3);
} else {
- chomp $line;
die "can't parse option '$line'\n"
}
return ($opt, $value);
}
-sub parse_vm_fw_rules {
- my ($filename, $fh) = @_;
+sub resolve_alias {
+ my ($clusterfw_conf, $fw_conf, $cidr) = @_;
- 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;
- }
+ my $alias = lc($cidr);
+ my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
+ $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
- next if !$res->{$section}; # skip undefined section
+ die "no such alias '$cidr'\n" if !$e;;
- if ($section eq 'options') {
- eval {
- my ($opt, $value) = parse_vmfw_option($line);
- $res->{options}->{$opt} = $value;
- };
- warn "$prefix: $@" if $@;
- next;
- }
+ return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
+}
- 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 => {},
- 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/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
+ if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
+ $section = 'aliases';
+ next;
+ }
+
+ 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)
+ $res->{ipset_comments}->{$group} = decode('utf8', $comment)
if $comment;
next;
}
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_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;
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;
$line =~ m/^(\!)?\s*(\S+)\s*$/;
my $nomatch = $1;
my $cidr = $2;
+ my $errors;
- $cidr =~ s|/32$||;
-
- eval { pve_verify_ipv4_or_cidr($cidr); };
+ if ($nomatch && !$feature_ipset_nomatch) {
+ $errors->{nomatch} = "nomatch not supported by kernel";
+ }
+
+ 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 = $@) {
- warn "$prefix: $cidr - $err";
- next;
+ chomp $err;
+ $errors->{cidr} = $err;
+ }
+
+ if ($cidr =~ m!/0+$!) {
+ $errors->{cidr} = "a zero prefix is not allowed in ipset entries\n";
+ }
+
+ 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";
+ }
}
- my $entry = { cidr => $cidr };
- $entry->{nomatch} = 1 if $nomatch;
- $entry->{comment} = $comment if $comment;
-
- push @{$res->{$section}->{$group}}, $entry;
- }
- }
+ 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) = @_;
- return $res;
+ 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 {
sub read_local_vm_config {
- my $openvz = {};
my $qemu = {};
+ my $lxc = {};
- my $vmdata = { openvz => $openvz, qemu => $qemu };
+ my $vmdata = { qemu => $qemu, lxc => $lxc };
my $vmlist = PVE::Cluster::get_vmlist();
return $vmdata if !$vmlist || !$vmlist->{ids};
my $d = $ids->{$vmid};
next if !$d->{node} || $d->{node} ne $nodename;
next if !$d->{type};
- if ($d->{type} eq 'openvz') {
- if ($have_pve_manager) {
- my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
- if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
- $openvz->{$vmid} = $conf;
- }
- }
- } elsif ($d->{type} eq 'qemu') {
+ if ($d->{type} eq 'qemu') {
if ($have_qemu_server) {
- my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
+ my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
$qemu->{$vmid} = $conf;
}
}
- }
+ } elsif ($d->{type} eq 'lxc') {
+ if ($have_lxc) {
+ my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
+ if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
+ $lxc->{$vmid} = $conf;
+ }
+ }
+ }
}
return $vmdata;
};
sub load_vmfw_conf {
- my ($vmid) = @_;
+ my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
my $vmfw_conf = {};
- my $filename = "/etc/pve/firewall/$vmid.fw";
+ $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;
}
my $format_rules = sub {
- my ($rules, $need_iface) = @_;
+ my ($rules, $allow_iface) = @_;
my $raw = '';
} else {
$raw .= " " . $rule->{action};
}
- $raw .= " " . ($rule->{iface} || '-') if $need_iface;
+ if ($allow_iface && $rule->{iface}) {
+ $raw .= " -i $rule->{iface}";
+ }
if ($rule->{type} ne 'group') {
- $raw .= " " . ($rule->{source} || '-');
- $raw .= " " . ($rule->{dest} || '-');
- $raw .= " " . ($rule->{proto} || '-');
- $raw .= " " . ($rule->{dport} || '-');
- $raw .= " " . ($rule->{sport} || '-');
+ $raw .= " -source $rule->{source}" if $rule->{source};
+ $raw .= " -dest $rule->{dest}" if $rule->{dest};
+ $raw .= " -p $rule->{proto}" if $rule->{proto};
+ $raw .= " -dport $rule->{dport}" if $rule->{dport};
+ $raw .= " -sport $rule->{sport}" if $rule->{sport};
}
$raw .= " # " . encode('utf8', $rule->{comment})
return $raw;
};
-my $format_ipset = sub {
- my ($options) = @_;
+my $format_aliases = sub {
+ my ($aliases) = @_;
my $raw = '';
- my $nethash = {};
- foreach my $entry (@$options) {
- $nethash->{$entry->{cidr}} = $entry;
+ $raw .= "[ALIASES]\n\n";
+ foreach my $k (keys %$aliases) {
+ my $e = $aliases->{$k};
+ $raw .= "$e->{name} $e->{cidr}";
+ $raw .= " # " . encode('utf8', $e->{comment})
+ if $e->{comment} && $e->{comment} !~ m/^\s*$/;
+ $raw .= "\n";
}
+ $raw .= "\n";
+
+ return $raw;
+};
+
+my $format_ipsets = sub {
+ my ($fw_conf) = @_;
+
+ my $raw = '';
+
+ 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};
+
+ 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";
+ }
- 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;
};
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 $rules = $vmfw_conf->{rules};
- if (scalar(@$rules)) {
+ 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 ($rules && scalar(@$rules)) {
$raw .= "[RULES]\n\n";
$raw .= &$format_rules($rules, 1);
$raw .= "\n";
}
- my $filename = "/etc/pve/firewall/$vmid.fw";
- PVE::Tools::file_set_contents($filename, $raw);
+ my $filename = "$pvefw_conf_dir/$vmid.fw";
+ if ($raw) {
+ mkdir $pvefw_conf_dir;
+ PVE::Tools::file_set_contents($filename, $raw);
+ } else {
+ unlink $filename;
+ }
+}
+
+sub remove_vmfw_conf {
+ my ($vmid) = @_;
+
+ my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
+
+ unlink $vmfw_conffile;
+}
+
+sub clone_vmfw_conf {
+ my ($vmid, $newid) = @_;
+
+ my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
+ my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
+
+ if (-f $clonevm_conffile) {
+ unlink $clonevm_conffile;
+ }
+ if (-f $sourcevm_conffile) {
+ my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
+ PVE::Tools::file_set_contents($clonevm_conffile, $data);
+ }
}
sub read_vm_firewall_configs {
- my ($vmdata) = @_;
+ 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);
+ 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->{lxc}}) {
+ 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;
+ }
return $vmfw_configs;
}
}
sub generate_std_chains {
- my ($ruleset, $options) = @_;
+ my ($ruleset, $options, $ipversion) = @_;
- my $loglevel = get_option_log_level($options, 'smurf_log_level');
+ my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
- # same as shorewall smurflog.
+ my $loglevel = get_option_log_level($options, 'smurf_log_level');
my $chain = 'PVEFW-smurflog';
- $pve_std_chains->{$chain} = [];
-
- push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
- push @{$pve_std_chains->{$chain}}, "-j DROP";
+ if ( $std_chains->{$chain} ) {
+ foreach my $r (@{$std_chains->{$chain}}) {
+ $r->{log} = $loglevel;
+ }
+ }
# same as shorewall logflags action.
$loglevel = get_option_log_level($options, 'tcp_flags_log_level');
$chain = 'PVEFW-logflags';
- $pve_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";
+ if ( $std_chains->{$chain} ) {
+ foreach my $r (@{$std_chains->{$chain}}) {
+ $r->{log} = $loglevel;
+ }
+ }
- 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);
+ ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
} else {
- ruleset_addrule($ruleset, $chain, $rule);
+ die "rule $rule as string - should not happen";
}
}
}
}
sub generate_ipset_chains {
- my ($ipset_ruleset, $fw_conf) = @_;
+ my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
- foreach my $ipset (keys %{$fw_conf->{ipset}}) {
- generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
- }
-}
+ foreach my $ipset (keys %{$ipsets}) {
-sub generate_ipset {
- my ($ipset_ruleset, $name, $options) = @_;
+ my $options = $ipsets->{$ipset};
- my $hashsize = scalar(@$options);
- if ($hashsize <= 64) {
- $hashsize = 64;
- } else {
- $hashsize = round_powerof2($hashsize);
- }
+ if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
+ if (my $ips = $device_ips->{$1}) {
+ $options = [@$options, @$ips];
+ }
+ }
+
+ # remove duplicates
+ my $nethash = {};
+ foreach my $entry (@$options) {
+ next if $entry->{errors}; # skip entries with errors
+ eval {
+ my ($cidr, $ver);
+ if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
+ ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
+ } else {
+ ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
+ }
+ #http://backreference.org/2013/03/01/ipv6-address-normalization/
+ if ($ver == 6) {
+ # ip_compress_address takes an address only, no CIDR
+ my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
+ $cidr = lc(Net::IP::ip_compress_address($addr, 6));
+ $cidr .= $prefix_len if defined($prefix_len);
+ $cidr =~ s|/128$||;
+ } else {
+ $cidr =~ s|/32$||;
+ }
- push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
+ $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
+ };
+ warn $@ if $@;
+ }
- # remove duplicates
- my $nethash = {};
- foreach my $entry (@$options) {
- $nethash->{$entry->{cidr}} = $entry;
- }
+ foreach my $ipversion (4, 6) {
+ my $data = $nethash->{$ipversion};
- foreach my $cidr (sort keys %$nethash) {
- my $entry = $nethash->{$cidr};
+ my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
- my $cmd = "add $name $cidr";
- if ($entry->{nomatch}) {
- if ($feature_ipset_nomatch) {
- push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
+ my $hashsize = scalar(@$options);
+ if ($hashsize <= 64) {
+ $hashsize = 64;
} else {
- warn "ignore !$cidr - nomatch not supported by kernel\n";
+ $hashsize = round_powerof2($hashsize);
+ }
+
+ my $family = $ipversion == "6" ? "inet6" : "inet";
+
+ $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
+
+ foreach my $cidr (sort keys %$data) {
+ my $entry = $data->{$cidr};
+
+ my $cmd = "add $name $cidr";
+ if ($entry->{nomatch}) {
+ if ($feature_ipset_nomatch) {
+ push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
+ } else {
+ warn "ignore !$cidr - nomatch not supported by kernel\n";
+ }
+ } else {
+ push @{$ipset_ruleset->{$name}}, $cmd;
+ }
}
- } else {
- push @{$ipset_ruleset->{$name}}, $cmd;
}
}
}
return ++$int;
}
-sub save_pvefw_status {
- my ($status) = @_;
-
- die "unknown status '$status' - internal error"
- if $status !~ m/^(stopped|active)$/;
-
- mkdir dirname($pve_fw_status_filename);
- PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
-}
-
-sub read_pvefw_status {
-
- my $status = 'unknown';
-
- return 'stopped' if ! -f $pve_fw_status_filename;
-
- eval {
- $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
- };
- warn $@ if $@;
-
- return $status;
-}
-
-# fixme: move to pve-common PVE::ProcFSTools
-sub read_proc_net_route {
- my $filename = "/proc/net/route";
-
- my $res = {};
-
- my $fh = IO::File->new ($filename, "r");
- return $res if !$fh;
-
- my $int_to_quad = sub {
- return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
- };
-
- while (defined(my $line = <$fh>)) {
- next if $line =~/^Iface\s+Destination/; # skip head
- my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
- push @{$res->{$iface}}, {
- dest => &$int_to_quad(hex($dest)),
- gateway => &$int_to_quad(hex($gateway)),
- mask => &$int_to_quad(hex($mask)),
- metric => $metric,
- mtu => $mtu,
- };
- }
-
- return $res;
-}
-
sub load_clusterfw_conf {
+ my ($filename, $verbose) = @_;
+
+ $filename = $clusterfw_conf_filename if !defined($filename);
my $cluster_conf = {};
- if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
- $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
+ if (my $fh = IO::File->new($filename, O_RDONLY)) {
+ $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
}
return $cluster_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);
- 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";
- }
+ my $aliases = $cluster_conf->{aliases};
+ $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";
+ }
}
- PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
+ if ($raw) {
+ mkdir $pvefw_conf_dir;
+ PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
+ } else {
+ unlink $clusterfw_conf_filename;
+ }
}
sub load_hostfw_conf {
+ my ($cluster_conf, $filename, $verbose) = @_;
+
+ $filename = $hostfw_conf_filename if !defined($filename);
my $hostfw_conf = {};
- if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
- $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
+ if (my $fh = IO::File->new($filename, O_RDONLY)) {
+ $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
}
return $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";
}
- PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
+ if ($raw) {
+ PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
+ } else {
+ unlink $hostfw_conf_filename;
+ }
}
sub compile {
- my ($cluster_conf, $hostfw_conf) = @_;
+ my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
- $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
- $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
+ my $vmfw_configs;
- my $vmdata = read_local_vm_config();
- my $vmfw_configs = read_vm_firewall_configs($vmdata);
+ # fixme: once we read standard chains from config this needs to be put in test/standard cases below
+ $pve_std_chains = dclone($pve_std_chains_conf);
- my $routing_table = read_proc_net_route();
+ if ($vmdata) { # test mode
+ my $testdir = $vmdata->{testdir} || die "no test directory specified";
+ my $filename = "$testdir/cluster.fw";
+ $cluster_conf = load_clusterfw_conf($filename, $verbose);
- my $ipset_ruleset = {};
- generate_ipset_chains($ipset_ruleset, $cluster_conf);
+ $filename = "$testdir/host.fw";
+ $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
+
+ $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
+ } else { # normal operation
+ $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
+
+ $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
+
+ $vmdata = read_local_vm_config();
+ $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
+ }
+
+ return ({},{},{}) if !$cluster_conf->{options}->{enable};
+
+ my $localnet;
+ if ($cluster_conf->{aliases}->{local_network}) {
+ $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
+ } else {
+ my $localnet_ver;
+ ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
+
+ $cluster_conf->{aliases}->{local_network} = {
+ name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
+ }
+
+ push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
+
+ my $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);
+ my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
+
+ return ($ruleset, $ipset_ruleset, $rulesetv6);
+}
+
+sub compile_iptables_filter {
+ my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
my $ruleset = {};
my $hostfw_options = $hostfw_conf->{options} || {};
- generate_std_chains($ruleset, $hostfw_options);
+ # fixme: what log level should we use here?
+ my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
- my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
+ ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
- enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
+ ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
+ ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
- # 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);
+ ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+", "-j PVEFW-FWBR-IN");
- foreach my $netid (keys %$conf) {
- next if $netid !~ m/^net(\d+)$/;
- my $net = PVE::QemuServer::parse_net($conf->{$netid});
- next if !$net;
- my $iface = "tap${vmid}i$1";
+ ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
+ ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+", "-j PVEFW-FWBR-OUT");
- my $bridge = $net->{bridge};
- next if !$bridge; # fixme: ?
+ generate_std_chains($ruleset, $hostfw_options, $ipversion);
- $bridge .= "v$net->{tag}" if $net->{tag};
+ my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
- generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
+ if ($hostfw_enable) {
+ eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
+ warn $@ if $@; # just to be sure - should not happen
+ }
- my $macaddr = $net->{macaddr};
- generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
- $vmfw_conf, $vmid, $bridge, 'IN');
- generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
- $vmfw_conf, $vmid, $bridge, 'OUT');
- }
+ # generate firewall rules for QEMU VMs
+ foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
+ eval {
+ my $conf = $vmdata->{qemu}->{$vmid};
+ my $vmfw_conf = $vmfw_configs->{$vmid};
+ return if !$vmfw_conf;
+
+ foreach my $netid (sort 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 LXC containers
+ foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
+ eval {
+ my $conf = $vmdata->{lxc}->{$vmid};
+ my $vmfw_conf = $vmfw_configs->{$vmid};
+ return if !$vmfw_conf;
+
+ if ($vmfw_conf->{options}->{enable}) {
+ foreach my $netid (sort keys %$conf) {
+ next if $netid !~ m/^net(\d+)$/;
+ my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
+ next if !$net->{firewall};
+ my $iface = "veth${vmid}i$1";
+ my $macaddr = $net->{hwaddr};
+ 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};
+ if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
+ ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED", "-j PVEFW-IPS");
+ }
- my $vmfw_conf = $vmfw_configs->{$vmid};
- next if !$vmfw_conf;
- next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
+ return $ruleset;
+}
- if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
- my $ip = $conf->{ip_address}->{value};
- generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'IN');
- generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'OUT');
- }
+sub mac_to_linklocal {
+ my ($macaddr) = @_;
+ my @parts = split(/:/, $macaddr);
+ # The standard link local address uses the fe80::/64 prefix with the
+ # modified EUI-64 identifier derived from the MAC address by flipping the
+ # universal/local bit and inserting FF:FE in the middle.
+ # See RFC 4291.
+ $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
+ my @meui64 = (@parts[0,1,2], 'ff', 'fe', @parts[3,4,5]);
+ return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
+}
- 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};
- if (!$bridge) {
- warn "no bridge device for CT $vmid iface '$netid'\n";
- next; # fixme?
- }
+sub compile_ipsets {
+ my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
- generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
+ my $localnet;
+ if ($cluster_conf->{aliases}->{local_network}) {
+ $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
+ } else {
+ my $localnet_ver;
+ ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
- my $macaddr = $d->{mac};
- my $iface = $d->{host_ifname};
- generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
- $vmfw_conf, $vmid, $bridge, 'IN');
- generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
- $vmfw_conf, $vmid, $bridge, 'OUT');
- }
- }
+ $cluster_conf->{aliases}->{local_network} = {
+ name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
}
- if($hostfw_options->{optimize}){
+ push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
- my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
- ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
- ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
- }
- # fixme: what log level should we use here?
- my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
+ my $ipset_ruleset = {};
+
+ # generate ipsets for QEMU VMs
+ foreach my $vmid (keys %{$vmdata->{qemu}}) {
+ eval {
+ my $conf = $vmdata->{qemu}->{$vmid};
+ my $vmfw_conf = $vmfw_configs->{$vmid};
+ return if !$vmfw_conf;
+
+ # When the 'ipfilter' option is enabled every device for which there
+ # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
+ # ipset.
+ # The reason is that ipfilter ipsets are always filled with standard
+ # IPv6 link-local filters.
+ my $ipsets = $vmfw_conf->{ipset};
+ my $implicit_sets = {};
+
+ my $device_ips = {};
+ foreach my $netid (keys %$conf) {
+ next if $netid !~ m/^net(\d+)$/;
+ my $net = PVE::QemuServer::parse_net($conf->{$netid});
+ next if !$net->{firewall};
+
+ if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
+ $implicit_sets->{"ipfilter-$netid"} = [];
+ }
+
+ my $macaddr = $net->{macaddr};
+ my $linklocal = mac_to_linklocal($macaddr);
+ $device_ips->{$netid} = [
+ { cidr => $linklocal },
+ { cidr => 'fe80::/10', nomatch => 1 }
+ ];
+ }
+
+ generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
+ generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
+ };
+ warn $@ if $@; # just to be sure - should not happen
+ }
+
+ # generate firewall rules for LXC containers
+ foreach my $vmid (keys %{$vmdata->{lxc}}) {
+ eval {
+ my $conf = $vmdata->{lxc}->{$vmid};
+ my $vmfw_conf = $vmfw_configs->{$vmid};
+ return if !$vmfw_conf;
+
+ # When the 'ipfilter' option is enabled every device for which there
+ # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
+ # ipset.
+ # The reason is that ipfilter ipsets are always filled with standard
+ # IPv6 link-local filters, as well as the IP addresses configured
+ # for the container.
+ my $ipsets = $vmfw_conf->{ipset};
+ my $implicit_sets = {};
+
+ my $device_ips = {};
+ foreach my $netid (keys %$conf) {
+ next if $netid !~ m/^net(\d+)$/;
+ my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
+ next if !$net->{firewall};
+
+ if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
+ $implicit_sets->{"ipfilter-$netid"} = [];
+ }
- # fixme: should we really block inter-bridge traffic?
+ my $macaddr = $net->{hwaddr};
+ my $linklocal = mac_to_linklocal($macaddr);
+ my $set = $device_ips->{$netid} = [
+ { cidr => $linklocal },
+ { cidr => 'fe80::/10', nomatch => 1 }
+ ];
+ if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
+ push @$set, { cidr => $1 };
+ }
+ if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
+ push @$set, { cidr => $1 };
+ }
+ }
- # always allow traffic from containers?
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
+ generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
+ generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
+ };
+ warn $@ if $@; # just to be sure - should not happen
+ }
- # disable interbridge routing
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
- ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
- ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
- ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
+ generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
- return ($ruleset, $ipset_ruleset);
+ return $ipset_ruleset;
}
sub get_ruleset_status {
}
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
}
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";
}
}
my $active_chains = ipset_get_chains();
my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
- # remove stale _swap chains
+ # remove stale _swap chains
foreach my $chain (keys %$active_chains) {
if ($chain =~ m/^PVEFW-\S+_swap$/) {
$cmdlist .= "destroy $chain\n";
}
}
- foreach my $chain (sort keys %$ruleset) {
+ foreach my $chain (keys %$ruleset) {
my $stat = $statushash->{$chain};
die "internal error" if !$stat;
$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";
$cmdlist .= "flush $chain_swap\n";
$cmdlist .= "destroy $chain_swap\n";
}
-
}
+ # the remove unused chains
foreach my $chain (keys %$statushash) {
next if $statushash->{$chain}->{action} ne 'delete';
}
sub apply_ruleset {
- my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
+ my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
enable_bridge_firewall();
- update_nf_conntrack_max($hostfw_conf);
-
- update_nf_conntrack_tcp_timeout_established($hostfw_conf);
-
my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
- get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
+ get_ipset_cmdlist($ipset_ruleset, $verbose);
my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
+ my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
if ($verbose) {
if ($ipset_changes) {
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
}
}
+ 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);
+
+ update_nf_conntrack_tcp_timeout_established($hostfw_conf);
+
}
sub update_nf_conntrack_max {
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)) {
}
$cmdlist .= "COMMIT\n";
- iptables_restore_cmdlist($cmdlist);
+ if($iptablescmd eq "ip6tables") {
+ ip6tables_restore_cmdlist($cmdlist);
+ } else {
+ iptables_restore_cmdlist($cmdlist);
+ }
}
-sub update {
- my ($start, $verbose) = @_;
+sub remove_pvefw_chains_ipset {
- my $code = sub {
+ my $ipset_chains = ipset_get_chains();
- my $cluster_conf = load_clusterfw_conf();
- my $cluster_options = $cluster_conf->{options};
+ my $cmdlist = "";
+
+ foreach my $chain (keys %$ipset_chains) {
+ $cmdlist .= "flush $chain\n";
+ $cmdlist .= "destroy $chain\n";
+ }
+
+ ipset_restore_cmdlist($cmdlist) if $cmdlist;
+}
+
+sub init {
+ my $cluster_conf = load_clusterfw_conf();
+ my $cluster_options = $cluster_conf->{options};
+ my $enable = $cluster_options->{enable};
+
+ return if !$enable;
- my $enable = $cluster_options->{enable};
+ # load required modules here
+}
- my $status = read_pvefw_status();
+sub update {
+ my $code = sub {
- die "Firewall is disabled - cannot start\n" if !$enable && $start;
+ my $cluster_conf = load_clusterfw_conf();
+ my $cluster_options = $cluster_conf->{options};
- 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 $hostfw_conf = load_hostfw_conf($cluster_conf);
- if ($start || $status eq 'active') {
+ my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
- save_pvefw_status('active') if ($status ne 'active');
-
- apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
- } else {
- print "Firewall not active (status = $status)\n" if $verbose;
- }
+ apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
};
run_locked($code);
}
-
1;