9 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::JSONSchema
qw(get_standard_option);
13 use PVE
::Tools
qw($IPV4RE);
18 use PVE
::Tools
qw(run_command lock_file);
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
24 # dynamically include PVE::QemuServer and PVE::OpenVZ
25 # to avoid dependency problems
28 require PVE
::QemuServer
;
29 $have_qemu_server = 1;
35 $have_pve_manager = 1;
38 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
39 sub pve_verify_ipv4_or_cidr
{
40 my ($cidr, $noerr) = @_;
42 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$! && (!$1 || (($2 > 7) && ($2 <= 32)))) {
45 return undef if $noerr;
46 die "value does not look like a valid IP address or CIDR network\n";
50 my $feature_ipset_nomatch = 0;
52 my (undef, undef, $release) = POSIX
::uname
();
53 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
54 my ($major, $minor) = ($1, $2);
55 $feature_ipset_nomatch = 1 if ($major > 3) ||
56 ($major == 3 && $minor >= 7);
63 my $nodename = PVE
::INotify
::nodename
();
65 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
66 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
68 my $default_log_level = 'info';
70 my $log_level_hash = {
81 # imported/converted from: /usr/share/shorewall/macro.*
85 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
86 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
89 "Auth (identd) traffic",
90 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
93 "Border Gateway Protocol traffic",
94 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
97 "BitTorrent traffic for BitTorrent 3.1 and earlier",
98 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
99 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
102 "BitTorrent traffic for BitTorrent 3.2 and later",
103 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
104 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
107 "Concurrent Versions System pserver traffic",
108 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
111 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
112 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
113 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
114 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
117 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
118 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
119 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
122 "Distributed Checksum Clearinghouse spam filtering mechanism",
123 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
126 "Forwarded DHCP traffic (bidirectional)",
127 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
128 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
131 "Domain Name System traffic (upd and tcp)",
132 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
133 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
136 "Distributed Compiler service",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
140 "File Transfer Protocol",
141 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
144 "Finger protocol (RFC 742)",
145 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
148 "GNUnet secure peer-to-peer networking traffic",
149 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
150 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
151 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
152 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
155 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
156 { action
=> 'PARAM', proto
=> '47' },
157 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
160 "Git distributed revision control traffic",
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
164 "OpenPGP HTTP keyserver protocol traffic",
165 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
168 "Hypertext Transfer Protocol (WWW)",
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
172 "Hypertext Transfer Protocol (WWW) over SSL",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
176 "Internet Cache Protocol V2 (Squid) traffic",
177 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
180 "AOL Instant Messenger traffic",
181 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
184 "Internet Message Access Protocol",
185 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
188 "Internet Message Access Protocol over SSL",
189 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
192 "IPIP capsulation traffic (bidirectional)",
193 { action
=> 'PARAM', proto
=> '94' },
194 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
197 "IPsec traffic (bidirectional)",
198 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
199 { action
=> 'PARAM', proto
=> '50' },
200 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
201 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
204 "IPsec authentication (AH) traffic (bidirectional)",
205 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
206 { action
=> 'PARAM', proto
=> '51' },
207 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
208 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
211 "IPsec traffic and Nat-Traversal (bidirectional)",
212 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
213 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
214 { action
=> 'PARAM', proto
=> '50' },
215 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
216 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
217 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
220 "Internet Relay Chat traffic",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
224 "HP Jetdirect printing",
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
228 "Layer 2 Tunneling Protocol traffic",
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
230 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
233 "Lightweight Directory Access Protocol traffic",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
237 "Secure Lightweight Directory Access Protocol traffic",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
241 "Microsoft Notification Protocol",
242 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
245 "Microsoft SQL Server",
246 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
249 "Mail traffic (SMTP, SMTPS, Submission)",
250 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
251 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
252 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
255 "Munin networked resource monitoring traffic",
256 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
260 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
263 "NNTP traffic (Usenet).",
264 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
267 "Encrypted NNTP traffic (Usenet)",
268 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
271 "Network Time Protocol (ntpd)",
272 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
275 "Bi-directional NTP (for NTP peers)",
276 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
277 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
280 "OSPF multicast traffic",
281 { action
=> 'PARAM', proto
=> '89' },
285 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
288 "Symantec PCAnywere (tm)",
289 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
290 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
294 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
297 "Encrypted POP3 traffic",
298 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
301 "Point-to-Point Tunneling Protocol",
302 { action
=> 'PARAM', proto
=> '47' },
303 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
304 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
308 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
315 "Line Printer protocol printing",
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
319 "Microsoft Remote Desktop Protocol traffic",
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
323 "Routing Information Protocol (bidirectional)",
324 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
325 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
328 "BIND remote management protocol",
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
332 "Razor Antispam System",
333 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
336 "Remote time retrieval (rdate)",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
341 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
344 "SANE network scanning",
345 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
348 "Microsoft SMB traffic",
349 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
350 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
351 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
352 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
355 "Microsoft SMB traffic (bidirectional)",
356 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
357 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
358 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
359 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
360 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
361 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
362 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
363 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
366 "Samba Web Administration Tool",
367 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
370 "Simple Mail Transfer Protocol",
371 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
374 "Encrypted Simple Mail Transfer Protocol",
375 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
378 "Simple Network Management Protocol",
379 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
383 "Spam Assassin SPAMD traffic",
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
387 "Secure shell traffic",
388 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
391 "Subversion server (svnserve)",
392 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
395 "SixXS IPv6 Deployment and Tunnel Broker",
396 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
397 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
398 { action
=> 'PARAM', proto
=> '41' },
399 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
402 "Squid web proxy traffic",
403 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
406 "Mail message submission traffic",
407 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
410 "Syslog protocol (RFC 5424) traffic",
411 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
415 "Trivial File Transfer Protocol traffic",
416 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
420 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
424 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
427 "RFC 868 Time protocol",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
431 "Traceroute (for up to 30 hops) traffic",
432 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
433 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
436 "VNC traffic for VNC display's 0 - 9",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
440 "VNC traffic from Vncservers to Vncviewers in listen mode",
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
444 "WWW traffic (HTTP and HTTPS)",
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
449 "Web Cache/Proxy traffic (port 8080)",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
457 "Whois (nicname, RFC 3912) traffic",
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
462 my $pve_fw_parsed_macros;
463 my $pve_fw_macro_descr;
464 my $pve_fw_preferred_macro_names = {};
466 my $pve_std_chains = {
467 'PVEFW-SET-ACCEPT-MARK' => [
468 "-j MARK --set-mark 1",
470 'PVEFW-DropBroadcast' => [
471 # same as shorewall 'Broadcast'
472 # simply DROP BROADCAST/MULTICAST/ANYCAST
473 # we can use this to reduce logging
474 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
475 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
476 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
477 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
480 # same as shorewall 'reject'
481 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
482 { action
=> 'DROP', source
=> '224.0.0.0/4' },
483 { action
=> 'DROP', proto
=> 'icmp' },
484 "-p tcp -j REJECT --reject-with tcp-reset",
485 "-p udp -j REJECT --reject-with icmp-port-unreachable",
486 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
487 "-j REJECT --reject-with icmp-host-prohibited",
490 # same as shorewall 'Drop', which is equal to DROP,
491 # but REJECT/DROP some packages to reduce logging,
492 # and ACCEPT critical ICMP types
493 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
494 # we are not interested in BROADCAST/MULTICAST/ANYCAST
495 { action
=> 'PVEFW-DropBroadcast' },
496 # ACCEPT critical ICMP types
497 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
498 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
499 # Drop packets with INVALID state
500 "-m conntrack --ctstate INVALID -j DROP",
501 # Drop Microsoft SMB noise
502 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
503 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
504 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
505 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
506 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
507 # Drop new/NotSyn traffic so that it doesn't get logged
508 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
510 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
513 # same as shorewall 'Reject', which is equal to Reject,
514 # but REJECT/DROP some packages to reduce logging,
515 # and ACCEPT critical ICMP types
516 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
517 # we are not interested in BROADCAST/MULTICAST/ANYCAST
518 { action
=> 'PVEFW-DropBroadcast' },
519 # ACCEPT critical ICMP types
520 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
521 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
522 # Drop packets with INVALID state
523 "-m conntrack --ctstate INVALID -j DROP",
524 # Drop Microsoft SMB noise
525 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
526 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
527 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
528 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
529 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
530 # Drop new/NotSyn traffic so that it doesn't get logged
531 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
533 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
535 'PVEFW-tcpflags' => [
536 # same as shorewall tcpflags action.
537 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
538 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
539 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
540 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
541 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
542 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
545 # same as shorewall smurfs action
546 # Filter packets for smurfs (packets with a broadcast address as the source).
547 "-s 0.0.0.0/32 -j RETURN",
548 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
549 "-s 224.0.0.0/4 -g PVEFW-smurflog",
553 # iptables -p icmp -h
554 my $icmp_type_names = {
557 'destination-unreachable' => 1,
558 'network-unreachable' => 1,
559 'host-unreachable' => 1,
560 'protocol-unreachable' => 1,
561 'port-unreachable' => 1,
562 'fragmentation-needed' => 1,
563 'source-route-failed' => 1,
564 'network-unknown' => 1,
566 'network-prohibited' => 1,
567 'host-prohibited' => 1,
568 'TOS-network-unreachable' => 1,
569 'TOS-host-unreachable' => 1,
570 'communication-prohibited' => 1,
571 'host-precedence-violation' => 1,
572 'precedence-cutoff' => 1,
573 'source-quench' => 1,
575 'network-redirect' => 1,
576 'host-redirect' => 1,
577 'TOS-network-redirect' => 1,
578 'TOS-host-redirect' => 1,
580 'router-advertisement' => 1,
581 'router-solicitation' => 1,
582 'time-exceeded' => 1,
583 'ttl-zero-during-transit' => 1,
584 'ttl-zero-during-reassembly' => 1,
585 'parameter-problem' => 1,
586 'ip-header-bad' => 1,
587 'required-option-missing' => 1,
588 'timestamp-request' => 1,
589 'timestamp-reply' => 1,
590 'address-mask-request' => 1,
591 'address-mask-reply' => 1,
594 sub init_firewall_macros
{
596 $pve_fw_parsed_macros = {};
598 foreach my $k (keys %$pve_fw_macros) {
599 my $lc_name = lc($k);
600 my $macro = $pve_fw_macros->{$k};
601 if (!ref($macro->[0])) {
602 $pve_fw_macro_descr->{$k} = shift @$macro;
604 $pve_fw_preferred_macro_names->{$lc_name} = $k;
605 $pve_fw_parsed_macros->{$k} = $macro;
609 init_firewall_macros
();
612 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
617 sub get_etc_services
{
619 return $etc_services if $etc_services;
621 my $filename = "/etc/services";
623 my $fh = IO
::File-
>new($filename, O_RDONLY
);
625 warn "unable to read '$filename' - $!\n";
631 while (my $line = <$fh>) {
633 next if $line =~m/^#/;
634 next if ($line =~m/^\s*$/);
636 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
637 $services->{byid
}->{$2}->{name
} = $1;
638 $services->{byid
}->{$2}->{port
} = $2;
639 $services->{byid
}->{$2}->{$3} = 1;
640 $services->{byname
}->{$1} = $services->{byid
}->{$2};
646 $etc_services = $services;
649 return $etc_services;
654 sub get_etc_protocols
{
655 return $etc_protocols if $etc_protocols;
657 my $filename = "/etc/protocols";
659 my $fh = IO
::File-
>new($filename, O_RDONLY
);
661 warn "unable to read '$filename' - $!\n";
667 while (my $line = <$fh>) {
669 next if $line =~m/^#/;
670 next if ($line =~m/^\s*$/);
672 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
673 $protocols->{byid
}->{$2}->{name
} = $1;
674 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
680 $etc_protocols = $protocols;
682 return $etc_protocols;
685 sub parse_address_list
{
688 return if $str !~ m/^(\+)(\S+)$/; # ipset ref
692 foreach my $elem (split(/,/, $str)) {
694 if (!Net
::IP-
>new($elem)) {
695 my $err = Net
::IP
::Error
();
696 die "invalid IP address: $err\n";
698 $iprange = 1 if $elem =~ m/-/;
701 die "you can use a range in a list\n" if $iprange && $count > 1;
704 sub parse_port_name_number_or_range
{
707 my $services = PVE
::Firewall
::get_etc_services
();
711 foreach my $item (split(/,/, $str)) {
713 if ($item =~ m/^(\d+):(\d+)$/) {
714 my ($port1, $port2) = ($1, $2);
715 die "invalid port '$port1'\n" if $port1 > 65535;
716 die "invalid port '$port2'\n" if $port2 > 65535;
717 } elsif ($item =~ m/^(\d+)$/) {
719 die "invalid port '$port'\n" if $port > 65535;
721 if ($icmp_type_names->{$item}) {
724 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
729 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
734 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
735 sub pve_fw_verify_port_spec
{
738 parse_port_name_number_or_range
($portstr);
743 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
744 sub pve_fw_verify_v4addr_spec
{
747 parse_address_list
($list);
752 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
753 sub pve_fw_verify_protocol_spec
{
756 my $protocols = get_etc_protocols
();
758 die "unknown protocol '$proto'\n" if $proto &&
759 !(defined($protocols->{byname
}->{$proto}) ||
760 defined($protocols->{byid
}->{$proto}));
766 # helper function for API
768 my $rule_properties = {
770 description
=> "Update rule at position <pos>.",
784 enum
=> ['in', 'out', 'group'],
789 enum
=> ['ACCEPT', 'DROP', 'REJECT'],
796 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
798 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
802 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
806 type
=> 'string', format
=> 'pve-fw-protocol-spec',
814 type
=> 'string', format
=> 'pve-fw-port-spec',
818 type
=> 'string', format
=> 'pve-fw-port-spec',
827 sub cleanup_fw_rule
{
828 my ($rule, $digest, $pos) = @_;
832 foreach my $k (keys %$rule) {
833 next if !$rule_properties->{$k};
835 next if !defined($v);
837 $r->{digest
} = $digest;
844 sub add_rule_properties
{
845 my ($properties) = @_;
847 foreach my $k (keys %$rule_properties) {
848 my $h = $rule_properties->{$k};
849 # copy data, so that we can modify later without side effects
850 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
856 sub delete_rule_properties
{
857 my ($rule, $delete_str) = @_;
859 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
860 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
861 if !defined($rule_properties->{$opt});
862 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
863 if $opt eq 'type' || $opt eq 'action';
864 delete $rule->{$opt};
870 my $apply_macro = sub {
871 my ($macro_name, $param, $verify) = @_;
873 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
874 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
878 foreach my $templ (@$macro_rules) {
881 foreach my $k (keys %$templ) {
882 my $v = $templ->{$k};
885 $param_used->{$k} = 1;
886 } elsif ($v eq 'DEST') {
888 $param_used->{dest
} = 1;
889 } elsif ($v eq 'SOURCE') {
890 $v = $param->{source
};
891 $param_used->{source
} = 1;
895 my $msg = "missing parameter '$k' in macro '$macro_name'";
896 raise_param_exc
({ macro => $msg }) if $verify;
901 foreach my $k (keys %$param) {
902 next if $k eq 'macro';
903 next if !defined($param->{$k});
904 next if $param_used->{$k};
905 if (defined($rule->{$k})) {
906 if ($rule->{$k} ne $param->{$k}) {
907 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
908 raise_param_exc
({ $k => $msg }) if $verify;
912 $rule->{$k} = $param->{$k};
922 my ($rule, $allow_groups) = @_;
924 my $type = $rule->{type
};
926 raise_param_exc
({ type
=> "missing property"}) if !$type;
927 raise_param_exc
({ action
=> "missing property"}) if !$rule->{action
};
929 if ($type eq 'in' || $type eq 'out') {
930 raise_param_exc
({ action
=> "unknown action '$rule->{action}'"})
931 if $rule->{action
} !~ m/^(ACCEPT|DROP|REJECT)$/;
932 } elsif ($type eq 'group') {
933 raise_param_exc
({ type
=> "security groups not allowed"})
935 raise_param_exc
({ action
=> "invalid characters in security group name"})
936 if $rule->{action
} !~ m/^[A-Za-z0-9_\-]+$/;
938 raise_param_exc
({ type
=> "unknown rule type '$type'"});
941 # fixme: verify $rule->{iface}?
943 if ($rule->{macro}) {
944 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
945 raise_param_exc
({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
946 $rule->{macro} = $preferred_name;
949 if ($rule->{dport
}) {
950 eval { parse_port_name_number_or_range
($rule->{dport
}); };
951 raise_param_exc
({ dport
=> $@ }) if $@;
954 if ($rule->{sport
}) {
955 eval { parse_port_name_number_or_range
($rule->{sport
}); };
956 raise_param_exc
({ sport
=> $@ }) if $@;
959 if ($rule->{source
}) {
960 eval { parse_address_list
($rule->{source
}); };
961 raise_param_exc
({ source
=> $@ }) if $@;
965 eval { parse_address_list
($rule->{dest
}); };
966 raise_param_exc
({ dest
=> $@ }) if $@;
969 if ($rule->{macro}) {
970 &$apply_macro($rule->{macro}, $rule, 1);
977 my ($rule, $param) = @_;
979 foreach my $k (keys %$rule_properties) {
980 if (defined(my $v = $param->{$k})) {
981 if ($v eq '' || $v eq '-') {
997 my $bridge_firewall_enabled = 0;
999 sub enable_bridge_firewall
{
1001 return if $bridge_firewall_enabled; # only once
1003 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1004 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1006 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1007 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1009 $bridge_firewall_enabled = 1;
1012 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1014 sub iptables_restore_cmdlist
{
1017 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1020 sub ipset_restore_cmdlist
{
1023 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1026 sub iptables_get_chains
{
1030 # check what chains we want to track
1031 my $is_pvefw_chain = sub {
1034 return 1 if $name =~ m/^PVEFW-\S+$/;
1036 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1038 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1040 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1042 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
1043 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1055 return if $line =~ m/^#/;
1056 return if $line =~ m/^\s*$/;
1058 if ($line =~ m/^\*(\S+)$/) {
1063 return if $table ne 'filter';
1065 if ($line =~ m/^:(\S+)\s/) {
1067 return if !&$is_pvefw_chain($chain);
1068 $res->{$chain} = "unknown";
1069 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1070 my ($chain, $sig) = ($1, $2);
1071 return if !&$is_pvefw_chain($chain);
1072 $res->{$chain} = $sig;
1073 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1076 # simply ignore the rest
1081 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1083 return wantarray ?
($res, $hooks) : $res;
1086 sub iptables_chain_digest
{
1088 my $digest = Digest
::SHA-
>new('sha1');
1089 foreach my $rule (@$rules) { # order is important
1090 $digest->add($rule);
1092 return $digest->b64digest;
1095 sub ipset_chain_digest
{
1098 my $digest = Digest
::SHA-
>new('sha1');
1099 foreach my $rule (sort @$rules) { # note: sorted
1100 $digest->add($rule);
1102 return $digest->b64digest;
1105 sub ipset_get_chains
{
1113 return if $line =~ m/^#/;
1114 return if $line =~ m/^\s*$/;
1115 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1117 $line =~ s/\s+$//; # delete trailing white space
1118 push @{$chains->{$chain}}, $line;
1120 # simply ignore the rest
1125 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1127 # compute digest for each chain
1128 foreach my $chain (keys %$chains) {
1129 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1135 sub ruleset_generate_cmdstr
{
1136 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1138 return if defined($rule->{enable
}) && !$rule->{enable
};
1140 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1142 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1143 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1147 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1148 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1150 my $source = $rule->{source
};
1151 my $dest = $rule->{dest
};
1154 if ($source =~ m/^(\+)(\S+)$/) {
1155 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1156 push @cmd, "-m set --match-set PVEFW-$2 src";
1158 } elsif ($source =~ m/\-/){
1159 push @cmd, "-m iprange --src-range $source";
1162 push @cmd, "-s $source";
1167 if ($dest =~ m/^(\+)(\S+)$/) {
1168 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1169 push @cmd, "-m set --match-set PVEFW-$2 dst";
1171 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1172 push @cmd, "-m iprange --dst-range $dest";
1175 push @cmd, "-s $dest";
1179 if ($rule->{proto
}) {
1180 push @cmd, "-p $rule->{proto}";
1183 $multiport++ if $nbdport > 1;
1184 $multiport++ if $nbsport > 1;
1186 push @cmd, "--match multiport" if $multiport;
1188 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1189 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1191 if ($rule->{dport
}) {
1192 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1193 # Note: we use dport to store --icmp-type
1194 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1195 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1198 if ($multiport == 2) {
1199 push @cmd, "--ports $rule->{dport}";
1201 push @cmd, "--dports $rule->{dport}";
1204 push @cmd, "--dport $rule->{dport}";
1209 if ($rule->{sport
}) {
1211 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1213 push @cmd, "--sport $rule->{sport}";
1216 } elsif ($rule->{dport
} || $rule->{sport
}) {
1217 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1218 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1221 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1223 if (my $action = $rule->{action
}) {
1224 $action = $actions->{$action} if defined($actions->{$action});
1225 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1226 push @cmd, $goto ?
"-g $action" : "-j $action";
1229 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1232 sub ruleset_generate_rule
{
1233 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1237 if ($rule->{macro}) {
1238 $rules = &$apply_macro($rule->{macro}, $rule);
1243 foreach my $tmp (@$rules) {
1244 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1245 ruleset_addrule
($ruleset, $chain, $cmdstr);
1250 sub ruleset_generate_rule_insert
{
1251 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1253 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1255 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1256 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1260 sub ruleset_create_chain
{
1261 my ($ruleset, $chain) = @_;
1263 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1264 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1266 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1268 $ruleset->{$chain} = [];
1271 sub ruleset_chain_exist
{
1272 my ($ruleset, $chain) = @_;
1274 return $ruleset->{$chain} ?
1 : undef;
1277 sub ruleset_addrule
{
1278 my ($ruleset, $chain, $rule) = @_;
1280 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1282 push @{$ruleset->{$chain}}, "-A $chain $rule";
1285 sub ruleset_insertrule
{
1286 my ($ruleset, $chain, $rule) = @_;
1288 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1290 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1293 sub get_log_rule_base
{
1294 my ($chain, $vmid, $msg, $loglevel) = @_;
1296 die "internal error - no log level" if !defined($loglevel);
1298 $vmid = 0 if !defined($vmid);
1300 # Note: we use special format for prefix to pass further
1301 # info to log daemon (VMID, LOGVELEL and CHAIN)
1303 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1306 sub ruleset_addlog {
1307 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1309 return if !defined($loglevel);
1311 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1313 $logrule = "$rule $logrule" if defined($rule);
1315 ruleset_addrule($ruleset, $chain, $logrule)
1318 sub generate_bridge_chains {
1319 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1321 my $options = $hostfw_conf->{options} || {};
1323 die "error
: detected direct route to bridge
'$bridge'\n"
1324 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1326 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1327 ruleset_create_chain($ruleset, "$bridge-FW
");
1328 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1329 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1332 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1333 ruleset_create_chain($ruleset, "$bridge-OUT
");
1334 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1335 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1338 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1339 ruleset_create_chain($ruleset, "$bridge-IN
");
1340 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1341 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1342 # accept traffic to unmanaged bridge ports
1343 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1347 sub ruleset_add_chain_policy {
1348 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1350 if ($policy eq 'ACCEPT') {
1352 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1353 { ACCEPT => $accept_action});
1355 } elsif ($policy eq 'DROP') {
1357 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1359 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1361 ruleset_addrule($ruleset, $chain, "-j DROP
");
1362 } elsif ($policy eq 'REJECT') {
1363 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1365 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1367 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1370 die "internal error
: unknown policy
'$policy'";
1374 sub ruleset_create_vm_chain {
1375 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1377 ruleset_create_chain($ruleset, $chain);
1378 my $accept = generate_nfqueue($options);
1380 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1381 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1384 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1385 if ($direction eq 'OUT') {
1386 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1387 proto => 'udp', sport => 68, dport => 67 });
1389 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1390 proto => 'udp', sport => 67, dport => 68 });
1394 if ($options->{tcpflags}) {
1395 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1398 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1399 if ($direction eq 'OUT') {
1400 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1402 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1405 if ($direction eq 'OUT') {
1406 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1407 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1409 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1413 sub ruleset_generate_vm_rules {
1414 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1416 my $lc_direction = lc($direction);
1418 foreach my $rule (@$rules) {
1419 next if $rule->{iface} && $rule->{iface} ne $netid;
1420 next if !$rule->{enable};
1421 if ($rule->{type} eq 'group') {
1422 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1423 if(!ruleset_chain_exist($ruleset, $group_chain)){
1424 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1426 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1427 if ($direction eq 'OUT'){
1428 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1430 my $accept = generate_nfqueue($options);
1431 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1435 next if $rule->{type} ne $lc_direction;
1436 if ($direction eq 'OUT') {
1437 ruleset_generate_rule($ruleset, $chain, $rule,
1438 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1440 my $accept = generate_nfqueue($options);
1441 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1447 sub generate_nfqueue {
1451 if($options->{ips}){
1452 $action = "NFQUEUE
";
1453 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1454 if(defined($3) && defined($1)) {
1455 $action .= " --queue-balance
$1:$3";
1456 }elsif (defined($1)) {
1457 $action .= " --queue-num
$1";
1460 $action .= " --queue-bypass
";
1468 sub ruleset_generate_vm_ipsrules {
1469 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1471 if ($options->{ips} && $direction eq 'IN') {
1472 my $nfqueue = generate_nfqueue($options);
1474 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1475 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1478 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1479 ruleset_create_chain($ruleset, "$bridge-IPS
");
1480 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1483 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1487 sub generate_venet_rules_direction {
1488 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1490 parse_address_list($ip); # make sure we have a valid $ip list
1492 my $lc_direction = lc($direction);
1494 my $rules = $vmfw_conf->{rules};
1496 my $options = $vmfw_conf->{options};
1497 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1499 my $chain = "venet0-
$vmid-$direction";
1501 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1503 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1508 if ($direction eq 'OUT') {
1509 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1511 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1514 my $accept = generate_nfqueue($options);
1515 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1516 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1518 # plug into FORWARD, INPUT and OUTPUT chain
1519 if ($direction eq 'OUT') {
1520 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1523 iface_in => 'venet0'});
1525 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1528 iface_in => 'venet0'});
1530 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1533 iface_out => 'venet0'});
1535 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1538 iface_out => 'venet0'});
1542 sub generate_tap_rules_direction {
1543 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1545 my $lc_direction = lc($direction);
1547 my $rules = $vmfw_conf->{rules};
1549 my $options = $vmfw_conf->{options};
1550 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1552 my $tapchain = "$iface-$direction";
1554 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1556 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1558 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1563 if ($direction eq 'OUT') {
1564 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1566 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1569 my $accept = generate_nfqueue($options);
1570 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1571 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1573 # plug the tap chain to bridge chain
1574 if ($direction eq 'IN') {
1575 ruleset_insertrule($ruleset, "$bridge-IN
",
1576 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1578 ruleset_insertrule($ruleset, "$bridge-OUT
",
1579 "-m physdev
--physdev-in
$iface -j
$tapchain");
1583 sub enable_host_firewall {
1584 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1586 # fixme: allow security groups
1588 my $options = $hostfw_conf->{options};
1589 my $rules = $hostfw_conf->{rules};
1591 # host inbound firewall
1592 my $chain = "PVEFW-HOST-IN
";
1593 ruleset_create_chain($ruleset, $chain);
1595 my $loglevel = get_option_log_level($options, "log_level_in
");
1597 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1598 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1601 if ($options->{tcpflags}) {
1602 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1605 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1606 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1607 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1608 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1609 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1610 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1612 # we use RETURN because we need to check also tap rules
1613 my $accept_action = 'RETURN';
1615 foreach my $rule (@$rules) {
1616 next if $rule->{type} ne 'in';
1617 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1620 # implement input policy
1621 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1622 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1624 # host outbound firewall
1625 $chain = "PVEFW-HOST-OUT
";
1626 ruleset_create_chain($ruleset, $chain);
1628 $loglevel = get_option_log_level($options, "log_level_out
");
1630 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1631 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1632 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1633 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1634 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1635 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1637 # we use RETURN because we may want to check other thigs later
1638 $accept_action = 'RETURN';
1640 foreach my $rule (@$rules) {
1641 next if $rule->{type} ne 'out';
1642 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1645 # implement output policy
1646 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1647 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1649 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1650 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1653 sub generate_group_rules {
1654 my ($ruleset, $cluster_conf, $group) = @_;
1655 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1657 my $rules = $cluster_conf->{groups}->{$group};
1659 my $chain = "GROUP-
${group
}-IN
";
1661 ruleset_create_chain($ruleset, $chain);
1662 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1664 foreach my $rule (@$rules) {
1665 next if $rule->{type} ne 'in';
1666 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1669 $chain = "GROUP-
${group
}-OUT
";
1671 ruleset_create_chain($ruleset, $chain);
1672 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1674 foreach my $rule (@$rules) {
1675 next if $rule->{type} ne 'out';
1676 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1677 # check also other tap rules later
1678 ruleset_generate_rule($ruleset, $chain, $rule,
1679 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1684 my $valid_netdev_names = {};
1685 for (my $i = 0; $i < $MAX_NETS; $i++) {
1686 $valid_netdev_names->{"net
$i"} = 1;
1690 my ($line, $need_iface, $allow_groups) = @_;
1692 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1694 # we can add single line comments to the end of the rule
1695 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1697 # we can disable a rule when prefixed with '|'
1700 $enable = 0 if $line =~ s/^\|//;
1702 my @data = split(/\s+/, $line);
1703 my $expected_elements = $need_iface ? 8 : 7;
1705 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1708 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1710 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1713 die "incomplete rule
\n" if ! ($type && $action);
1719 if ($type eq 'in' || $type eq 'out') {
1720 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1722 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1724 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1725 die "unknown
macro '$1'\n" if !$preferred_name;
1726 $macro = $preferred_name;
1728 die "unknown action
'$action'\n";
1730 } elsif ($type eq 'group') {
1731 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1732 die "groups disabled
\n" if !$allow_groups;
1734 die "invalid characters
in group name
\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1736 die "unknown rule type
'$type'\n";
1740 $iface = undef if $iface && $iface eq '-';
1743 $proto = undef if $proto && $proto eq '-';
1744 pve_fw_verify_protocol_spec($proto) if $proto;
1746 $source = undef if $source && $source eq '-';
1747 $dest = undef if $dest && $dest eq '-';
1749 $dport = undef if $dport && $dport eq '-';
1750 $sport = undef if $sport && $sport eq '-';
1752 parse_port_name_number_or_range($dport) if defined($dport);
1753 parse_port_name_number_or_range($sport) if defined($sport);
1755 parse_address_list($source) if $source;
1756 parse_address_list($dest) if $dest;
1761 comment => $comment,
1773 sub parse_vmfw_option {
1778 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1780 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1783 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1785 $value = $2 ? lc($3) : '';
1786 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1789 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1794 die "can
't parse option '$line'\n"
1797 return ($opt, $value);
1800 sub parse_hostfw_option {
1805 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1807 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1810 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1812 $value = $2 ? lc($3) : '';
1813 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1816 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1821 die "can't parse option
'$line'\n"
1824 return ($opt, $value);
1827 sub parse_clusterfw_option {
1832 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1837 die "can
't parse option '$line'\n"
1840 return ($opt, $value);
1843 sub parse_vm_fw_rules {
1844 my ($filename, $fh) = @_;
1846 my $res = { rules => [], options => {}};
1850 my $digest = Digest::SHA->new('sha1
');
1852 while (defined(my $line = <$fh>)) {
1853 $digest->add($line);
1855 next if $line =~ m/^#/;
1856 next if $line =~ m/^\s*$/;
1858 my $linenr = $fh->input_line_number();
1859 my $prefix = "$filename (line $linenr)";
1861 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1863 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1867 warn "$prefix: skip line - no section";
1871 next if !$res->{$section}; # skip undefined section
1873 if ($section eq 'options
') {
1875 my ($opt, $value) = parse_vmfw_option($line);
1876 $res->{options}->{$opt} = $value;
1878 warn "$prefix: $@" if $@;
1883 eval { $rule = parse_fw_rule($line, 1, 1); };
1885 warn "$prefix: $err";
1889 push @{$res->{$section}}, $rule;
1892 $res->{digest} = $digest->b64digest;
1897 sub parse_host_fw_rules {
1898 my ($filename, $fh) = @_;
1900 my $res = { rules => [], options => {}};
1904 my $digest = Digest::SHA->new('sha1
');
1906 while (defined(my $line = <$fh>)) {
1907 $digest->add($line);
1909 next if $line =~ m/^#/;
1910 next if $line =~ m/^\s*$/;
1912 my $linenr = $fh->input_line_number();
1913 my $prefix = "$filename (line $linenr)";
1915 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1917 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1921 warn "$prefix: skip line - no section";
1925 next if !$res->{$section}; # skip undefined section
1927 if ($section eq 'options
') {
1929 my ($opt, $value) = parse_hostfw_option($line);
1930 $res->{options}->{$opt} = $value;
1932 warn "$prefix: $@" if $@;
1937 eval { $rule = parse_fw_rule($line, 1, 1); };
1939 warn "$prefix: $err";
1943 push @{$res->{$section}}, $rule;
1946 $res->{digest} = $digest->b64digest;
1951 sub parse_cluster_fw_rules {
1952 my ($filename, $fh) = @_;
1957 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
1959 my $digest = Digest::SHA->new('sha1
');
1961 while (defined(my $line = <$fh>)) {
1962 $digest->add($line);
1964 next if $line =~ m/^#/;
1965 next if $line =~ m/^\s*$/;
1967 my $linenr = $fh->input_line_number();
1968 my $prefix = "$filename (line $linenr)";
1970 if ($line =~ m/^\[options\]$/i) {
1971 $section = 'options
';
1975 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1976 $section = 'groups
';
1981 if ($line =~ m/^\[rules\]$/i) {
1986 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
1993 warn "$prefix: skip line - no section\n";
1997 if ($section eq 'options
') {
1999 my ($opt, $value) = parse_clusterfw_option($line);
2000 $res->{options}->{$opt} = $value;
2002 warn "$prefix: $@" if $@;
2003 } elsif ($section eq 'rules
') {
2005 eval { $rule = parse_fw_rule($line, 1, 1); };
2007 warn "$prefix: $err";
2010 push @{$res->{$section}}, $rule;
2011 } elsif ($section eq 'groups
') {
2013 eval { $rule = parse_fw_rule($line, 0, 0); };
2015 warn "$prefix: $err";
2018 push @{$res->{$section}->{$group}}, $rule;
2019 } elsif ($section eq 'ipset
') {
2020 # we can add single line comments to the end of the rule
2021 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2023 $line =~ m/^(\!)?\s*((?:\d+)\.(?:\d+)\.(?:\d+)\.(?:\d+))(?:\/(\d+))?\s*$/;
2027 $cidr .= "/$3" if defined($3) && $3 != 32;
2029 if (!Net::IP->new($cidr)) {
2030 my $err = Net::IP::Error();
2031 warn "$prefix: $cidr - $err\n";
2035 my $entry = { cidr => $cidr };
2036 $entry->{nomatch} = 1 if $nomatch;
2037 $entry->{comment} = $comment if $comment;
2039 push @{$res->{$section}->{$group}}, $entry;
2043 $res->{digest} = $digest->b64digest;
2048 my ($code, @param) = @_;
2052 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2059 sub read_local_vm_config {
2064 my $vmdata = { openvz => $openvz, qemu => $qemu };
2066 my $vmlist = PVE::Cluster::get_vmlist();
2067 return $vmdata if !$vmlist || !$vmlist->{ids};
2068 my $ids = $vmlist->{ids};
2070 foreach my $vmid (keys %$ids) {
2071 next if !$vmid; # skip VE0
2072 my $d = $ids->{$vmid};
2073 next if !$d->{node} || $d->{node} ne $nodename;
2074 next if !$d->{type};
2075 if ($d->{type} eq 'openvz
') {
2076 if ($have_pve_manager) {
2077 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2078 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2079 $openvz->{$vmid} = $conf;
2082 } elsif ($d->{type} eq 'qemu
') {
2083 if ($have_qemu_server) {
2084 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2085 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2086 $qemu->{$vmid} = $conf;
2095 sub load_vmfw_conf {
2100 my $filename = "/etc/pve/firewall/$vmid.fw";
2101 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2102 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2108 my $format_rules = sub {
2109 my ($rules, $need_iface) = @_;
2113 foreach my $rule (@$rules) {
2114 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
') {
2115 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2116 $raw .= uc($rule->{type});
2117 if ($rule->{macro}) {
2118 $raw .= " $rule->{macro}($rule->{action})";
2120 $raw .= " " . $rule->{action};
2122 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2123 $raw .= " " . ($rule->{source} || '-');
2124 $raw .= " " . ($rule->{dest} || '-');
2125 $raw .= " " . ($rule->{proto} || '-');
2126 $raw .= " " . ($rule->{dport} || '-');
2127 $raw .= " " . ($rule->{sport} || '-');
2128 $raw .= " # " . encode('utf8
', $rule->{comment})
2129 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2132 die "implement me '$rule->{type
}'";
2139 my $format_options = sub {
2144 $raw .= "[OPTIONS]\n\n";
2145 foreach my $opt (keys %$options) {
2146 $raw .= "$opt: $options->{$opt}\n";
2153 my $format_ipset = sub {
2159 foreach my $entry (@$options) {
2160 $nethash->{$entry->{cidr}} = $entry;
2163 foreach my $cidr (sort keys %$nethash) {
2164 my $entry = $nethash->{$cidr};
2165 my $line = $entry->{nomatch} ? '!' : '';
2166 $line .= $entry->{cidr};
2167 $line .= " # " . encode('utf8
', $entry->{comment})
2168 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2175 sub save_vmfw_conf {
2176 my ($vmid, $vmfw_conf) = @_;
2180 my $options = $vmfw_conf->{options};
2181 $raw .= &$format_options($options) if scalar(keys %$options);
2183 my $rules = $vmfw_conf->{rules};
2184 if (scalar(@$rules)) {
2185 $raw .= "[RULES]\n\n";
2186 $raw .= &$format_rules($rules, 1);
2190 my $filename = "/etc/pve/firewall/$vmid.fw";
2191 PVE::Tools::file_set_contents($filename, $raw);
2194 sub read_vm_firewall_configs {
2196 my $vmfw_configs = {};
2198 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2199 my $vmfw_conf = load_vmfw_conf($vmid);
2200 next if !$vmfw_conf->{options}; # skip if file does not exists
2201 $vmfw_configs->{$vmid} = $vmfw_conf;
2204 return $vmfw_configs;
2207 sub get_option_log_level {
2208 my ($options, $k) = @_;
2210 my $v = $options->{$k};
2211 $v = $default_log_level if !defined($v);
2213 return undef if $v eq '' || $v eq 'nolog
';
2215 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2217 return $v if ($v >= 0) && ($v <= 7);
2219 warn "unknown log level ($k = '$v')\n";
2224 sub generate_std_chains {
2225 my ($ruleset, $options) = @_;
2227 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2229 # same as shorewall smurflog.
2230 my $chain = 'PVEFW-smurflog
';
2232 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2233 push @{$pve_std_chains->{$chain}}, "-j DROP";
2235 # same as shorewall logflags action.
2236 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2237 $chain = 'PVEFW-logflags
';
2238 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2239 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2240 push @{$pve_std_chains->{$chain}}, "-j DROP";
2242 foreach my $chain (keys %$pve_std_chains) {
2243 ruleset_create_chain($ruleset, $chain);
2244 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2246 ruleset_generate_rule($ruleset, $chain, $rule);
2248 ruleset_addrule($ruleset, $chain, $rule);
2254 sub generate_ipset_chains {
2255 my ($ipset_ruleset, $fw_conf) = @_;
2257 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2258 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2262 sub generate_ipset {
2263 my ($ipset_ruleset, $name, $options) = @_;
2265 my $hashsize = scalar(@$options);
2266 if ($hashsize <= 64) {
2269 $hashsize = round_powerof2($hashsize);
2272 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2274 foreach my $entry (@$options) {
2275 my $cidr = $entry->{cidr};
2276 my $cmd = "add $name $cidr";
2277 if ($entry->{nomatch}) {
2278 if ($feature_ipset_nomatch) {
2279 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2281 warn "ignore !$cidr - nomatch not supported by kernel\n";
2284 push @{$ipset_ruleset->{$name}}, $cmd;
2289 sub round_powerof2 {
2293 $int |= $int >> $_ foreach (1,2,4,8,16);
2297 sub save_pvefw_status {
2300 die "unknown status '$status' - internal error"
2301 if $status !~ m/^(stopped|active)$/;
2303 mkdir dirname($pve_fw_status_filename);
2304 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2307 sub read_pvefw_status {
2309 my $status = 'unknown
';
2311 return 'stopped
' if ! -f $pve_fw_status_filename;
2314 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2321 # fixme: move to pve-common PVE::ProcFSTools
2322 sub read_proc_net_route {
2323 my $filename = "/proc/net/route";
2327 my $fh = IO::File->new ($filename, "r");
2328 return $res if !$fh;
2330 my $int_to_quad = sub {
2331 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2334 while (defined(my $line = <$fh>)) {
2335 next if $line =~/^Iface\s+Destination/; # skip head
2336 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2337 push @{$res->{$iface}}, {
2338 dest => &$int_to_quad(hex($dest)),
2339 gateway => &$int_to_quad(hex($gateway)),
2340 mask => &$int_to_quad(hex($mask)),
2349 sub load_clusterfw_conf {
2351 my $cluster_conf = {};
2352 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2353 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2356 return $cluster_conf;
2359 sub save_clusterfw_conf {
2360 my ($cluster_conf) = @_;
2364 my $options = $cluster_conf->{options};
2365 $raw .= &$format_options($options) if scalar(keys %$options);
2367 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2368 $raw .= "[IPSET $ipset]\n\n";
2369 my $options = $cluster_conf->{ipset}->{$ipset};
2370 $raw .= &$format_ipset($options);
2374 my $rules = $cluster_conf->{rules};
2375 if (scalar(@$rules)) {
2376 $raw .= "[RULES]\n\n";
2377 $raw .= &$format_rules($rules, 1);
2381 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2382 my $rules = $cluster_conf->{groups}->{$group};
2383 $raw .= "[group $group]\n\n";
2384 $raw .= &$format_rules($rules, 0);
2388 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2391 sub load_hostfw_conf {
2393 my $hostfw_conf = {};
2394 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2395 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2397 return $hostfw_conf;
2400 sub save_hostfw_conf {
2401 my ($hostfw_conf) = @_;
2405 my $options = $hostfw_conf->{options};
2406 $raw .= &$format_options($options) if scalar(keys %$options);
2408 my $rules = $hostfw_conf->{rules};
2409 if (scalar(@$rules)) {
2410 $raw .= "[RULES]\n\n";
2411 $raw .= &$format_rules($rules, 1);
2415 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2419 my $vmdata = read_local_vm_config();
2420 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2422 my $routing_table = read_proc_net_route();
2424 my $cluster_conf = load_clusterfw_conf();
2426 my $ipset_ruleset = {};
2427 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2431 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2432 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2434 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2436 my $hostfw_conf = load_hostfw_conf();
2437 my $hostfw_options = $hostfw_conf->{options} || {};
2439 generate_std_chains($ruleset, $hostfw_options);
2441 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2443 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2445 # generate firewall rules for QEMU VMs
2446 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2447 my $conf = $vmdata->{qemu}->{$vmid};
2448 my $vmfw_conf = $vmfw_configs->{$vmid};
2449 next if !$vmfw_conf;
2450 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2452 foreach my $netid (keys %$conf) {
2453 next if $netid !~ m/^net(\d+)$/;
2454 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2456 my $iface = "tap${vmid}i$1";
2458 my $bridge = $net->{bridge};
2459 next if !$bridge; # fixme: ?
2461 $bridge .= "v$net->{tag}" if $net->{tag};
2463 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2465 my $macaddr = $net->{macaddr};
2466 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2467 $vmfw_conf, $vmid, $bridge, 'IN
');
2468 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2469 $vmfw_conf, $vmid, $bridge, 'OUT
');
2473 # generate firewall rules for OpenVZ containers
2474 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2475 my $conf = $vmdata->{openvz}->{$vmid};
2477 my $vmfw_conf = $vmfw_configs->{$vmid};
2478 next if !$vmfw_conf;
2479 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2481 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2482 my $ip = $conf->{ip_address}->{value};
2483 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2484 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2487 if ($conf->{netif} && $conf->{netif}->{value}) {
2488 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2489 foreach my $netid (keys %$netif) {
2490 my $d = $netif->{$netid};
2491 my $bridge = $d->{bridge};
2493 warn "no bridge device for CT $vmid iface '$netid'\n";
2497 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2499 my $macaddr = $d->{mac};
2500 my $iface = $d->{host_ifname};
2501 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2502 $vmfw_conf, $vmid, $bridge, 'IN
');
2503 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2504 $vmfw_conf, $vmid, $bridge, 'OUT
');
2509 if($hostfw_options->{optimize}){
2511 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2512 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2513 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2516 # fixme: what log level should we use here?
2517 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2519 # fixme: should we really block inter-bridge traffic?
2521 # always allow traffic from containers?
2522 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2524 # disable interbridge routing
2525 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2526 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2527 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2528 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2529 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2530 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2532 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
2535 sub get_ruleset_status {
2536 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2538 my $statushash = {};
2540 foreach my $chain (sort keys %$ruleset) {
2541 my $sig = &$digest_fn($ruleset->{$chain});
2543 $statushash->{$chain}->{sig} = $sig;
2545 my $oldsig = $active_chains->{$chain};
2546 if (!defined($oldsig)) {
2547 $statushash->{$chain}->{action} = 'create
';
2549 if ($oldsig eq $sig) {
2550 $statushash->{$chain}->{action} = 'exists';
2552 $statushash->{$chain}->{action} = 'update
';
2555 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2556 foreach my $cmd (@{$ruleset->{$chain}}) {
2557 print "\t$cmd\n" if $verbose;
2561 foreach my $chain (sort keys %$active_chains) {
2562 if (!defined($ruleset->{$chain})) {
2563 my $sig = $active_chains->{$chain};
2564 $statushash->{$chain}->{action} = 'delete';
2565 $statushash->{$chain}->{sig} = $sig;
2566 print "delete $chain ($sig)\n" if $verbose;
2573 sub print_sig_rule {
2574 my ($chain, $sig) = @_;
2576 # We just use this to store a SHA1 checksum used to detect changes
2577 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2580 sub get_ruleset_cmdlist {
2581 my ($ruleset, $verbose) = @_;
2583 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2585 my ($active_chains, $hooks) = iptables_get_chains();
2586 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2588 # create missing chains first
2589 foreach my $chain (sort keys %$ruleset) {
2590 my $stat = $statushash->{$chain};
2591 die "internal error" if !$stat;
2592 next if $stat->{action} ne 'create
';
2594 $cmdlist .= ":$chain - [0:0]\n";
2597 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2598 if (!$hooks->{$h}) {
2599 $cmdlist .= "-A $h -j PVEFW-$h\n";
2603 foreach my $chain (sort keys %$ruleset) {
2604 my $stat = $statushash->{$chain};
2605 die "internal error" if !$stat;
2607 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2608 $cmdlist .= "-F $chain\n";
2609 foreach my $cmd (@{$ruleset->{$chain}}) {
2610 $cmdlist .= "$cmd\n";
2612 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2613 } elsif ($stat->{action
} eq 'delete') {
2614 die "internal error"; # this should not happen
2615 } elsif ($stat->{action
} eq 'exists') {
2618 die "internal error - unknown status '$stat->{action}'";
2622 foreach my $chain (keys %$statushash) {
2623 next if $statushash->{$chain}->{action
} ne 'delete';
2624 $cmdlist .= "-F $chain\n";
2626 foreach my $chain (keys %$statushash) {
2627 next if $statushash->{$chain}->{action
} ne 'delete';
2628 next if $chain eq 'PVEFW-INPUT';
2629 next if $chain eq 'PVEFW-OUTPUT';
2630 next if $chain eq 'PVEFW-FORWARD';
2631 $cmdlist .= "-X $chain\n";
2634 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2636 $cmdlist .= "COMMIT\n";
2638 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2641 sub get_ipset_cmdlist
{
2642 my ($ruleset, $verbose) = @_;
2646 my $delete_cmdlist = "";
2648 my $active_chains = ipset_get_chains
();
2649 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2651 foreach my $chain (sort keys %$ruleset) {
2652 my $stat = $statushash->{$chain};
2653 die "internal error" if !$stat;
2655 if ($stat->{action
} eq 'create') {
2656 foreach my $cmd (@{$ruleset->{$chain}}) {
2657 $cmdlist .= "$cmd\n";
2661 if ($stat->{action
} eq 'update') {
2662 my $chain_swap = $chain."_swap";
2664 foreach my $cmd (@{$ruleset->{$chain}}) {
2665 $cmd =~ s/$chain/$chain_swap/;
2666 $cmdlist .= "$cmd\n";
2668 $cmdlist .= "swap $chain_swap $chain\n";
2669 $cmdlist .= "flush $chain_swap\n";
2670 $cmdlist .= "destroy $chain_swap\n";
2675 foreach my $chain (keys %$statushash) {
2676 next if $statushash->{$chain}->{action
} ne 'delete';
2678 $delete_cmdlist .= "flush $chain\n";
2679 $delete_cmdlist .= "destroy $chain\n";
2682 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2684 return ($cmdlist, $delete_cmdlist, $changes);
2688 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2690 enable_bridge_firewall
();
2692 update_nf_conntrack_max
($hostfw_conf);
2694 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2695 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2697 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2700 if ($ipset_changes) {
2701 print "ipset changes:\n";
2702 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2703 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2707 print "iptables changes:\n";
2712 ipset_restore_cmdlist
($ipset_create_cmdlist);
2714 iptables_restore_cmdlist
($cmdlist);
2716 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2718 # test: re-read status and check if everything is up to date
2719 my $active_chains = iptables_get_chains
();
2720 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2723 foreach my $chain (sort keys %$ruleset) {
2724 my $stat = $statushash->{$chain};
2725 if ($stat->{action
} ne 'exists') {
2726 warn "unable to update chain '$chain'\n";
2731 die "unable to apply firewall changes\n" if $errors;
2734 sub update_nf_conntrack_max
{
2735 my ($hostfw_conf) = @_;
2737 my $max = 65536; # reasonable default
2739 my $options = $hostfw_conf->{options
} || {};
2741 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2742 $max = $options->{nf_conntrack_max
};
2743 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2746 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2747 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2749 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2751 if ($current != $max) {
2752 my $hashsize = int($max/4);
2753 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2754 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2758 sub remove_pvefw_chains
{
2760 my ($chash, $hooks) = iptables_get_chains
();
2761 my $cmdlist = "*filter\n";
2763 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2765 $cmdlist .= "-D $h -j PVEFW-$h\n";
2769 foreach my $chain (keys %$chash) {
2770 $cmdlist .= "-F $chain\n";
2773 foreach my $chain (keys %$chash) {
2774 $cmdlist .= "-X $chain\n";
2776 $cmdlist .= "COMMIT\n";
2778 iptables_restore_cmdlist
($cmdlist);
2782 my ($start, $verbose) = @_;
2785 my $status = read_pvefw_status
();
2787 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile
();
2789 if ($start || $status eq 'active') {
2791 save_pvefw_status
('active') if ($status ne 'active');
2793 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2795 print "Firewall not active (status = $status)\n" if $verbose;