]> git.proxmox.com Git - pve-firewall.git/blobdiff - src/PVE/Firewall.pm
add aliases feature
[pve-firewall.git] / src / PVE / Firewall.pm
index 8ba1ba9bad89ab273e9b2b5da60f1f0d1ba4366a..7ef38fa514be9b0c35cf2ba3425845ef95472649 100644 (file)
@@ -2,13 +2,15 @@ package PVE::Firewall;
 
 use warnings;
 use strict;
+use POSIX;
 use Data::Dumper;
 use Digest::SHA;
 use PVE::INotify;
-use PVE::JSONSchema qw(get_standard_option);
+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;
+use PVE::Tools qw($IPV4RE);
 use File::Basename;
 use File::Path;
 use IO::File;
@@ -16,9 +18,10 @@ use Net::IP;
 use PVE::Tools qw(run_command lock_file);
 use Encode;
 
+my $hostfw_conf_filename = "/etc/pve/local/host.fw";
 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
 
-# dynamically include PVE::QemuServer and PVE::OpenVZ 
+# dynamically include PVE::QemuServer and PVE::OpenVZ
 # to avoid dependency problems
 my $have_qemu_server;
 eval {
@@ -32,6 +35,55 @@ eval {
     $have_pve_manager = 1;
 };
 
+PVE::JSONSchema::register_format('IPv4orCIDR', \&pve_verify_ipv4_or_cidr);
+sub pve_verify_ipv4_or_cidr {
+    my ($cidr, $noerr) = @_;
+
+    if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
+       return $cidr if Net::IP->new($cidr); 
+       return undef if $noerr;
+       die Net::IP::Error() . "\n";
+    }
+    return undef if $noerr;
+    die "value does not look like a valid IP address or CIDR network\n";
+}
+
+PVE::JSONSchema::register_standard_option('ipset-name', {
+    description => "IP set name.",
+    type => 'string',
+    pattern => '[A-Za-z][A-Za-z0-9\-\_]+',
+    minLength => 2,
+    maxLength => 20,                     
+});
+
+PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
+    description => "Log level.",
+    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,
+    minLength => 2,
+    maxLength => 20,                             
+});
+
+my $feature_ipset_nomatch = 0;
+eval  {
+    my (undef, undef, $release) = POSIX::uname();
+    if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
+       my ($major, $minor) = ($1, $2);
+       $feature_ipset_nomatch = 1 if ($major > 3) ||
+           ($major == 3 && $minor >= 7);
+    }
+
+};
+
 use Data::Dumper;
 
 my $nodename = PVE::INotify::nodename();
@@ -55,124 +107,134 @@ my $log_level_hash = {
 # imported/converted from: /usr/share/shorewall/macro.*
 my $pve_fw_macros = {
     'Amanda' => [
+       "Amanda Backup",
        { action => 'PARAM', proto => 'udp', dport => '10080' },
        { action => 'PARAM', proto => 'tcp', dport => '10080' },
     ],
     'Auth' => [
+       "Auth (identd) traffic",
        { action => 'PARAM', proto => 'tcp', dport => '113' },
     ],
     'BGP' => [
+       "Border Gateway Protocol traffic",
        { action => 'PARAM', proto => 'tcp', dport => '179' },
     ],
     'BitTorrent' => [
+       "BitTorrent traffic for BitTorrent 3.1 and earlier",
        { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
        { action => 'PARAM', proto => 'udp', dport => '6881' },
     ],
     'BitTorrent32' => [
+       "BitTorrent traffic for BitTorrent 3.2 and later",
        { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
        { action => 'PARAM', proto => 'udp', dport => '6881' },
     ],
     'CVS' => [
+       "Concurrent Versions System pserver traffic",
        { action => 'PARAM', proto => 'tcp', dport => '2401' },
     ],
     'Citrix' => [
+       "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
        { action => 'PARAM', proto => 'tcp', dport => '1494' },
        { action => 'PARAM', proto => 'udp', dport => '1604' },
        { action => 'PARAM', proto => 'tcp', dport => '2598' },
     ],
     'DAAP' => [
+       "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
        { action => 'PARAM', proto => 'tcp', dport => '3689' },
        { action => 'PARAM', proto => 'udp', dport => '3689' },
     ],
     'DCC' => [
+       "Distributed Checksum Clearinghouse spam filtering mechanism",
        { action => 'PARAM', proto => 'tcp', dport => '6277' },
     ],
     'DHCPfwd' => [
+       "Forwarded DHCP traffic (bidirectional)",
        { 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 => '53' },
        { action => 'PARAM', proto => 'tcp', dport => '53' },
     ],
     'Distcc' => [
+       "Distributed Compiler service",
        { action => 'PARAM', proto => 'tcp', dport => '3632' },
     ],
-    'Edonkey' => [
-       { action => 'PARAM', proto => 'tcp', dport => '4662' },
-       { action => 'PARAM', proto => 'udp', dport => '4665' },
-    ],
     'FTP' => [
+       "File Transfer Protocol",
        { action => 'PARAM', proto => 'tcp', dport => '21' },
     ],
     'Finger' => [
+       "Finger protocol (RFC 742)",
        { action => 'PARAM', proto => 'tcp', dport => '79' },
     ],
     'GNUnet' => [
+       "GNUnet secure peer-to-peer networking traffic",
        { action => 'PARAM', proto => 'tcp', dport => '2086' },
        { action => 'PARAM', proto => 'udp', dport => '2086' },
        { action => 'PARAM', proto => 'tcp', dport => '1080' },
        { action => 'PARAM', proto => 'udp', dport => '1080' },
     ],
     'GRE' => [
+       "Generic Routing Encapsulation tunneling protocol (bidirectional)",
        { action => 'PARAM', proto => '47' },
        { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
     ],
     'Git' => [
+       "Git distributed revision control traffic",
        { action => 'PARAM', proto => 'tcp', dport => '9418' },
     ],
-    'Gnutella' => [
-       { action => 'PARAM', proto => 'tcp', dport => '6346' },
-       { action => 'PARAM', proto => 'udp', dport => '6346' },
-    ],
     'HKP' => [
+       "OpenPGP HTTP keyserver protocol traffic",
        { action => 'PARAM', proto => 'tcp', dport => '11371' },
     ],
     'HTTP' => [
+       "Hypertext Transfer Protocol (WWW)",
        { action => 'PARAM', proto => 'tcp', dport => '80' },
     ],
     'HTTPS' => [
+       "Hypertext Transfer Protocol (WWW) over SSL",
        { action => 'PARAM', proto => 'tcp', dport => '443' },
     ],
     'ICPV2' => [
+       "Internet Cache Protocol V2 (Squid) traffic",
        { action => 'PARAM', proto => 'udp', dport => '3130' },
     ],
     'ICQ' => [
+       "AOL Instant Messenger traffic",
        { action => 'PARAM', proto => 'tcp', dport => '5190' },
     ],
     'IMAP' => [
+       "Internet Message Access Protocol",
        { action => 'PARAM', proto => 'tcp', dport => '143' },
     ],
     'IMAPS' => [
+       "Internet Message Access Protocol over SSL",
        { action => 'PARAM', proto => 'tcp', dport => '993' },
     ],
     'IPIP' => [
+       "IPIP capsulation traffic (bidirectional)",
        { action => 'PARAM', proto => '94' },
        { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '94' },
     ],
-    'IPP' => [
-       { action => 'PARAM', proto => 'tcp', dport => '631' },
-    ],
-    'IPPbrd' => [
-       { action => 'PARAM', proto => 'udp', dport => '631' },
-    ],
-    'IPPserver' => [
-       { action => 'PARAM', source => 'SOURCE', dest => 'DEST', proto => 'tcp', dport => '631' },
-       { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '631' },
-    ],
     'IPsec' => [
+       "IPsec traffic (bidirectional)",
        { 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)",
        { 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)",
        { action => 'PARAM', proto => 'udp', dport => '500' },
        { action => 'PARAM', proto => 'udp', dport => '4500' },
        { action => 'PARAM', proto => '50' },
@@ -181,123 +243,142 @@ my $pve_fw_macros = {
        { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
     ],
     'IRC' => [
+       "Internet Relay Chat traffic",
        { action => 'PARAM', proto => 'tcp', dport => '6667' },
     ],
-    'JabberPlain' => [
-       { action => 'PARAM', proto => 'tcp', dport => '5222' },
-    ],
-    'JabberSecure' => [
-       { action => 'PARAM', proto => 'tcp', dport => '5223' },
-    ],
-    'Jabberd' => [
-       { action => 'PARAM', proto => 'tcp', dport => '5269' },
-    ],
     'Jetdirect' => [
+       "HP Jetdirect printing",
        { action => 'PARAM', proto => 'tcp', dport => '9100' },
     ],
     '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 => '389' },
     ],
     'LDAPS' => [
+       "Secure Lightweight Directory Access Protocol traffic",
        { action => 'PARAM', proto => 'tcp', dport => '636' },
     ],
     'MSNP' => [
+       "Microsoft Notification Protocol",
        { action => 'PARAM', proto => 'tcp', dport => '1863' },
     ],
     'MSSQL' => [
+       "Microsoft SQL Server",
        { action => 'PARAM', proto => 'tcp', dport => '1433' },
     ],
     'Mail' => [
+       "Mail traffic (SMTP, SMTPS, Submission)",
        { action => 'PARAM', proto => 'tcp', dport => '25' },
        { action => 'PARAM', proto => 'tcp', dport => '465' },
        { action => 'PARAM', proto => 'tcp', dport => '587' },
     ],
     'Munin' => [
+       "Munin networked resource monitoring traffic",
        { action => 'PARAM', proto => 'tcp', dport => '4949' },
     ],
     'MySQL' => [
+       "MySQL server",
        { action => 'PARAM', proto => 'tcp', dport => '3306' },
     ],
     'NNTP' => [
+       "NNTP traffic (Usenet).",
        { action => 'PARAM', proto => 'tcp', dport => '119' },
     ],
     'NNTPS' => [
+       "Encrypted NNTP traffic (Usenet)",
        { action => 'PARAM', proto => 'tcp', dport => '563' },
     ],
     'NTP' => [
+       "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' },
     ],
-    'NTPbrd' => [
-       { action => 'PARAM', proto => 'udp', dport => '123' },
-       { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '123' },
-    ],
     'OSPF' => [
+       "OSPF multicast traffic",
        { action => 'PARAM', proto => '89' },
     ],
     'OpenVPN' => [
+       "OpenVPN traffic",
        { action => 'PARAM', proto => 'udp', dport => '1194' },
     ],
     'PCA' => [
+       "Symantec PCAnywere (tm)",
        { action => 'PARAM', proto => 'udp', dport => '5632' },
        { action => 'PARAM', proto => 'tcp', dport => '5631' },
     ],
     'POP3' => [
+       "POP3 traffic",
        { action => 'PARAM', proto => 'tcp', dport => '110' },
     ],
     'POP3S' => [
+       "Encrypted POP3 traffic",
        { action => 'PARAM', proto => 'tcp', dport => '995' },
     ],
     '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' => [
+       "ICMP echo request",
        { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
     ],
     'PostgreSQL' => [
+       "PostgreSQL server",
        { action => 'PARAM', proto => 'tcp', dport => '5432' },
     ],
     'Printer' => [
+       "Line Printer protocol printing",
        { action => 'PARAM', proto => 'tcp', dport => '515' },
     ],
     'RDP' => [
+       "Microsoft Remote Desktop Protocol traffic",
        { action => 'PARAM', proto => 'tcp', dport => '3389' },
     ],
     'RIPbi' => [
+       "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 => 'tcp', dport => '953' },
     ],
     'Razor' => [
+       "Razor Antispam System",
        { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
     ],
     'Rdate' => [
+       "Remote time retrieval (rdate)",
        { action => 'PARAM', proto => 'tcp', dport => '37' },
     ],
     'Rsync' => [
+       "Rsync server",
        { action => 'PARAM', proto => 'tcp', dport => '873' },
     ],
     'SANE' => [
+       "SANE network scanning",
        { action => 'PARAM', proto => 'tcp', dport => '6566' },
     ],
     'SMB' => [
+       "Microsoft SMB traffic",
        { 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' },
     ],
     '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' },
@@ -308,81 +389,104 @@ my $pve_fw_macros = {
        { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'tcp', dport => '135,139,445' },
     ],
     'SMBswat' => [
+       "Samba Web Administration Tool",
        { action => 'PARAM', proto => 'tcp', dport => '901' },
     ],
     'SMTP' => [
+       "Simple Mail Transfer Protocol",
        { action => 'PARAM', proto => 'tcp', dport => '25' },
     ],
     'SMTPS' => [
+       "Encrypted Simple Mail Transfer Protocol",
        { action => 'PARAM', proto => 'tcp', dport => '465' },
     ],
     'SNMP' => [
+       "Simple Network Management Protocol",
        { action => 'PARAM', proto => 'udp', dport => '161:162' },
        { action => 'PARAM', proto => 'tcp', dport => '161' },
     ],
     'SPAMD' => [
+       "Spam Assassin SPAMD traffic",
        { action => 'PARAM', proto => 'tcp', dport => '783' },
     ],
     'SSH' => [
+       "Secure shell traffic",
        { action => 'PARAM', proto => 'tcp', dport => '22' },
     ],
     'SVN' => [
+       "Subversion server (svnserve)",
        { action => 'PARAM', proto => 'tcp', dport => '3690' },
     ],
     'SixXS' => [
+       "SixXS IPv6 Deployment and Tunnel Broker",
        { action => 'PARAM', proto => 'tcp', dport => '3874' },
        { action => 'PARAM', proto => 'udp', dport => '3740' },
        { action => 'PARAM', proto => '41' },
        { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
     ],
     'Squid' => [
+       "Squid web proxy traffic",
        { action => 'PARAM', proto => 'tcp', dport => '3128' },
     ],
     'Submission' => [
+       "Mail message submission traffic",
        { action => 'PARAM', proto => 'tcp', dport => '587' },
     ],
     'Syslog' => [
+       "Syslog protocol (RFC 5424) traffic",
        { action => 'PARAM', proto => 'udp', dport => '514' },
        { action => 'PARAM', proto => 'tcp', dport => '514' },
     ],
     'TFTP' => [
+       "Trivial File Transfer Protocol traffic",
        { action => 'PARAM', proto => 'udp', dport => '69' },
     ],
     'Telnet' => [
+       "Telnet traffic",
        { action => 'PARAM', proto => 'tcp', dport => '23' },
     ],
     'Telnets' => [
+       "Telnet over SSL",
        { action => 'PARAM', proto => 'tcp', dport => '992' },
     ],
     'Time' => [
+       "RFC 868 Time protocol",
        { action => 'PARAM', proto => 'tcp', dport => '37' },
     ],
     'Trcrt' => [
+       "Traceroute (for up to 30 hops) traffic",
        { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
        { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
     ],
     'VNC' => [
+       "VNC traffic for VNC display's 0 - 9",
        { action => 'PARAM', proto => 'tcp', dport => '5900:5909' },
     ],
     'VNCL' => [
+       "VNC traffic from Vncservers to Vncviewers in listen mode",
        { action => 'PARAM', proto => 'tcp', dport => '5500' },
     ],
     'Web' => [
+       "WWW traffic (HTTP and HTTPS)",
        { action => 'PARAM', proto => 'tcp', dport => '80' },
        { action => 'PARAM', proto => 'tcp', dport => '443' },
     ],
     'Webcache' => [
+       "Web Cache/Proxy traffic (port 8080)",
        { action => 'PARAM', proto => 'tcp', dport => '8080' },
     ],
     'Webmin' => [
+       "Webmin traffic",
        { action => 'PARAM', proto => 'tcp', dport => '10000' },
     ],
     'Whois' => [
+       "Whois (nicname, RFC 3912) traffic",
        { action => 'PARAM', proto => 'tcp', dport => '43' },
     ],
 };
 
 my $pve_fw_parsed_macros;
+my $pve_fw_macro_descr;
 my $pve_fw_preferred_macro_names = {};
 
 my $pve_std_chains = {
@@ -396,12 +500,12 @@ my $pve_std_chains = {
        { action => 'DROP', dsttype => 'BROADCAST' },
        { action => 'DROP', dsttype => 'MULTICAST' },
        { action => 'DROP', dsttype => 'ANYCAST' },
-       { action => 'DROP', dest => '224.0.0.0/4' }, 
+       { 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', 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",
@@ -409,7 +513,7 @@ my $pve_std_chains = {
        "-j REJECT --reject-with icmp-host-prohibited",
     ],
     'PVEFW-Drop' => [
-       # same as shorewall 'Drop', which is equal to 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'
@@ -432,7 +536,7 @@ my $pve_std_chains = {
        { action => 'DROP', proto => 'udp', sport => 53 },
     ],
     'PVEFW-Reject' => [
-       # same as shorewall 'Reject', which is equal to 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'
@@ -520,6 +624,9 @@ sub init_firewall_macros {
     foreach my $k (keys %$pve_fw_macros) {
        my $lc_name = lc($k);
        my $macro = $pve_fw_macros->{$k};
+       if (!ref($macro->[0])) {
+           $pve_fw_macro_descr->{$k} = shift @$macro;
+       }
        $pve_fw_preferred_macro_names->{$lc_name} = $k;
        $pve_fw_parsed_macros->{$k} = $macro;
     }
@@ -527,6 +634,10 @@ sub init_firewall_macros {
 
 init_firewall_macros();
 
+sub get_macros {
+    return wantarray ? ($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
+}
+
 my $etc_services;
 
 sub get_etc_services {
@@ -600,47 +711,58 @@ sub get_etc_protocols {
 sub parse_address_list {
     my ($str) = @_;
 
-    my $nbaor = 0;
-    foreach my $aor (split(/,/, $str)) {
-       if (!Net::IP->new($aor)) {
+    return if $str =~ m/^(\+)(\S+)$/; # ipset ref
+    return if $str =~ m/^${security_group_pattern}$/; # aliases
+
+    my $count = 0;
+    my $iprange = 0;
+    foreach my $elem (split(/,/, $str)) {
+       $count++;
+       if (!Net::IP->new($elem)) {
            my $err = Net::IP::Error();
            die "invalid IP address: $err\n";
-       }else{
-           $nbaor++;
        }
+       $iprange = 1 if $elem =~ m/-/;
     }
-    return $nbaor;
+    
+    die "you can use a range in a list\n" if $iprange && $count > 1;
 }
 
 sub parse_port_name_number_or_range {
     my ($str) = @_;
 
     my $services = PVE::Firewall::get_etc_services();
-    my $nbports = 0;
+    my $count = 0;
+    my $icmp_port = 0;
+
     foreach my $item (split(/,/, $str)) {
-       my $portlist = "";
-       my $oldpon = undef;
-       $nbports++;
-       foreach my $pon (split(':', $item, 2)) {
-           $pon = $services->{byname}->{$pon}->{port} if $services->{byname}->{$pon}->{port};
-           if ($pon =~ m/^\d+$/){
-               die "invalid port '$pon'\n" if $pon < 0 && $pon > 65535;
-               die "port '$pon' must be bigger than port '$oldpon' \n" if $oldpon && ($pon < $oldpon);
-               $oldpon = $pon;
-           }else{
-               die "invalid port $services->{byname}->{$pon}\n" if !$services->{byname}->{$pon};
+       $count++;
+       if ($item =~ m/^(\d+):(\d+)$/) {
+           my ($port1, $port2) = ($1, $2);
+           die "invalid port '$port1'\n" if $port1 > 65535;
+           die "invalid port '$port2'\n" if $port2 > 65535;
+       } elsif ($item =~ m/^(\d+)$/) {
+           my $port = $1;
+           die "invalid port '$port'\n" if $port > 65535;
+       } else {
+           if ($icmp_type_names->{$item}) {
+               $icmp_port = 1;
+           } else {
+               die "invalid port '$item'\n" if !$services->{byname}->{$item}; 
            }
        }
     }
 
-    return ($nbports);
+    die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
+
+    return $count;
 }
 
 PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
 sub pve_fw_verify_port_spec {
    my ($portstr) = @_;
 
-    parse_port_name_number_or_range($portstr);
+   parse_port_name_number_or_range($portstr);
 
    return $portstr;
 }
@@ -670,6 +792,52 @@ sub pve_fw_verify_protocol_spec {
 
 # helper function for API
 
+sub copy_opject_with_digest {
+    my ($object) = @_;
+
+    my $sha = Digest::SHA->new('sha1');
+
+    my $res = {};
+    foreach my $k (sort keys %$object) {
+       my $v = $object->{$k};
+       next if !defined($v);
+       $res->{$k} = $v;
+       $sha->add($k, ':', $v, "\n");
+    }
+
+    my $digest = $sha->b64digest;
+
+    $res->{digest} = $digest;
+
+    return wantarray ? ($res, $digest) : $res;
+}
+
+sub copy_list_with_digest {
+    my ($list) = @_;
+
+    my $sha = Digest::SHA->new('sha1');
+
+    my $res = [];
+    foreach my $entry (@$list) {
+       my $data = {};
+       foreach my $k (sort keys %$entry) {
+           my $v = $entry->{$k};
+           next if !defined($v);
+           $data->{$k} = $v;
+           $sha->add($k, ':', $v, "\n");
+       }
+       push @$res, $data;
+    }
+
+    my $digest = $sha->b64digest;
+
+    foreach my $entry (@$res) {
+       $entry->{digest} = $digest;
+    }
+
+    return wantarray ? ($res, $digest) : $res;
+}
+
 my $rule_properties = {
     pos => {
        description => "Update rule at position <pos>.",
@@ -677,21 +845,19 @@ my $rule_properties = {
        minimum => 0,
        optional => 1,
     },
-    digest => {
-       type => 'string',
-       optional => 1,
-       maxLength => 27,
-       minLength => 27,
-    },
+    digest => get_standard_option('pve-config-digest'),
     type => {
        type => 'string',
        optional => 1,
        enum => ['in', 'out', 'group'],
     },
     action => {
+       description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
        type => 'string',
        optional => 1,
-       enum => ['ACCEPT', 'DROP', 'REJECT'],
+       pattern => $security_group_pattern,
+       maxLength => 20,
+       minLength => 2,
     },
     macro => {
        type => 'string',
@@ -729,31 +895,136 @@ my $rule_properties = {
     },
 };
 
-sub cleanup_fw_rule {
-    my ($rule, $digest, $pos) = @_;
+sub add_rule_properties {
+    my ($properties) = @_;
 
-    my $r = {};
+    foreach my $k (keys %$rule_properties) {
+       my $h = $rule_properties->{$k};
+       # copy data, so that we can modify later without side effects
+       foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
+    }
 
-    foreach my $k (keys %$rule) {
-       next if !$rule_properties->{$k};
-       my $v = $rule->{$k};
-       next if !defined($v);
-       $r->{$k} = $v;
-       $r->{digest} = $digest;
-       $r->{pos} = $pos;
+    return $properties;
+}
+
+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});
+       raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
+           if $opt eq 'type' || $opt eq 'action';
+       delete $rule->{$opt};
     }
 
-    return $r;
+    return $rule;
 }
 
-sub add_rule_properties {
-    my ($properties) = @_;
+my $apply_macro = sub {
+    my ($macro_name, $param, $verify) = @_;
 
-    foreach my $k (keys %$rule_properties) {
-       $properties->{$k} = $rule_properties->{$k};
+    my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
+    die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
+
+    my $rules = [];
+
+    foreach my $templ (@$macro_rules) {
+       my $rule = {};
+       my $param_used = {};
+       foreach my $k (keys %$templ) {
+           my $v = $templ->{$k};
+           if ($v eq 'PARAM') {
+               $v = $param->{$k};
+               $param_used->{$k} = 1;
+           } elsif ($v eq 'DEST') {
+               $v = $param->{dest};
+               $param_used->{dest} = 1;
+           } elsif ($v eq 'SOURCE') {
+               $v = $param->{source};
+               $param_used->{source} = 1;
+           }
+
+           if (!defined($v)) {
+               my $msg = "missing parameter '$k' in macro '$macro_name'";
+               raise_param_exc({ macro => $msg }) if $verify; 
+               die "$msg\n";
+           }
+           $rule->{$k} = $v;
+       }
+       foreach my $k (keys %$param) {
+           next if $k eq 'macro';
+           next if !defined($param->{$k});
+           next if $param_used->{$k};
+           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; 
+                   die "$msg\n";
+               }
+           } else {
+               $rule->{$k} = $param->{$k};
+           }
+       }
+       push @$rules, $rule;
     }
-    
-    return $properties;
+
+    return $rules;
+};
+
+sub verify_rule {
+    my ($rule, $allow_groups) = @_;
+
+    my $type = $rule->{type};
+
+    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}?
+
+    if ($rule->{macro}) {
+       my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
+       raise_param_exc({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
+       $rule->{macro} = $preferred_name;
+    }
+
+    if ($rule->{dport}) {
+       eval { parse_port_name_number_or_range($rule->{dport}); };
+       raise_param_exc({ dport => $@ }) if $@;
+    }
+
+    if ($rule->{sport}) {
+       eval { parse_port_name_number_or_range($rule->{sport}); };
+       raise_param_exc({ sport => $@ }) if $@;
+    }
+
+    if ($rule->{source}) {
+       eval { parse_address_list($rule->{source}); };
+       raise_param_exc({ source => $@ }) if $@;
+    }
+
+    if ($rule->{dest}) {
+       eval { parse_address_list($rule->{dest}); };
+       raise_param_exc({ dest => $@ }) if $@;
+    }
+
+    if ($rule->{macro}) {
+       &$apply_macro($rule->{macro}, $rule, 1);
+    }
+
+    return $rule;
 }
 
 sub copy_rule_data {
@@ -770,6 +1041,9 @@ sub copy_rule_data {
            delete $rule->{$k};
        }
     }
+
+    # verify rule now
+
     return $rule;
 }
 
@@ -791,12 +1065,6 @@ sub enable_bridge_firewall {
 
 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
 
-sub iptables {
-    my ($cmd) = @_;
-
-    run_command("/sbin/iptables $cmd", outfunc => sub {}, errfunc => sub {});
-}
-
 sub iptables_restore_cmdlist {
     my ($cmdlist) = @_;
 
@@ -806,7 +1074,7 @@ sub iptables_restore_cmdlist {
 sub ipset_restore_cmdlist {
     my ($cmdlist) = @_;
 
-    run_command(" /usr/sbin/ipset restore", input => $cmdlist);
+    run_command("/usr/sbin/ipset restore", input => $cmdlist);
 }
 
 sub iptables_get_chains {
@@ -898,8 +1166,10 @@ sub ipset_get_chains {
 
        return if $line =~ m/^#/;
        return if $line =~ m/^\s*$/;
-       if ($line =~ m/^(\S+)\s(\S+)\s(\S+)/) {
-           push @{$chains->{$2}}, $line;
+       if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
+           my $chain = $1;
+           $line =~ s/\s+$//; # delete trailing white space
+           push @{$chains->{$chain}}, $line;
        } else {
            # simply ignore the rest
            return;
@@ -916,30 +1186,8 @@ sub ipset_get_chains {
     return $res;
 }
 
-sub iptables_chain_exist {
-    my ($chain) = @_;
-
-    eval{
-       iptables("-n --list $chain");
-    };
-    return undef if $@;
-
-    return 1;
-}
-
-sub iptables_rule_exist {
-    my ($rule) = @_;
-
-    eval{
-       iptables("-C $rule");
-    };
-    return undef if $@;
-
-    return 1;
-}
-
 sub ruleset_generate_cmdstr {
-    my ($ruleset, $chain, $rule, $actions, $goto) = @_;
+    my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
 
     return if defined($rule->{enable}) && !$rule->{enable};
 
@@ -947,18 +1195,48 @@ sub ruleset_generate_cmdstr {
 
     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 $nbsource = $rule->{source} ? parse_address_list( $rule->{source}) : 0;
-    my $nbdest = $rule->{dest} ? parse_address_list($rule->{dest}) : 0;
 
     my @cmd = ();
 
     push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
     push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
 
-    push @cmd, "-m iprange --src-range" if $nbsource > 1;
-    push @cmd, "-s $rule->{source}" if $rule->{source};
-    push @cmd, "-m iprange --dst-range" if $nbdest > 1;
-    push @cmd, "-d $rule->{dest}" if $rule->{dest};
+    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/^${security_group_pattern}$/){
+           die "no such alias $source" if !$cluster_conf->{aliases}->{$source};
+           push @cmd, "-s $cluster_conf->{aliases}->{$source}";
+
+        } elsif ($source =~ m/\-/){
+           push @cmd, "-m iprange --src-range $source";
+
+       } 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/^${security_group_pattern}$/){
+           die "no such alias $dest" if !$cluster_conf->{aliases}->{$dest};
+           push @cmd, "-d $cluster_conf->{aliases}->{$dest}";
+
+        } 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}";
@@ -969,7 +1247,7 @@ sub ruleset_generate_cmdstr {
 
        push @cmd, "--match multiport" if $multiport;
 
-       die "multiport: option '--sports' cannot be used together with '--dports'\n" 
+       die "multiport: option '--sports' cannot be used together with '--dports'\n"
            if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
 
        if ($rule->{dport}) {
@@ -1005,7 +1283,7 @@ sub ruleset_generate_cmdstr {
     push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
 
     if (my $action = $rule->{action}) {
-       $action = $actions->{$action} if defined($actions->{$action}); 
+       $action = $actions->{$action} if defined($actions->{$action});
        $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
        push @cmd, $goto ? "-g $action" : "-j $action";
     }
@@ -1013,52 +1291,8 @@ sub ruleset_generate_cmdstr {
     return scalar(@cmd) ? join(' ', @cmd) : undef;
 }
 
-my $apply_macro = sub {
-    my ($macro_name, $param) = @_;
-
-    my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
-    die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
-
-    my $rules = [];
-
-    foreach my $templ (@$macro_rules) {
-       my $rule = {};
-       my $param_used = {};
-       foreach my $k (keys %$templ) {
-           my $v = $templ->{$k};
-           if ($v eq 'PARAM') {
-               $v = $param->{$k};
-               $param_used->{$k} = 1;
-           } elsif ($v eq 'DEST') {
-               $v = $param->{dest};
-               $param_used->{dest} = 1;
-           } elsif ($v eq 'SOURCE') {
-               $v = $param->{source};
-               $param_used->{source} = 1;
-           }
-
-           die "missing parameter '$k' in macro '$macro_name'\n" if !defined($v);
-           $rule->{$k} = $v;
-       }
-       foreach my $k (keys %$param) {
-           next if $k eq 'macro';
-           next if !defined($param->{$k});
-           next if $param_used->{$k};
-           if (defined($rule->{$k})) {
-               die "parameter '$k' already define in macro (value = '$rule->{$k}')\n"
-                   if $rule->{$k} ne $param->{$k};
-           } else {
-               $rule->{$k} = $param->{$k};
-           }
-       }
-       push @$rules, $rule;
-    }
-
-    return $rules;
-};
-
 sub ruleset_generate_rule {
-    my ($ruleset, $chain, $rule, $actions, $goto) = @_;
+    my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
 
     my $rules;
 
@@ -1068,8 +1302,8 @@ sub ruleset_generate_rule {
        $rules = [ $rule ];
     }
 
-    foreach my $tmp (@$rules) { 
-       if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto)) {
+    foreach my $tmp (@$rules) {
+       if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
            ruleset_addrule($ruleset, $chain, $cmdstr);
        }
     }
@@ -1120,12 +1354,12 @@ sub ruleset_insertrule {
 
 sub get_log_rule_base {
     my ($chain, $vmid, $msg, $loglevel) = @_;
-    
+
     die "internal error - no log level" if !defined($loglevel);
 
     $vmid = 0 if !defined($vmid);
 
-    # Note: we use special format for prefix to pass further 
+    # Note: we use special format for prefix to pass further
     # info to log daemon (VMID, LOGVELEL and CHAIN)
 
     return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
@@ -1200,44 +1434,42 @@ sub ruleset_add_chain_policy {
 }
 
 sub ruleset_create_vm_chain {
-    my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
+    my ($ruleset, $chain, $options, $host_options, $macaddr, $direction) = @_;
 
     ruleset_create_chain($ruleset, $chain);
     my $accept = generate_nfqueue($options);
 
-    if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
+    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 ($direction eq 'OUT') {
-           ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK', 
+           ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
                                                      proto => 'udp', sport => 68, dport => 67 });
        } else {
-           ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT', 
+           ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
                                                      proto => 'udp', sport => 67, dport => 68 });
        }
     }
 
-    if ($options->{tcpflags}) {
+    if ($host_options->{tcpflags}) {
        ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
     }
 
     ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
-    if($direction eq 'OUT'){
+    if ($direction eq 'OUT') {
        ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -g PVEFW-SET-ACCEPT-MARK");
-
-    }else{
+    } else {
        ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
     }
+
     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
     }
-
-
 }
 
 sub ruleset_generate_vm_rules {
@@ -1249,7 +1481,7 @@ sub ruleset_generate_vm_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"; 
+           my $group_chain = "GROUP-$rule->{action}-$direction";
            if(!ruleset_chain_exist($ruleset, $group_chain)){
                generate_group_rules($ruleset, $cluster_conf, $rule->{action});
            }
@@ -1264,11 +1496,11 @@ sub ruleset_generate_vm_rules {
        } 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" });
+               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" });
+               ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject" }, undef, $cluster_conf);
            }
        }
     }
@@ -1287,7 +1519,7 @@ sub generate_nfqueue {
                $action .= " --queue-num $1";
            }
        }
-       $action .= " --queue-bypass";
+       $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
     }else{
        $action = "ACCEPT";
     }
@@ -1315,7 +1547,7 @@ sub ruleset_generate_vm_ipsrules {
 }
 
 sub generate_venet_rules_direction {
-    my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
+    my ($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
 
     parse_address_list($ip); # make sure we have a valid $ip list
 
@@ -1324,11 +1556,12 @@ sub generate_venet_rules_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, undef, $direction);
+    ruleset_create_vm_chain($ruleset, $chain, $options, $hostfw_options, undef, $direction);
 
     ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
 
@@ -1370,18 +1603,19 @@ sub generate_venet_rules_direction {
 }
 
 sub generate_tap_rules_direction {
-    my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
+    my ($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
 
     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, $macaddr, $direction);
+    ruleset_create_vm_chain($ruleset, $tapchain, $options, $hostfw_options, $macaddr, $direction);
 
     ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
 
@@ -1413,10 +1647,10 @@ sub generate_tap_rules_direction {
 sub enable_host_firewall {
     my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
 
-    # fixme: allow security groups
-
     my $options = $hostfw_conf->{options};
+    my $cluster_options = $cluster_conf->{options};
     my $rules = $hostfw_conf->{rules};
+    my $cluster_rules = $cluster_conf->{rules};
 
     # host inbound firewall
     my $chain = "PVEFW-HOST-IN";
@@ -1442,13 +1676,14 @@ sub enable_host_firewall {
     # we use RETURN because we need to check also tap rules
     my $accept_action = 'RETURN';
 
-    foreach my $rule (@$rules) {
+    # 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" });
+       ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
     }
 
     # implement input policy
-    my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
+    my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
     ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
 
     # host outbound firewall
@@ -1467,13 +1702,14 @@ sub enable_host_firewall {
     # we use RETURN because we may want to check other thigs later
     $accept_action = 'RETURN';
 
-    foreach my $rule (@$rules) {
+    # 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" });
+       ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
     }
 
     # implement output policy
-    $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
+    $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
     ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
 
     ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
@@ -1493,7 +1729,7 @@ sub generate_group_rules {
 
     foreach my $rule (@$rules) {
        next if $rule->{type} ne 'in';
-       ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
+       ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
     }
 
     $chain = "GROUP-${group}-OUT";
@@ -1505,8 +1741,8 @@ sub generate_group_rules {
        next if $rule->{type} ne 'out';
        # 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" });
+       ruleset_generate_rule($ruleset, $chain, $rule,
+                             { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
     }
 }
 
@@ -1561,7 +1797,7 @@ sub parse_fw_rule {
        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/^[A-Za-z0-9_\-]+$/;    
+       die "invalid characters in group name\n" if $action !~ m/^${security_group_pattern}$/;
     } else {
        die "unknown rule type '$type'\n";
     }
@@ -1581,7 +1817,7 @@ sub parse_fw_rule {
 
     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;
 
@@ -1607,7 +1843,7 @@ sub parse_vmfw_option {
 
     my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
 
-    if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
+    if ($line =~ m/^(enable|dhcp|macfilter|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) {
@@ -1634,16 +1870,13 @@ sub parse_hostfw_option {
 
     my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
 
-    if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
+    if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\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 = $2 ? lc($3) : '';
-    } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
-       $opt = lc($1);
-       $value = uc($3);
-    } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
+    } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
        $opt = lc($1);
        $value = int($2);
     } else {
@@ -1662,6 +1895,9 @@ sub parse_clusterfw_option {
     if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
        $opt = lc($1);
        $value = int($2);
+    } 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"
@@ -1670,6 +1906,25 @@ sub parse_clusterfw_option {
     return ($opt, $value);
 }
 
+sub parse_clusterfw_alias {
+    my ($line) = @_;
+
+    my ($opt, $value);
+    if ($line =~ m/^(\S+)\s(\S+)$/) {
+       $opt = lc($1);
+       if($2){
+           $2 =~ s|/32$||;
+           pve_verify_ipv4_or_cidr($2) if $2;
+           $value = $2;
+       }
+    } else {
+       chomp $line;
+       die "can't parse option '$line'\n";
+    }
+
+    return ($opt, $value);
+}
+
 sub parse_vm_fw_rules {
     my ($filename, $fh) = @_;
 
@@ -1677,11 +1932,7 @@ sub parse_vm_fw_rules {
 
     my $section;
 
-    my $digest = Digest::SHA->new('sha1');
-
     while (defined(my $line = <$fh>)) {
-       $digest->add($line);
-
        next if $line =~ m/^#/;
        next if $line =~ m/^\s*$/;
 
@@ -1719,8 +1970,6 @@ sub parse_vm_fw_rules {
        push @{$res->{$section}}, $rule;
     }
 
-    $res->{digest} = $digest->b64digest;
-
     return $res;
 }
 
@@ -1731,11 +1980,7 @@ sub parse_host_fw_rules {
 
     my $section;
 
-    my $digest = Digest::SHA->new('sha1');
-
     while (defined(my $line = <$fh>)) {
-       $digest->add($line);
-
        next if $line =~ m/^#/;
        next if $line =~ m/^\s*$/;
 
@@ -1769,12 +2014,10 @@ sub parse_host_fw_rules {
            warn "$prefix: $err";
            next;
        }
-       
+
        push @{$res->{$section}}, $rule;
     }
 
-    $res->{digest} = $digest->b64digest;
-
     return $res;
 }
 
@@ -1784,13 +2027,16 @@ sub parse_cluster_fw_rules {
     my $section;
     my $group;
 
-    my $res = { rules => [], options => {}, groups => {}, ipset => {} };
-
-    my $digest = Digest::SHA->new('sha1');
+    my $res = { 
+       rules => [], 
+       options => {}, 
+       groups => {}, 
+       group_comments => {}, 
+       ipset => {} ,
+       ipset_comments => {}, 
+    };
 
     while (defined(my $line = <$fh>)) {
-       $digest->add($line);
-
        next if $line =~ m/^#/;
        next if $line =~ m/^\s*$/;
 
@@ -1802,9 +2048,18 @@ sub parse_cluster_fw_rules {
            next;
        }
 
-       if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
+       if ($line =~ m/^\[aliases\]$/i) {
+           $section = 'aliases';
+           next;
+       }
+
+       if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
            $section = 'groups';
            $group = lc($1);
+           my $comment = $2;
+           $res->{$section}->{$group} = [];
+           $res->{group_comments}->{$group} =  decode('utf8', $comment)
+               if $comment;
            next;
        }
 
@@ -1812,23 +2067,19 @@ sub parse_cluster_fw_rules {
            $section = 'rules';
            next;
        }
-    
-       if ($line =~ m/^\[ipgroup\s+(\S+)\]\s*$/i) {
-           $section = 'ipset';
-           $group = lc($1);
-           $res->{$section}->{$group}->{type} = 'hash:ip family inet hashsize 1024 maxelem 65536 ';
-           next;
-       }
 
-       if ($line =~ m/^\[netgroup\s+(\S+)\]\s*$/i) {
+       if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
            $section = 'ipset';
            $group = lc($1);
-           $res->{$section}->{$group}->{type} = 'hash:net family inet hashsize 1024 maxelem 65536 ';
+           my $comment = $2;
+           $res->{$section}->{$group} = [];
+           $res->{ipset_comments}->{$group} = decode('utf8', $comment) 
+               if $comment;
            next;
        }
 
        if (!$section) {
-           warn "$prefix: skip line - no section";
+           warn "$prefix: skip line - no section\n";
            next;
        }
 
@@ -1838,6 +2089,12 @@ sub parse_cluster_fw_rules {
                $res->{options}->{$opt} = $value;
            };
            warn "$prefix: $@" if $@;
+       } elsif ($section eq 'aliases') {
+           eval {
+               my ($opt, $value) = parse_clusterfw_alias($line);
+               $res->{aliases}->{$opt} = $value;
+           };
+           warn "$prefix: $@" if $@;
        } elsif ($section eq 'rules') {
            my $rule;
            eval { $rule = parse_fw_rule($line, 1, 1); };
@@ -1855,18 +2112,31 @@ sub parse_cluster_fw_rules {
            }
            push @{$res->{$section}->{$group}}, $rule;
        } elsif ($section eq 'ipset') {
-           chomp $line;
-           my $ip;
-           if (!Net::IP->new($line)) {
-               warn "$prefix: $line is not an valid ip address";
-               next;
+           # we can add single line comments to the end of the rule
+           my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
+
+           $line =~ m/^(\!)?\s*(\S+)\s*$/;
+           my $nomatch = $1;
+           my $cidr = $2;
+
+           if($cidr !~ m/^${security_group_pattern}$/) {
+               $cidr =~ s|/32$||;
+           
+               eval { pve_verify_ipv4_or_cidr($cidr); };
+               if (my $err = $@) {
+                   warn "$prefix: $cidr - $err";
+                   next;
+               }
            }
-           push @{$res->{$section}->{$group}->{ip}}, $line;
+
+           my $entry = { cidr => $cidr }; 
+           $entry->{nomatch} = 1 if $nomatch;
+           $entry->{comment} = $comment if $comment;
+           
+           push @{$res->{$section}->{$group}}, $entry;
        }
     }
 
-    $res->{digest} = $digest->b64digest;
-
     return $res;
 }
 
@@ -1931,6 +2201,96 @@ sub load_vmfw_conf {
     return $vmfw_conf;
 }
 
+my $format_rules = sub {
+    my ($rules, $need_iface) = @_;
+
+    my $raw = '';
+
+    foreach my $rule (@$rules) {
+       if ($rule->{type} eq  'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
+           $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
+           $raw .= uc($rule->{type});
+           if ($rule->{macro}) {
+               $raw .= " $rule->{macro}($rule->{action})";
+           } else {
+               $raw .= " " . $rule->{action};
+           }
+           $raw .= " " . ($rule->{iface} || '-') if $need_iface;
+
+           if ($rule->{type} ne  'group')  {
+               $raw .= " " . ($rule->{source} || '-');
+               $raw .= " " . ($rule->{dest} || '-');
+               $raw .= " " . ($rule->{proto} || '-');
+               $raw .= " " . ($rule->{dport} || '-');
+               $raw .= " " . ($rule->{sport} || '-');
+           }
+
+           $raw .= " # " . encode('utf8', $rule->{comment})
+               if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
+           $raw .= "\n";
+       } else {
+           die "unknown rule type '$rule->{type}'";
+       }
+    }
+
+    return $raw;
+};
+
+my $format_options = sub {
+    my ($options) = @_;
+
+    my $raw = '';
+
+    $raw .= "[OPTIONS]\n\n";
+    foreach my $opt (keys %$options) {
+       $raw .= "$opt: $options->{$opt}\n";
+    }
+    $raw .= "\n";
+
+    return $raw;
+};
+
+my $format_ipset = sub {
+    my ($options) = @_;
+
+    my $raw = '';
+
+    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";
+    }
+    return $raw;
+};
+
+sub save_vmfw_conf {
+    my ($vmid, $vmfw_conf) = @_;
+
+    my $raw = '';
+
+    my $options = $vmfw_conf->{options};
+    $raw .= &$format_options($options) if scalar(keys %$options);
+
+    my $rules = $vmfw_conf->{rules};
+    if (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);
+}
+
 sub read_vm_firewall_configs {
     my ($vmdata) = @_;
     my $vmfw_configs = {};
@@ -1963,11 +2323,12 @@ sub get_option_log_level {
 
 sub generate_std_chains {
     my ($ruleset, $options) = @_;
-    
+
     my $loglevel = get_option_log_level($options, 'smurf_log_level');
 
     # same as shorewall smurflog.
     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";
@@ -1975,6 +2336,8 @@ sub generate_std_chains {
     # 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";
@@ -1992,21 +2355,59 @@ sub generate_std_chains {
 }
 
 sub generate_ipset_chains {
-    my ($ipset_ruleset, $options) = @_;
+    my ($ipset_ruleset, $fw_conf) = @_;
 
-    foreach my $ipset (keys %{$options->{ipset}}) {
-       generate_ipset($ipset_ruleset, $ipset, $options->{ipset}->{$ipset});
+    foreach my $ipset (keys %{$fw_conf->{ipset}}) {
+       generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
     }
 }
 
 sub generate_ipset {
-    my ($ipset_ruleset, $name, $options) = @_;
+    my ($ipset_ruleset, $name, $options, $aliases) = @_;
+
+    my $hashsize = scalar(@$options);
+    if ($hashsize <= 64) {
+       $hashsize = 64;
+    } else {
+       $hashsize = round_powerof2($hashsize);
+    }
 
-    push @{$ipset_ruleset->{$name}}, "create $name $options->{type}";
+    push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
 
-    foreach my $ip (@{$options->{ip}}) {
-       push @{$ipset_ruleset->{$name}}, "add $name $ip";
+    # remove duplicates
+    my $nethash = {};
+    foreach my $entry (@$options) {
+       my $cidr = $entry->{cidr};
+       #check aliases
+       if ($cidr =~ m/^${security_group_pattern}$/){
+           die "no such alias $cidr" if !$aliases->{$cidr};
+           $entry->{cidr} = $aliases->{$cidr};
+       }
+       $nethash->{$entry->{cidr}} = $entry;
     }
+
+    foreach my $cidr (sort keys %$nethash) {
+       my $entry = $nethash->{$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;
+       }
+    }
+}
+
+sub round_powerof2 {
+    my ($int) = @_;
+
+    $int--;
+    $int |= $int >> $_ foreach (1,2,4,8,16);
+    return ++$int;
 }
 
 sub save_pvefw_status {
@@ -2071,60 +2472,43 @@ sub load_clusterfw_conf {
     return $cluster_conf;
 }
 
-my $rules_to_conf = sub {
-    my ($rules, $need_iface) = @_;
-
-    my $raw = '';
-
-    foreach my $rule (@$rules) {
-       if ($rule->{type} eq  'in' || $rule->{type} eq 'out') {
-           $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
-           $raw .= uc($rule->{type});
-           $raw .= " " . $rule->{action};
-           $raw .= " " . ($rule->{iface} || '-') if $need_iface;
-           $raw .= " " . ($rule->{source} || '-');
-           $raw .= " " . ($rule->{dest} || '-');
-           $raw .= " " . ($rule->{proto} || '-');
-           $raw .= " " . ($rule->{dport} || '-');
-           $raw .= " " . ($rule->{sport} || '-');
-           $raw .= " # " . encode('utf8', $rule->{comment}) 
-               if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
-           $raw .= "\n";
-       } else {
-           die "implement me '$rule->{type}'";
-       }
-    }
-
-    return $raw;
-};
-
 sub save_clusterfw_conf {
     my ($cluster_conf) = @_;
 
     my $raw = '';
 
     my $options = $cluster_conf->{options};
-    if (scalar(keys %$options)) {
-       $raw .= "[OPTIONS]\n\n";
-       foreach my $opt (keys %$options) {
-           $raw .= "$opt: $options->{$opt}\n";
+    $raw .= &$format_options($options) if 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";
     }
 
-    # fixme: save ipset
-
     my $rules = $cluster_conf->{rules};
     if (scalar(@$rules)) {
        $raw .= "[RULES]\n\n";
-       $raw .= &$rules_to_conf($rules, 1);
+       $raw .= &$format_rules($rules, 1);
        $raw .= "\n";
     }
 
     foreach my $group (sort keys %{$cluster_conf->{groups}}) {
        my $rules = $cluster_conf->{groups}->{$group};
-       $raw .= "[group $group]\n\n";
-       $raw .= &$rules_to_conf($rules, 0);
+       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";
     }
 
@@ -2134,21 +2518,41 @@ sub save_clusterfw_conf {
 sub load_hostfw_conf {
 
     my $hostfw_conf = {};
-    my $filename = "/etc/pve/local/host.fw";
-    if (my $fh = IO::File->new($filename, O_RDONLY)) {
-       $hostfw_conf = parse_host_fw_rules($filename, $fh);
+    if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
+       $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
     }
     return $hostfw_conf;
 }
 
+sub save_hostfw_conf {
+    my ($hostfw_conf) = @_;
+
+    my $raw = '';
+
+    my $options = $hostfw_conf->{options};
+    $raw .= &$format_options($options) if scalar(keys %$options);
+
+    my $rules = $hostfw_conf->{rules};
+    if (scalar(@$rules)) {
+       $raw .= "[RULES]\n\n";
+       $raw .= &$format_rules($rules, 1);
+       $raw .= "\n";
+    }
+
+    PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
+}
+
 sub compile {
+    my ($cluster_conf, $hostfw_conf) = @_;
+
+    $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
+    $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
+
     my $vmdata = read_local_vm_config();
     my $vmfw_configs = read_vm_firewall_configs($vmdata);
 
     my $routing_table = read_proc_net_route();
 
-    my $cluster_conf = load_clusterfw_conf();
-
     my $ipset_ruleset = {};
     generate_ipset_chains($ipset_ruleset, $cluster_conf);
 
@@ -2159,7 +2563,6 @@ sub compile {
 
     ruleset_create_chain($ruleset, "PVEFW-FORWARD");
 
-    my $hostfw_conf = load_hostfw_conf();
     my $hostfw_options = $hostfw_conf->{options} || {};
 
     generate_std_chains($ruleset, $hostfw_options);
@@ -2189,9 +2592,9 @@ sub compile {
            generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
 
            my $macaddr = $net->{macaddr};
-           generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $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, $iface, $netid, $macaddr, 
+           generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
                                         $vmfw_conf, $vmid, $bridge, 'OUT');
        }
     }
@@ -2206,8 +2609,8 @@ sub compile {
 
        if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
            my $ip = $conf->{ip_address}->{value};
-           generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
-           generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
+           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');
        }
 
        if ($conf->{netif} && $conf->{netif}->{value}) {
@@ -2219,14 +2622,14 @@ sub compile {
                    warn "no bridge device for CT $vmid iface '$netid'\n";
                    next; # fixme?
                }
-               
+
                generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
 
                my $macaddr = $d->{mac};
                my $iface = $d->{host_ifname};
-               generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $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, $iface, $netid, $macaddr, 
+               generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
                                             $vmfw_conf, $vmid, $bridge, 'OUT');
            }
        }
@@ -2248,14 +2651,14 @@ sub compile {
     ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
 
     # disable interbridge routing
-    ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop"); 
+    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_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");
 
-    return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
+    return ($ruleset, $ipset_ruleset);
 }
 
 sub get_ruleset_status {
@@ -2292,7 +2695,7 @@ sub get_ruleset_status {
            print "delete $chain ($sig)\n" if $verbose;
        }
     }
-    
+
     return $statushash;
 }
 
@@ -2307,7 +2710,7 @@ sub get_ruleset_cmdlist {
     my ($ruleset, $verbose) = @_;
 
     my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
+
     my ($active_chains, $hooks) = iptables_get_chains();
     my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
 
@@ -2369,9 +2772,18 @@ sub get_ipset_cmdlist {
 
     my $cmdlist = "";
 
+    my $delete_cmdlist = "";
+
     my $active_chains = ipset_get_chains();
     my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
 
+    # 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) {
        my $stat = $statushash->{$chain};
        die "internal error" if !$stat;
@@ -2380,7 +2792,7 @@ sub get_ipset_cmdlist {
            foreach my $cmd (@{$ruleset->{$chain}}) {
                $cmdlist .= "$cmd\n";
            }
-        }
+       }
 
        if ($stat->{action} eq 'update') {
            my $chain_swap = $chain."_swap";
@@ -2388,25 +2800,24 @@ sub get_ipset_cmdlist {
            foreach my $cmd (@{$ruleset->{$chain}}) {
                $cmd =~ s/$chain/$chain_swap/;
                $cmdlist .= "$cmd\n";
-
            }
            $cmdlist .= "swap $chain_swap $chain\n";
            $cmdlist .= "flush $chain_swap\n";
            $cmdlist .= "destroy $chain_swap\n";
-        }
+       }
 
     }
 
     foreach my $chain (keys %$statushash) {
        next if $statushash->{$chain}->{action} ne 'delete';
 
-       $cmdlist .= "flush $chain\n";
-       $cmdlist .= "destroy $chain\n";
+       $delete_cmdlist .= "flush $chain\n";
+       $delete_cmdlist .= "destroy $chain\n";
     }
 
-    my $changes = $cmdlist ? 1 : 0;
+    my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
 
-    return wantarray ? ($cmdlist, $changes) : $cmdlist;
+    return ($cmdlist, $delete_cmdlist, $changes);
 }
 
 sub apply_ruleset {
@@ -2416,21 +2827,35 @@ sub apply_ruleset {
 
     update_nf_conntrack_max($hostfw_conf);
 
-    my $ipsetcmdlist = get_ipset_cmdlist($ipset_ruleset, $verbose);
+    update_nf_conntrack_tcp_timeout_established($hostfw_conf);
 
-    my $cmdlist = get_ruleset_cmdlist($ruleset, $verbose);
+    my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
+       get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
 
-    print $ipsetcmdlist if $verbose;
+    my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
 
-    print $cmdlist if $verbose;
+    if ($verbose) {
+       if ($ipset_changes) {
+           print "ipset changes:\n";
+           print $ipset_create_cmdlist if $ipset_create_cmdlist;
+           print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
+       }
 
-    ipset_restore_cmdlist($ipsetcmdlist);
+       if ($changes) {
+           print "iptables changes:\n";
+           print $cmdlist;
+       }
+    }
+
+    ipset_restore_cmdlist($ipset_create_cmdlist);
 
     iptables_restore_cmdlist($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_chains = iptables_get_chains();
-    my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
+    my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
 
     my $errors;
     foreach my $chain (sort keys %$ruleset) {
@@ -2468,6 +2893,16 @@ sub update_nf_conntrack_max {
     }
 }
 
+sub update_nf_conntrack_tcp_timeout_established {
+    my ($hostfw_conf) = @_;
+
+    my $options = $hostfw_conf->{options} || {};
+
+    my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
+
+    PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
+}
+
 sub remove_pvefw_chains {
 
     my ($chash, $hooks) = iptables_get_chains();
@@ -2478,7 +2913,7 @@ sub remove_pvefw_chains {
            $cmdlist .= "-D $h -j PVEFW-$h\n";
        }
     }
+
     foreach my $chain (keys %$chash) {
        $cmdlist .= "-F $chain\n";
     }
@@ -2495,9 +2930,25 @@ sub update {
     my ($start, $verbose) = @_;
 
     my $code = sub {
+
+       my $cluster_conf = load_clusterfw_conf();
+       my $cluster_options = $cluster_conf->{options};
+
+       my $enable = $cluster_options->{enable};
+
        my $status = read_pvefw_status();
 
-       my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile();
+       die "Firewall is disabled - cannot start\n" if !$enable && $start;
+
+       if (!$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);
 
        if ($start || $status eq 'active') {