]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
762816fff102ff2c17721695f8ee59c10e6295cb
[pve-firewall.git] / src / PVE / Firewall.pm
1 package PVE::Firewall;
2
3 use warnings;
4 use strict;
5 use POSIX;
6 use Data::Dumper;
7 use Digest::SHA;
8 use Socket qw(AF_INET6 inet_ntop inet_pton);
9 use PVE::INotify;
10 use PVE::Exception qw(raise raise_param_exc);
11 use PVE::JSONSchema qw(register_standard_option get_standard_option);
12 use PVE::Cluster;
13 use PVE::ProcFSTools;
14 use PVE::Tools qw($IPV4RE $IPV6RE);
15 use File::Basename;
16 use File::Path;
17 use IO::File;
18 use Net::IP;
19 use PVE::Tools qw(run_command lock_file dir_glob_foreach);
20 use Encode;
21
22 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
23 my $pvefw_conf_dir = "/etc/pve/firewall";
24 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
25
26 # dynamically include PVE::QemuServer and PVE::OpenVZ
27 # to avoid dependency problems
28 my $have_qemu_server;
29 eval {
30 require PVE::QemuServer;
31 $have_qemu_server = 1;
32 };
33
34 my $have_pve_manager;
35 eval {
36 require PVE::OpenVZ;
37 $have_pve_manager = 1;
38 };
39
40 my $pve_fw_status_dir = "/var/lib/pve-firewall";
41
42 mkdir $pve_fw_status_dir; # make sure this exists
43
44 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
45 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
46 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
47
48 my $max_alias_name_length = 64;
49 my $max_ipset_name_length = 64;
50 my $max_group_name_length = 20;
51
52 PVE::JSONSchema::register_format('IPorCIDR', \&pve_verify_ip_or_cidr);
53 sub pve_verify_ip_or_cidr {
54 my ($cidr, $noerr) = @_;
55
56 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
57 return $cidr if Net::IP->new($cidr);
58 return undef if $noerr;
59 die Net::IP::Error() . "\n";
60 }
61 return undef if $noerr;
62 die "value does not look like a valid IP address or CIDR network\n";
63 }
64
65 PVE::JSONSchema::register_format('IPorCIDRorAlias', \&pve_verify_ip_or_cidr_or_alias);
66 sub pve_verify_ip_or_cidr_or_alias {
67 my ($cidr, $noerr) = @_;
68
69 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
70
71 return pve_verify_ip_or_cidr($cidr, $noerr);
72 }
73
74 PVE::JSONSchema::register_standard_option('ipset-name', {
75 description => "IP set name.",
76 type => 'string',
77 pattern => $ipset_name_pattern,
78 minLength => 2,
79 maxLength => $max_ipset_name_length,
80 });
81
82 PVE::JSONSchema::register_standard_option('pve-fw-alias', {
83 description => "Alias name.",
84 type => 'string',
85 pattern => $ip_alias_pattern,
86 minLength => 2,
87 maxLength => $max_alias_name_length,
88 });
89
90 PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
91 description => "Log level.",
92 type => 'string',
93 enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
94 optional => 1,
95 });
96
97 PVE::JSONSchema::register_standard_option('pve-security-group-name', {
98 description => "Security Group name.",
99 type => 'string',
100 pattern => $security_group_name_pattern,
101 minLength => 2,
102 maxLength => $max_group_name_length,
103 });
104
105 my $feature_ipset_nomatch = 0;
106 eval {
107 my (undef, undef, $release) = POSIX::uname();
108 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
109 my ($major, $minor) = ($1, $2);
110 $feature_ipset_nomatch = 1 if ($major > 3) ||
111 ($major == 3 && $minor >= 7);
112 }
113
114 };
115
116 use Data::Dumper;
117
118 my $nodename = PVE::INotify::nodename();
119
120 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
121
122 my $default_log_level = 'nolog'; # avoid logs by default
123
124 my $log_level_hash = {
125 debug => 7,
126 info => 6,
127 notice => 5,
128 warning => 4,
129 err => 3,
130 crit => 2,
131 alert => 1,
132 emerg => 0,
133 };
134
135 # we need to overwrite some macros for ipv6
136 my $pve_ipv6fw_macros = {
137 'Ping' => [
138 { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
139 ],
140 'NeighborDiscovery' => [
141 "IPv6 neighbor solicitation, neighbor and router advertisement",
142 { action => 'PARAM', proto => 'icmpv6', dport => 'router-advertisement' },
143 { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-solicitation' },
144 { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-advertisement' },
145 ],
146 'DHCPv6' => [
147 { action => 'PARAM', proto => 'udp', dport => '546:547', sport => '546:547' },
148 ],
149 'Trcrt' => [
150 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
151 { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
152 ],
153 };
154
155 # imported/converted from: /usr/share/shorewall/macro.*
156 my $pve_fw_macros = {
157 'Amanda' => [
158 "Amanda Backup",
159 { action => 'PARAM', proto => 'udp', dport => '10080' },
160 { action => 'PARAM', proto => 'tcp', dport => '10080' },
161 ],
162 'Auth' => [
163 "Auth (identd) traffic",
164 { action => 'PARAM', proto => 'tcp', dport => '113' },
165 ],
166 'BGP' => [
167 "Border Gateway Protocol traffic",
168 { action => 'PARAM', proto => 'tcp', dport => '179' },
169 ],
170 'BitTorrent' => [
171 "BitTorrent traffic for BitTorrent 3.1 and earlier",
172 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
173 { action => 'PARAM', proto => 'udp', dport => '6881' },
174 ],
175 'BitTorrent32' => [
176 "BitTorrent traffic for BitTorrent 3.2 and later",
177 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
178 { action => 'PARAM', proto => 'udp', dport => '6881' },
179 ],
180 'CVS' => [
181 "Concurrent Versions System pserver traffic",
182 { action => 'PARAM', proto => 'tcp', dport => '2401' },
183 ],
184 'Citrix' => [
185 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
186 { action => 'PARAM', proto => 'tcp', dport => '1494' },
187 { action => 'PARAM', proto => 'udp', dport => '1604' },
188 { action => 'PARAM', proto => 'tcp', dport => '2598' },
189 ],
190 'DAAP' => [
191 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
192 { action => 'PARAM', proto => 'tcp', dport => '3689' },
193 { action => 'PARAM', proto => 'udp', dport => '3689' },
194 ],
195 'DCC' => [
196 "Distributed Checksum Clearinghouse spam filtering mechanism",
197 { action => 'PARAM', proto => 'tcp', dport => '6277' },
198 ],
199 'DHCPfwd' => [
200 "Forwarded DHCP traffic",
201 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
202 ],
203 'DNS' => [
204 "Domain Name System traffic (upd and tcp)",
205 { action => 'PARAM', proto => 'udp', dport => '53' },
206 { action => 'PARAM', proto => 'tcp', dport => '53' },
207 ],
208 'Distcc' => [
209 "Distributed Compiler service",
210 { action => 'PARAM', proto => 'tcp', dport => '3632' },
211 ],
212 'FTP' => [
213 "File Transfer Protocol",
214 { action => 'PARAM', proto => 'tcp', dport => '21' },
215 ],
216 'Finger' => [
217 "Finger protocol (RFC 742)",
218 { action => 'PARAM', proto => 'tcp', dport => '79' },
219 ],
220 'GNUnet' => [
221 "GNUnet secure peer-to-peer networking traffic",
222 { action => 'PARAM', proto => 'tcp', dport => '2086' },
223 { action => 'PARAM', proto => 'udp', dport => '2086' },
224 { action => 'PARAM', proto => 'tcp', dport => '1080' },
225 { action => 'PARAM', proto => 'udp', dport => '1080' },
226 ],
227 'GRE' => [
228 "Generic Routing Encapsulation tunneling protocol",
229 { action => 'PARAM', proto => '47' },
230 ],
231 'Git' => [
232 "Git distributed revision control traffic",
233 { action => 'PARAM', proto => 'tcp', dport => '9418' },
234 ],
235 'HKP' => [
236 "OpenPGP HTTP keyserver protocol traffic",
237 { action => 'PARAM', proto => 'tcp', dport => '11371' },
238 ],
239 'HTTP' => [
240 "Hypertext Transfer Protocol (WWW)",
241 { action => 'PARAM', proto => 'tcp', dport => '80' },
242 ],
243 'HTTPS' => [
244 "Hypertext Transfer Protocol (WWW) over SSL",
245 { action => 'PARAM', proto => 'tcp', dport => '443' },
246 ],
247 'ICPV2' => [
248 "Internet Cache Protocol V2 (Squid) traffic",
249 { action => 'PARAM', proto => 'udp', dport => '3130' },
250 ],
251 'ICQ' => [
252 "AOL Instant Messenger traffic",
253 { action => 'PARAM', proto => 'tcp', dport => '5190' },
254 ],
255 'IMAP' => [
256 "Internet Message Access Protocol",
257 { action => 'PARAM', proto => 'tcp', dport => '143' },
258 ],
259 'IMAPS' => [
260 "Internet Message Access Protocol over SSL",
261 { action => 'PARAM', proto => 'tcp', dport => '993' },
262 ],
263 'IPIP' => [
264 "IPIP capsulation traffic",
265 { action => 'PARAM', proto => '94' },
266 ],
267 'IPsec' => [
268 "IPsec traffic",
269 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
270 { action => 'PARAM', proto => '50' },
271 ],
272 'IPsecah' => [
273 "IPsec authentication (AH) traffic",
274 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
275 { action => 'PARAM', proto => '51' },
276 ],
277 'IPsecnat' => [
278 "IPsec traffic and Nat-Traversal",
279 { action => 'PARAM', proto => 'udp', dport => '500' },
280 { action => 'PARAM', proto => 'udp', dport => '4500' },
281 { action => 'PARAM', proto => '50' },
282 ],
283 'IRC' => [
284 "Internet Relay Chat traffic",
285 { action => 'PARAM', proto => 'tcp', dport => '6667' },
286 ],
287 'Jetdirect' => [
288 "HP Jetdirect printing",
289 { action => 'PARAM', proto => 'tcp', dport => '9100' },
290 ],
291 'L2TP' => [
292 "Layer 2 Tunneling Protocol traffic",
293 { action => 'PARAM', proto => 'udp', dport => '1701' },
294 ],
295 'LDAP' => [
296 "Lightweight Directory Access Protocol traffic",
297 { action => 'PARAM', proto => 'tcp', dport => '389' },
298 ],
299 'LDAPS' => [
300 "Secure Lightweight Directory Access Protocol traffic",
301 { action => 'PARAM', proto => 'tcp', dport => '636' },
302 ],
303 'MSNP' => [
304 "Microsoft Notification Protocol",
305 { action => 'PARAM', proto => 'tcp', dport => '1863' },
306 ],
307 'MSSQL' => [
308 "Microsoft SQL Server",
309 { action => 'PARAM', proto => 'tcp', dport => '1433' },
310 ],
311 'Mail' => [
312 "Mail traffic (SMTP, SMTPS, Submission)",
313 { action => 'PARAM', proto => 'tcp', dport => '25' },
314 { action => 'PARAM', proto => 'tcp', dport => '465' },
315 { action => 'PARAM', proto => 'tcp', dport => '587' },
316 ],
317 'Munin' => [
318 "Munin networked resource monitoring traffic",
319 { action => 'PARAM', proto => 'tcp', dport => '4949' },
320 ],
321 'MySQL' => [
322 "MySQL server",
323 { action => 'PARAM', proto => 'tcp', dport => '3306' },
324 ],
325 'NNTP' => [
326 "NNTP traffic (Usenet).",
327 { action => 'PARAM', proto => 'tcp', dport => '119' },
328 ],
329 'NNTPS' => [
330 "Encrypted NNTP traffic (Usenet)",
331 { action => 'PARAM', proto => 'tcp', dport => '563' },
332 ],
333 'NTP' => [
334 "Network Time Protocol (ntpd)",
335 { action => 'PARAM', proto => 'udp', dport => '123' },
336 ],
337 'OSPF' => [
338 "OSPF multicast traffic",
339 { action => 'PARAM', proto => '89' },
340 ],
341 'OpenVPN' => [
342 "OpenVPN traffic",
343 { action => 'PARAM', proto => 'udp', dport => '1194' },
344 ],
345 'PCA' => [
346 "Symantec PCAnywere (tm)",
347 { action => 'PARAM', proto => 'udp', dport => '5632' },
348 { action => 'PARAM', proto => 'tcp', dport => '5631' },
349 ],
350 'POP3' => [
351 "POP3 traffic",
352 { action => 'PARAM', proto => 'tcp', dport => '110' },
353 ],
354 'POP3S' => [
355 "Encrypted POP3 traffic",
356 { action => 'PARAM', proto => 'tcp', dport => '995' },
357 ],
358 'PPtP' => [
359 "Point-to-Point Tunneling Protocol",
360 { action => 'PARAM', proto => '47' },
361 { action => 'PARAM', proto => 'tcp', dport => '1723' },
362 ],
363 'Ping' => [
364 "ICMP echo request",
365 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
366 ],
367 'PostgreSQL' => [
368 "PostgreSQL server",
369 { action => 'PARAM', proto => 'tcp', dport => '5432' },
370 ],
371 'Printer' => [
372 "Line Printer protocol printing",
373 { action => 'PARAM', proto => 'tcp', dport => '515' },
374 ],
375 'RDP' => [
376 "Microsoft Remote Desktop Protocol traffic",
377 { action => 'PARAM', proto => 'tcp', dport => '3389' },
378 ],
379 'RIP' => [
380 "Routing Information Protocol (bidirectional)",
381 { action => 'PARAM', proto => 'udp', dport => '520' },
382 ],
383 'RNDC' => [
384 "BIND remote management protocol",
385 { action => 'PARAM', proto => 'tcp', dport => '953' },
386 ],
387 'Razor' => [
388 "Razor Antispam System",
389 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
390 ],
391 'Rdate' => [
392 "Remote time retrieval (rdate)",
393 { action => 'PARAM', proto => 'tcp', dport => '37' },
394 ],
395 'Rsync' => [
396 "Rsync server",
397 { action => 'PARAM', proto => 'tcp', dport => '873' },
398 ],
399 'SANE' => [
400 "SANE network scanning",
401 { action => 'PARAM', proto => 'tcp', dport => '6566' },
402 ],
403 'SMB' => [
404 "Microsoft SMB traffic",
405 { action => 'PARAM', proto => 'udp', dport => '135,445' },
406 { action => 'PARAM', proto => 'udp', dport => '137:139' },
407 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
408 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
409 ],
410 'SMBswat' => [
411 "Samba Web Administration Tool",
412 { action => 'PARAM', proto => 'tcp', dport => '901' },
413 ],
414 'SMTP' => [
415 "Simple Mail Transfer Protocol",
416 { action => 'PARAM', proto => 'tcp', dport => '25' },
417 ],
418 'SMTPS' => [
419 "Encrypted Simple Mail Transfer Protocol",
420 { action => 'PARAM', proto => 'tcp', dport => '465' },
421 ],
422 'SNMP' => [
423 "Simple Network Management Protocol",
424 { action => 'PARAM', proto => 'udp', dport => '161:162' },
425 { action => 'PARAM', proto => 'tcp', dport => '161' },
426 ],
427 'SPAMD' => [
428 "Spam Assassin SPAMD traffic",
429 { action => 'PARAM', proto => 'tcp', dport => '783' },
430 ],
431 'SSH' => [
432 "Secure shell traffic",
433 { action => 'PARAM', proto => 'tcp', dport => '22' },
434 ],
435 'SVN' => [
436 "Subversion server (svnserve)",
437 { action => 'PARAM', proto => 'tcp', dport => '3690' },
438 ],
439 'SixXS' => [
440 "SixXS IPv6 Deployment and Tunnel Broker",
441 { action => 'PARAM', proto => 'tcp', dport => '3874' },
442 { action => 'PARAM', proto => 'udp', dport => '3740' },
443 { action => 'PARAM', proto => '41' },
444 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
445 ],
446 'Squid' => [
447 "Squid web proxy traffic",
448 { action => 'PARAM', proto => 'tcp', dport => '3128' },
449 ],
450 'Submission' => [
451 "Mail message submission traffic",
452 { action => 'PARAM', proto => 'tcp', dport => '587' },
453 ],
454 'Syslog' => [
455 "Syslog protocol (RFC 5424) traffic",
456 { action => 'PARAM', proto => 'udp', dport => '514' },
457 { action => 'PARAM', proto => 'tcp', dport => '514' },
458 ],
459 'TFTP' => [
460 "Trivial File Transfer Protocol traffic",
461 { action => 'PARAM', proto => 'udp', dport => '69' },
462 ],
463 'Telnet' => [
464 "Telnet traffic",
465 { action => 'PARAM', proto => 'tcp', dport => '23' },
466 ],
467 'Telnets' => [
468 "Telnet over SSL",
469 { action => 'PARAM', proto => 'tcp', dport => '992' },
470 ],
471 'Time' => [
472 "RFC 868 Time protocol",
473 { action => 'PARAM', proto => 'tcp', dport => '37' },
474 ],
475 'Trcrt' => [
476 "Traceroute (for up to 30 hops) traffic",
477 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
478 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
479 ],
480 'VNC' => [
481 "VNC traffic for VNC display's 0 - 99",
482 { action => 'PARAM', proto => 'tcp', dport => '5900:5999' },
483 ],
484 'VNCL' => [
485 "VNC traffic from Vncservers to Vncviewers in listen mode",
486 { action => 'PARAM', proto => 'tcp', dport => '5500' },
487 ],
488 'Web' => [
489 "WWW traffic (HTTP and HTTPS)",
490 { action => 'PARAM', proto => 'tcp', dport => '80' },
491 { action => 'PARAM', proto => 'tcp', dport => '443' },
492 ],
493 'Webcache' => [
494 "Web Cache/Proxy traffic (port 8080)",
495 { action => 'PARAM', proto => 'tcp', dport => '8080' },
496 ],
497 'Webmin' => [
498 "Webmin traffic",
499 { action => 'PARAM', proto => 'tcp', dport => '10000' },
500 ],
501 'Whois' => [
502 "Whois (nicname, RFC 3912) traffic",
503 { action => 'PARAM', proto => 'tcp', dport => '43' },
504 ],
505 };
506
507 my $pve_fw_parsed_macros;
508 my $pve_fw_macro_descr;
509 my $pve_fw_macro_ipversion = {};
510 my $pve_fw_preferred_macro_names = {};
511
512 my $pve_std_chains = {};
513 $pve_std_chains->{4} = {
514 'PVEFW-SET-ACCEPT-MARK' => [
515 "-j MARK --set-mark 1",
516 ],
517 'PVEFW-DropBroadcast' => [
518 # same as shorewall 'Broadcast'
519 # simply DROP BROADCAST/MULTICAST/ANYCAST
520 # we can use this to reduce logging
521 { action => 'DROP', dsttype => 'BROADCAST' },
522 { action => 'DROP', dsttype => 'MULTICAST' },
523 { action => 'DROP', dsttype => 'ANYCAST' },
524 { action => 'DROP', dest => '224.0.0.0/4' },
525 ],
526 'PVEFW-reject' => [
527 # same as shorewall 'reject'
528 { action => 'DROP', dsttype => 'BROADCAST' },
529 { action => 'DROP', source => '224.0.0.0/4' },
530 { action => 'DROP', proto => 'icmp' },
531 "-p tcp -j REJECT --reject-with tcp-reset",
532 "-p udp -j REJECT --reject-with icmp-port-unreachable",
533 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
534 "-j REJECT --reject-with icmp-host-prohibited",
535 ],
536 'PVEFW-Drop' => [
537 # same as shorewall 'Drop', which is equal to DROP,
538 # but REJECT/DROP some packages to reduce logging,
539 # and ACCEPT critical ICMP types
540 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
541 # we are not interested in BROADCAST/MULTICAST/ANYCAST
542 { action => 'PVEFW-DropBroadcast' },
543 # ACCEPT critical ICMP types
544 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
545 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
546 # Drop packets with INVALID state
547 "-m conntrack --ctstate INVALID -j DROP",
548 # Drop Microsoft SMB noise
549 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
550 { action => 'DROP', proto => 'udp', dport => '137:139'},
551 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
552 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
553 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
554 # Drop new/NotSyn traffic so that it doesn't get logged
555 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
556 # Drop DNS replies
557 { action => 'DROP', proto => 'udp', sport => 53 },
558 ],
559 'PVEFW-Reject' => [
560 # same as shorewall 'Reject', which is equal to Reject,
561 # but REJECT/DROP some packages to reduce logging,
562 # and ACCEPT critical ICMP types
563 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
564 # we are not interested in BROADCAST/MULTICAST/ANYCAST
565 { action => 'PVEFW-DropBroadcast' },
566 # ACCEPT critical ICMP types
567 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
568 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
569 # Drop packets with INVALID state
570 "-m conntrack --ctstate INVALID -j DROP",
571 # Drop Microsoft SMB noise
572 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
573 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
574 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
575 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
576 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
577 # Drop new/NotSyn traffic so that it doesn't get logged
578 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
579 # Drop DNS replies
580 { action => 'DROP', proto => 'udp', sport => 53 },
581 ],
582 'PVEFW-tcpflags' => [
583 # same as shorewall tcpflags action.
584 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
585 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
586 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
587 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
588 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
589 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
590 ],
591 'PVEFW-smurfs' => [
592 # same as shorewall smurfs action
593 # Filter packets for smurfs (packets with a broadcast address as the source).
594 "-s 0.0.0.0/32 -j RETURN",
595 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
596 "-s 224.0.0.0/4 -g PVEFW-smurflog",
597 ],
598 };
599
600 $pve_std_chains->{6} = {
601 'PVEFW-SET-ACCEPT-MARK' => [
602 "-j MARK --set-mark 1",
603 ],
604 'PVEFW-DropBroadcast' => [
605 # same as shorewall 'Broadcast'
606 # simply DROP BROADCAST/MULTICAST/ANYCAST
607 # we can use this to reduce logging
608 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
609 # ipv6 addrtype does not work with kernel 2.6.32
610 #{ action => 'DROP', dsttype => 'MULTICAST' },
611 #{ action => 'DROP', dsttype => 'ANYCAST' },
612 { action => 'DROP', dest => 'ff00::/8' },
613 #{ action => 'DROP', dest => '224.0.0.0/4' },
614 ],
615 'PVEFW-reject' => [
616 # same as shorewall 'reject'
617 #{ action => 'DROP', dsttype => 'BROADCAST' },
618 #{ action => 'DROP', source => '224.0.0.0/4' },
619 { action => 'DROP', proto => 'icmpv6' },
620 "-p tcp -j REJECT --reject-with tcp-reset",
621 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
622 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
623 #"-j REJECT --reject-with icmp-host-prohibited",
624 ],
625 'PVEFW-Drop' => [
626 # same as shorewall 'Drop', which is equal to DROP,
627 # but REJECT/DROP some packages to reduce logging,
628 # and ACCEPT critical ICMP types
629 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
630 # we are not interested in BROADCAST/MULTICAST/ANYCAST
631 { action => 'PVEFW-DropBroadcast' },
632 # ACCEPT critical ICMP types
633 { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' },
634 { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' },
635 { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' },
636
637 # Drop packets with INVALID state
638 "-m conntrack --ctstate INVALID -j DROP",
639 # Drop Microsoft SMB noise
640 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
641 { action => 'DROP', proto => 'udp', dport => '137:139'},
642 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
643 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
644 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
645 # Drop new/NotSyn traffic so that it doesn't get logged
646 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
647 # Drop DNS replies
648 { action => 'DROP', proto => 'udp', sport => 53 },
649 ],
650 'PVEFW-Reject' => [
651 # same as shorewall 'Reject', which is equal to Reject,
652 # but REJECT/DROP some packages to reduce logging,
653 # and ACCEPT critical ICMP types
654 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
655 # we are not interested in BROADCAST/MULTICAST/ANYCAST
656 { action => 'PVEFW-DropBroadcast' },
657 # ACCEPT critical ICMP types
658 { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' },
659 { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' },
660 { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' },
661
662 # Drop packets with INVALID state
663 "-m conntrack --ctstate INVALID -j DROP",
664 # Drop Microsoft SMB noise
665 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
666 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
667 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
668 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
669 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
670 # Drop new/NotSyn traffic so that it doesn't get logged
671 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
672 # Drop DNS replies
673 { action => 'DROP', proto => 'udp', sport => 53 },
674 ],
675 'PVEFW-tcpflags' => [
676 # same as shorewall tcpflags action.
677 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
678 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
679 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
680 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
681 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
682 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
683 ],
684 };
685
686 # iptables -p icmp -h
687 my $icmp_type_names = {
688 any => 1,
689 'echo-reply' => 1,
690 'destination-unreachable' => 1,
691 'network-unreachable' => 1,
692 'host-unreachable' => 1,
693 'protocol-unreachable' => 1,
694 'port-unreachable' => 1,
695 'fragmentation-needed' => 1,
696 'source-route-failed' => 1,
697 'network-unknown' => 1,
698 'host-unknown' => 1,
699 'network-prohibited' => 1,
700 'host-prohibited' => 1,
701 'TOS-network-unreachable' => 1,
702 'TOS-host-unreachable' => 1,
703 'communication-prohibited' => 1,
704 'host-precedence-violation' => 1,
705 'precedence-cutoff' => 1,
706 'source-quench' => 1,
707 'redirect' => 1,
708 'network-redirect' => 1,
709 'host-redirect' => 1,
710 'TOS-network-redirect' => 1,
711 'TOS-host-redirect' => 1,
712 'echo-request' => 1,
713 'router-advertisement' => 1,
714 'router-solicitation' => 1,
715 'time-exceeded' => 1,
716 'ttl-zero-during-transit' => 1,
717 'ttl-zero-during-reassembly' => 1,
718 'parameter-problem' => 1,
719 'ip-header-bad' => 1,
720 'required-option-missing' => 1,
721 'timestamp-request' => 1,
722 'timestamp-reply' => 1,
723 'address-mask-request' => 1,
724 'address-mask-reply' => 1,
725 };
726
727 # ip6tables -p icmpv6 -h
728
729 my $icmpv6_type_names = {
730 'any' => 1,
731 'destination-unreachable' => 1,
732 'no-route' => 1,
733 'communication-prohibited' => 1,
734 'address-unreachable' => 1,
735 'port-unreachable' => 1,
736 'packet-too-big' => 1,
737 'time-exceeded' => 1,
738 'ttl-zero-during-transit' => 1,
739 'ttl-zero-during-reassembly' => 1,
740 'parameter-problem' => 1,
741 'bad-header' => 1,
742 'unknown-header-type' => 1,
743 'unknown-option' => 1,
744 'echo-request' => 1,
745 'echo-reply' => 1,
746 'router-solicitation' => 1,
747 'router-advertisement' => 1,
748 'neighbor-solicitation' => 1,
749 'neighbour-solicitation' => 1,
750 'neighbor-advertisement' => 1,
751 'neighbour-advertisement' => 1,
752 'redirect' => 1,
753 };
754
755 sub init_firewall_macros {
756
757 $pve_fw_parsed_macros = {};
758
759 my $parse = sub {
760 my ($k, $macro) = @_;
761 my $lc_name = lc($k);
762 $pve_fw_macro_ipversion->{$k} = 0;
763 while (!ref($macro->[0])) {
764 my $desc = shift @$macro;
765 if ($desc eq 'ipv4only') {
766 $pve_fw_macro_ipversion->{$k} = 4;
767 } elsif ($desc eq 'ipv6only') {
768 $pve_fw_macro_ipversion->{$k} = 6;
769 } else {
770 $pve_fw_macro_descr->{$k} = $desc;
771 }
772 }
773 $pve_fw_preferred_macro_names->{$lc_name} = $k;
774 $pve_fw_parsed_macros->{$k} = $macro;
775 };
776
777 foreach my $k (keys %$pve_fw_macros) {
778 &$parse($k, $pve_fw_macros->{$k});
779 }
780
781 foreach my $k (keys %$pve_ipv6fw_macros) {
782 next if $pve_fw_parsed_macros->{$k};
783 &$parse($k, $pve_ipv6fw_macros->{$k});
784 $pve_fw_macro_ipversion->{$k} = 6;
785 }
786 }
787
788 init_firewall_macros();
789
790 sub get_macros {
791 return wantarray ? ($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
792 }
793
794 my $etc_services;
795
796 sub get_etc_services {
797
798 return $etc_services if $etc_services;
799
800 my $filename = "/etc/services";
801
802 my $fh = IO::File->new($filename, O_RDONLY);
803 if (!$fh) {
804 warn "unable to read '$filename' - $!\n";
805 return {};
806 }
807
808 my $services = {};
809
810 while (my $line = <$fh>) {
811 chomp ($line);
812 next if $line =~m/^#/;
813 next if ($line =~m/^\s*$/);
814
815 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
816 $services->{byid}->{$2}->{name} = $1;
817 $services->{byid}->{$2}->{port} = $2;
818 $services->{byid}->{$2}->{$3} = 1;
819 $services->{byname}->{$1} = $services->{byid}->{$2};
820 }
821 }
822
823 close($fh);
824
825 $etc_services = $services;
826
827
828 return $etc_services;
829 }
830
831 my $etc_protocols;
832
833 sub get_etc_protocols {
834 return $etc_protocols if $etc_protocols;
835
836 my $filename = "/etc/protocols";
837
838 my $fh = IO::File->new($filename, O_RDONLY);
839 if (!$fh) {
840 warn "unable to read '$filename' - $!\n";
841 return {};
842 }
843
844 my $protocols = {};
845
846 while (my $line = <$fh>) {
847 chomp ($line);
848 next if $line =~m/^#/;
849 next if ($line =~m/^\s*$/);
850
851 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
852 $protocols->{byid}->{$2}->{name} = $1;
853 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
854 }
855 }
856
857 close($fh);
858
859 # add special case for ICMP v6
860 $protocols->{byid}->{icmpv6}->{name} = "icmpv6";
861 $protocols->{byname}->{icmpv6} = $protocols->{byid}->{icmpv6};
862
863 $etc_protocols = $protocols;
864
865 return $etc_protocols;
866 }
867
868 my $ipv4_mask_hash_localnet = {
869 '255.255.0.0' => 16,
870 '255.255.128.0' => 17,
871 '255.255.192.0' => 18,
872 '255.255.224.0' => 19,
873 '255.255.240.0' => 20,
874 '255.255.248.0' => 21,
875 '255.255.252.0' => 22,
876 '255.255.254.0' => 23,
877 '255.255.255.0' => 24,
878 '255.255.255.128' => 25,
879 '255.255.255.192' => 26,
880 '255.255.255.224' => 27,
881 '255.255.255.240' => 28,
882 '255.255.255.248' => 29,
883 '255.255.255.252' => 30,
884 };
885
886 my $__local_network;
887
888 sub local_network {
889 my ($new_value) = @_;
890
891 $__local_network = $new_value if defined($new_value);
892
893 return $__local_network if defined($__local_network);
894
895 eval {
896 my $nodename = PVE::INotify::nodename();
897
898 my $ip = PVE::Cluster::remote_node_ip($nodename);
899
900 my $testip = Net::IP->new($ip);
901
902 my $routes = PVE::ProcFSTools::read_proc_net_route();
903 foreach my $entry (@$routes) {
904 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask}};
905 next if !defined($mask);
906 return if $mask eq '0.0.0.0';
907 my $cidr = "$entry->{dest}/$mask";
908 my $testnet = Net::IP->new($cidr);
909 if ($testnet->overlaps($testip)) {
910 $__local_network = $cidr;
911 return;
912 }
913 }
914 };
915 warn $@ if $@;
916
917 return $__local_network;
918 }
919
920 # ipset names are limited to 31 characters,
921 # and we use '-v4' or '-v6' to indicate IP versions,
922 # and we use '_swap' suffix for atomic update,
923 # for example PVEFW-${VMID}-${ipset_name}_swap
924
925 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
926
927 sub compute_ipset_chain_name {
928 my ($vmid, $ipset_name, $ipversion) = @_;
929
930 $vmid = 0 if !defined($vmid);
931
932 my $id = "$vmid-${ipset_name}-v$ipversion";
933
934 if (length($id) > $max_iptables_ipset_name_length) {
935 $id = PVE::Tools::fnv31a_hex($id);
936 }
937
938 return "PVEFW-$id";
939 }
940
941 sub compute_ipfilter_ipset_name {
942 my ($iface) = @_;
943
944 return "ipfilter-$iface";
945 }
946
947 sub parse_address_list {
948 my ($str) = @_;
949
950 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
951 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
952 return;
953 }
954
955 if ($str =~ m/^${ip_alias_pattern}$/) {
956 die "alias name too long\n" if length($str) > $max_alias_name_length;
957 return;
958 }
959
960 my $count = 0;
961 my $iprange = 0;
962 my $ipversion;
963
964 foreach my $elem (split(/,/, $str)) {
965 $count++;
966 my $ip = Net::IP->new($elem);
967 if (!$ip) {
968 my $err = Net::IP::Error();
969 die "invalid IP address: $err\n";
970 }
971 $iprange = 1 if $elem =~ m/-/;
972
973 my $new_ipversion = Net::IP::ip_is_ipv6($ip->ip()) ? 6 : 4;
974
975 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
976 if $ipversion && ($new_ipversion != $ipversion);
977
978 $ipversion = $new_ipversion;
979 }
980
981 die "you can't use a range in a list\n" if $iprange && $count > 1;
982
983 return $ipversion;
984 }
985
986 sub parse_port_name_number_or_range {
987 my ($str) = @_;
988
989 my $services = PVE::Firewall::get_etc_services();
990 my $count = 0;
991 my $icmp_port = 0;
992
993 foreach my $item (split(/,/, $str)) {
994 $count++;
995 if ($item =~ m/^(\d+):(\d+)$/) {
996 my ($port1, $port2) = ($1, $2);
997 die "invalid port '$port1'\n" if $port1 > 65535;
998 die "invalid port '$port2'\n" if $port2 > 65535;
999 } elsif ($item =~ m/^(\d+)$/) {
1000 my $port = $1;
1001 die "invalid port '$port'\n" if $port > 65535;
1002 } else {
1003 if ($icmp_type_names->{$item}) {
1004 $icmp_port = 1;
1005 } elsif ($icmpv6_type_names->{$item}) {
1006 $icmp_port = 1;
1007 } else {
1008 die "invalid port '$item'\n" if !$services->{byname}->{$item};
1009 }
1010 }
1011 }
1012
1013 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1014
1015 return $count;
1016 }
1017
1018 PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
1019 sub pve_fw_verify_port_spec {
1020 my ($portstr) = @_;
1021
1022 parse_port_name_number_or_range($portstr);
1023
1024 return $portstr;
1025 }
1026
1027 PVE::JSONSchema::register_format('pve-fw-addr-spec', \&pve_fw_verify_addr_spec);
1028 sub pve_fw_verify_addr_spec {
1029 my ($list) = @_;
1030
1031 parse_address_list($list);
1032
1033 return $list;
1034 }
1035
1036 PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
1037 sub pve_fw_verify_protocol_spec {
1038 my ($proto) = @_;
1039
1040 my $protocols = get_etc_protocols();
1041
1042 die "unknown protocol '$proto'\n" if $proto &&
1043 !(defined($protocols->{byname}->{$proto}) ||
1044 defined($protocols->{byid}->{$proto}));
1045
1046 return $proto;
1047 }
1048
1049
1050 # helper function for API
1051
1052 sub copy_opject_with_digest {
1053 my ($object) = @_;
1054
1055 my $sha = Digest::SHA->new('sha1');
1056
1057 my $res = {};
1058 foreach my $k (sort keys %$object) {
1059 my $v = $object->{$k};
1060 next if !defined($v);
1061 $res->{$k} = $v;
1062 $sha->add($k, ':', $v, "\n");
1063 }
1064
1065 my $digest = $sha->hexdigest;
1066
1067 $res->{digest} = $digest;
1068
1069 return wantarray ? ($res, $digest) : $res;
1070 }
1071
1072 sub copy_list_with_digest {
1073 my ($list) = @_;
1074
1075 my $sha = Digest::SHA->new('sha1');
1076
1077 my $res = [];
1078 foreach my $entry (@$list) {
1079 my $data = {};
1080 foreach my $k (sort keys %$entry) {
1081 my $v = $entry->{$k};
1082 next if !defined($v);
1083 $data->{$k} = $v;
1084 # Note: digest ignores refs ($rule->{errors})
1085 $sha->add($k, ':', $v, "\n") if !ref($v); ;
1086 }
1087 push @$res, $data;
1088 }
1089
1090 my $digest = $sha->hexdigest;
1091
1092 foreach my $entry (@$res) {
1093 $entry->{digest} = $digest;
1094 }
1095
1096 return wantarray ? ($res, $digest) : $res;
1097 }
1098
1099 my $rule_properties = {
1100 pos => {
1101 description => "Update rule at position <pos>.",
1102 type => 'integer',
1103 minimum => 0,
1104 optional => 1,
1105 },
1106 digest => get_standard_option('pve-config-digest'),
1107 type => {
1108 type => 'string',
1109 optional => 1,
1110 enum => ['in', 'out', 'group'],
1111 },
1112 action => {
1113 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1114 type => 'string',
1115 optional => 1,
1116 pattern => $security_group_name_pattern,
1117 maxLength => 20,
1118 minLength => 2,
1119 },
1120 macro => {
1121 type => 'string',
1122 optional => 1,
1123 maxLength => 128,
1124 },
1125 iface => get_standard_option('pve-iface', { optional => 1 }),
1126 source => {
1127 type => 'string', format => 'pve-fw-addr-spec',
1128 optional => 1,
1129 },
1130 dest => {
1131 type => 'string', format => 'pve-fw-addr-spec',
1132 optional => 1,
1133 },
1134 proto => {
1135 type => 'string', format => 'pve-fw-protocol-spec',
1136 optional => 1,
1137 },
1138 enable => {
1139 type => 'boolean',
1140 optional => 1,
1141 },
1142 sport => {
1143 type => 'string', format => 'pve-fw-port-spec',
1144 optional => 1,
1145 },
1146 dport => {
1147 type => 'string', format => 'pve-fw-port-spec',
1148 optional => 1,
1149 },
1150 comment => {
1151 type => 'string',
1152 optional => 1,
1153 },
1154 };
1155
1156 sub add_rule_properties {
1157 my ($properties) = @_;
1158
1159 foreach my $k (keys %$rule_properties) {
1160 my $h = $rule_properties->{$k};
1161 # copy data, so that we can modify later without side effects
1162 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1163 }
1164
1165 return $properties;
1166 }
1167
1168 sub delete_rule_properties {
1169 my ($rule, $delete_str) = @_;
1170
1171 foreach my $opt (PVE::Tools::split_list($delete_str)) {
1172 raise_param_exc({ 'delete' => "no such property ('$opt')"})
1173 if !defined($rule_properties->{$opt});
1174 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
1175 if $opt eq 'type' || $opt eq 'action';
1176 delete $rule->{$opt};
1177 }
1178
1179 return $rule;
1180 }
1181
1182 my $apply_macro = sub {
1183 my ($macro_name, $param, $verify, $ipversion) = @_;
1184
1185 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1186 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1187
1188 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1189 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1190 }
1191
1192 # skip macros which are specific to another ipversion
1193 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1194 return if $ipversion != $required;
1195 }
1196
1197 my $rules = [];
1198
1199 foreach my $templ (@$macro_rules) {
1200 my $rule = {};
1201 my $param_used = {};
1202 foreach my $k (keys %$templ) {
1203 my $v = $templ->{$k};
1204 if ($v eq 'PARAM') {
1205 $v = $param->{$k};
1206 $param_used->{$k} = 1;
1207 } elsif ($v eq 'DEST') {
1208 $v = $param->{dest};
1209 $param_used->{dest} = 1;
1210 } elsif ($v eq 'SOURCE') {
1211 $v = $param->{source};
1212 $param_used->{source} = 1;
1213 }
1214
1215 if (!defined($v)) {
1216 my $msg = "missing parameter '$k' in macro '$macro_name'";
1217 raise_param_exc({ macro => $msg }) if $verify;
1218 die "$msg\n";
1219 }
1220 $rule->{$k} = $v;
1221 }
1222 foreach my $k (keys %$param) {
1223 next if $k eq 'macro';
1224 next if !defined($param->{$k});
1225 next if $param_used->{$k};
1226 if (defined($rule->{$k})) {
1227 if ($rule->{$k} ne $param->{$k}) {
1228 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1229 raise_param_exc({ $k => $msg }) if $verify;
1230 die "$msg\n";
1231 }
1232 } else {
1233 $rule->{$k} = $param->{$k};
1234 }
1235 }
1236 push @$rules, $rule;
1237 }
1238
1239 return $rules;
1240 };
1241
1242 my $rule_env_iface_lookup = {
1243 'ct' => 1,
1244 'vm' => 1,
1245 'group' => 0,
1246 'cluster' => 1,
1247 'host' => 1,
1248 };
1249
1250 sub verify_rule {
1251 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1252
1253 my $allow_groups = $rule_env eq 'group' ? 0 : 1;
1254
1255 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1256 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1257
1258 my $errors = $rule->{errors} || {};
1259
1260 my $error_count = 0;
1261
1262 my $add_error = sub {
1263 my ($param, $msg) = @_;
1264 chomp $msg;
1265 raise_param_exc({ $param => $msg }) if !$noerr;
1266 $error_count++;
1267 $errors->{$param} = $msg if !$errors->{$param};
1268 };
1269
1270 my $ipversion;
1271 my $set_ip_version = sub {
1272 my $vers = shift;
1273 if ($vers) {
1274 die "detected mixed ipv4/ipv6 adresses in rule\n"
1275 if $ipversion && ($vers != $ipversion);
1276 $ipversion = $vers;
1277 }
1278 };
1279
1280 my $check_ipset_or_alias_property = sub {
1281 my ($name, $expected_ipversion) = @_;
1282
1283 if (my $value = $rule->{$name}) {
1284 if ($value =~ m/^\+/) {
1285 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1286 &$add_error($name, "no such ipset '$1'")
1287 if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
1288
1289 } else {
1290 &$add_error($name, "invalid ipset name '$value'");
1291 }
1292 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1293 my $alias = lc($value);
1294 &$add_error($name, "no such alias '$value'")
1295 if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}));
1296 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
1297 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1298
1299 &$set_ip_version($e->{ipversion});
1300 }
1301 }
1302 };
1303
1304 my $type = $rule->{type};
1305 my $action = $rule->{action};
1306
1307 &$add_error('type', "missing property") if !$type;
1308 &$add_error('action', "missing property") if !$action;
1309
1310 if ($type) {
1311 if ($type eq 'in' || $type eq 'out') {
1312 &$add_error('action', "unknown action '$action'")
1313 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1314 } elsif ($type eq 'group') {
1315 &$add_error('type', "security groups not allowed")
1316 if !$allow_groups;
1317 &$add_error('action', "invalid characters in security group name")
1318 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1319 } else {
1320 &$add_error('type', "unknown rule type '$type'");
1321 }
1322 }
1323
1324 if ($rule->{iface}) {
1325 &$add_error('type', "parameter -i not allowed for this rule type")
1326 if !$allow_iface;
1327 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
1328 &$add_error('iface', $@) if $@;
1329 if ($rule_env eq 'vm') {
1330 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1331 if $rule->{iface} !~ m/^net(\d+)$/;
1332 } elsif ($rule_env eq 'ct') {
1333 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1334 if $rule->{iface} !~ m/^(venet|eth(\d+))$/;
1335 }
1336 }
1337
1338 if ($rule->{macro}) {
1339 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1340 $rule->{macro} = $preferred_name;
1341 } else {
1342 &$add_error('macro', "unknown macro '$rule->{macro}'");
1343 }
1344 }
1345
1346 if ($rule->{proto}) {
1347 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1348 &$add_error('proto', $@) if $@;
1349 &$set_ip_version(4) if $rule->{proto} eq 'icmp';
1350 &$set_ip_version(6) if $rule->{proto} eq 'icmpv6';
1351 }
1352
1353 if ($rule->{dport}) {
1354 eval { parse_port_name_number_or_range($rule->{dport}); };
1355 &$add_error('dport', $@) if $@;
1356 &$add_error('proto', "missing property - 'dport' requires this property")
1357 if !$rule->{proto};
1358 }
1359
1360 if ($rule->{sport}) {
1361 eval { parse_port_name_number_or_range($rule->{sport}); };
1362 &$add_error('sport', $@) if $@;
1363 &$add_error('proto', "missing property - 'sport' requires this property")
1364 if !$rule->{proto};
1365 }
1366
1367 if ($rule->{source}) {
1368 eval {
1369 my $source_ipversion = parse_address_list($rule->{source});
1370 &$set_ip_version($source_ipversion);
1371 };
1372 &$add_error('source', $@) if $@;
1373 &$check_ipset_or_alias_property('source', $ipversion);
1374 }
1375
1376 if ($rule->{dest}) {
1377 eval {
1378 my $dest_ipversion = parse_address_list($rule->{dest});
1379 &$set_ip_version($dest_ipversion);
1380 };
1381 &$add_error('dest', $@) if $@;
1382 &$check_ipset_or_alias_property('dest', $ipversion);
1383 }
1384
1385 $rule->{ipversion} = $ipversion if $ipversion;
1386
1387 if ($rule->{macro} && !$error_count) {
1388 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1389 if (my $err = $@) {
1390 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1391 my $eh = $err->{errors};
1392 foreach my $p (keys %$eh) {
1393 &$add_error($p, $eh->{$p});
1394 }
1395 } else {
1396 &$add_error('macro', "$err");
1397 }
1398 }
1399 }
1400
1401 $rule->{errors} = $errors if $error_count;
1402
1403 return $rule;
1404 }
1405
1406 sub copy_rule_data {
1407 my ($rule, $param) = @_;
1408
1409 foreach my $k (keys %$rule_properties) {
1410 if (defined(my $v = $param->{$k})) {
1411 if ($v eq '' || $v eq '-') {
1412 delete $rule->{$k};
1413 } else {
1414 $rule->{$k} = $v;
1415 }
1416 }
1417 }
1418
1419 return $rule;
1420 }
1421
1422 sub rules_modify_permissions {
1423 my ($rule_env) = @_;
1424
1425 if ($rule_env eq 'host') {
1426 return {
1427 check => ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1428 };
1429 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1430 return {
1431 check => ['perm', '/', [ 'Sys.Modify' ]],
1432 };
1433 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1434 return {
1435 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1436 }
1437 }
1438
1439 return undef;
1440 }
1441
1442 sub rules_audit_permissions {
1443 my ($rule_env) = @_;
1444
1445 if ($rule_env eq 'host') {
1446 return {
1447 check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1448 };
1449 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1450 return {
1451 check => ['perm', '/', [ 'Sys.Audit' ]],
1452 };
1453 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1454 return {
1455 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1456 }
1457 }
1458
1459 return undef;
1460 }
1461
1462 # core functions
1463 my $bridge_firewall_enabled = 0;
1464
1465 sub enable_bridge_firewall {
1466
1467 return if $bridge_firewall_enabled; # only once
1468
1469 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1470 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1471
1472 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1473 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1474
1475 $bridge_firewall_enabled = 1;
1476 }
1477
1478 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1479
1480 sub iptables_restore_cmdlist {
1481 my ($cmdlist) = @_;
1482
1483 run_command("/sbin/iptables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
1484 }
1485
1486 sub ip6tables_restore_cmdlist {
1487 my ($cmdlist) = @_;
1488
1489 run_command("/sbin/ip6tables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
1490 }
1491
1492 sub ipset_restore_cmdlist {
1493 my ($cmdlist) = @_;
1494
1495 run_command("/usr/sbin/ipset restore", input => $cmdlist, errmsg => "ipset_restore_cmdlist");
1496 }
1497
1498 sub iptables_get_chains {
1499 my ($iptablescmd) = @_;
1500
1501 $iptablescmd = "iptables" if !$iptablescmd;
1502
1503 my $res = {};
1504
1505 # check what chains we want to track
1506 my $is_pvefw_chain = sub {
1507 my $name = shift;
1508
1509 return 1 if $name =~ m/^PVEFW-\S+$/;
1510
1511 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1512
1513 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1514
1515 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1516
1517 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1518 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1519
1520 return undef;
1521 };
1522
1523 my $table = '';
1524
1525 my $hooks = {};
1526
1527 my $parser = sub {
1528 my $line = shift;
1529
1530 return if $line =~ m/^#/;
1531 return if $line =~ m/^\s*$/;
1532
1533 if ($line =~ m/^\*(\S+)$/) {
1534 $table = $1;
1535 return;
1536 }
1537
1538 return if $table ne 'filter';
1539
1540 if ($line =~ m/^:(\S+)\s/) {
1541 my $chain = $1;
1542 return if !&$is_pvefw_chain($chain);
1543 $res->{$chain} = "unknown";
1544 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1545 my ($chain, $sig) = ($1, $2);
1546 return if !&$is_pvefw_chain($chain);
1547 $res->{$chain} = $sig;
1548 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1549 $hooks->{$1} = 1;
1550 } else {
1551 # simply ignore the rest
1552 return;
1553 }
1554 };
1555
1556 run_command("/sbin/$iptablescmd-save", outfunc => $parser);
1557
1558 return wantarray ? ($res, $hooks) : $res;
1559 }
1560
1561 sub iptables_chain_digest {
1562 my ($rules) = @_;
1563 my $digest = Digest::SHA->new('sha1');
1564 foreach my $rule (@$rules) { # order is important
1565 $digest->add($rule);
1566 }
1567 return $digest->b64digest;
1568 }
1569
1570 sub ipset_chain_digest {
1571 my ($rules) = @_;
1572
1573 my $digest = Digest::SHA->new('sha1');
1574 foreach my $rule (sort @$rules) { # note: sorted
1575 $digest->add($rule);
1576 }
1577 return $digest->b64digest;
1578 }
1579
1580 sub ipset_get_chains {
1581
1582 my $res = {};
1583 my $chains = {};
1584
1585 my $parser = sub {
1586 my $line = shift;
1587
1588 return if $line =~ m/^#/;
1589 return if $line =~ m/^\s*$/;
1590 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1591 my $chain = $1;
1592 $line =~ s/\s+$//; # delete trailing white space
1593 push @{$chains->{$chain}}, $line;
1594 } else {
1595 # simply ignore the rest
1596 return;
1597 }
1598 };
1599
1600 run_command("/usr/sbin/ipset save", outfunc => $parser);
1601
1602 # compute digest for each chain
1603 foreach my $chain (keys %$chains) {
1604 $res->{$chain} = ipset_chain_digest($chains->{$chain});
1605 }
1606
1607 return $res;
1608 }
1609
1610 sub ruleset_generate_cmdstr {
1611 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1612
1613 return if defined($rule->{enable}) && !$rule->{enable};
1614 return if $rule->{errors};
1615
1616 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1617
1618 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1619 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
1620
1621 my @cmd = ();
1622
1623 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1624 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1625
1626 my $source = $rule->{source};
1627 my $dest = $rule->{dest};
1628
1629 if ($source) {
1630 if ($source =~ m/^\+/) {
1631 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1632 my $name = $1;
1633 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
1634 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
1635 push @cmd, "-m set --match-set ${ipset_chain} src";
1636 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
1637 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
1638 push @cmd, "-m set --match-set ${ipset_chain} src";
1639 } else {
1640 die "no such ipset '$name'\n";
1641 }
1642 } else {
1643 die "invalid security group name '$source'\n";
1644 }
1645 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1646 my $alias = lc($source);
1647 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
1648 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1649 die "no such alias '$source'\n" if !$e;
1650 push @cmd, "-s $e->{cidr}";
1651 } elsif ($source =~ m/\-/){
1652 push @cmd, "-m iprange --src-range $source";
1653 } else {
1654 push @cmd, "-s $source";
1655 }
1656 }
1657
1658 if ($dest) {
1659 if ($dest =~ m/^\+/) {
1660 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1661 my $name = $1;
1662 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
1663 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
1664 push @cmd, "-m set --match-set ${ipset_chain} dst";
1665 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
1666 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
1667 push @cmd, "-m set --match-set ${ipset_chain} dst";
1668 } else {
1669 die "no such ipset '$name'\n";
1670 }
1671 } else {
1672 die "invalid security group name '$dest'\n";
1673 }
1674 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1675 my $alias = lc($dest);
1676 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
1677 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1678 die "no such alias '$dest'\n" if !$e;
1679 push @cmd, "-d $e->{cidr}";
1680 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1681 push @cmd, "-m iprange --dst-range $dest";
1682 } else {
1683 push @cmd, "-d $dest";
1684 }
1685 }
1686
1687 if ($rule->{proto}) {
1688 push @cmd, "-p $rule->{proto}";
1689
1690 my $multiport = 0;
1691 $multiport++ if $nbdport > 1;
1692 $multiport++ if $nbsport > 1;
1693
1694 push @cmd, "--match multiport" if $multiport;
1695
1696 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1697 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1698
1699 if ($rule->{dport}) {
1700 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1701 # Note: we use dport to store --icmp-type
1702 die "unknown icmp-type '$rule->{dport}'\n"
1703 if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
1704 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1705 } elsif ($rule->{proto} && $rule->{proto} eq 'icmpv6') {
1706 # Note: we use dport to store --icmpv6-type
1707 die "unknown icmpv6-type '$rule->{dport}'\n"
1708 if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
1709 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1710 } else {
1711 if ($nbdport > 1) {
1712 if ($multiport == 2) {
1713 push @cmd, "--ports $rule->{dport}";
1714 } else {
1715 push @cmd, "--dports $rule->{dport}";
1716 }
1717 } else {
1718 push @cmd, "--dport $rule->{dport}";
1719 }
1720 }
1721 }
1722
1723 if ($rule->{sport}) {
1724 if ($nbsport > 1) {
1725 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1726 } else {
1727 push @cmd, "--sport $rule->{sport}";
1728 }
1729 }
1730 } elsif ($rule->{dport} || $rule->{sport}) {
1731 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1732 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
1733 }
1734
1735 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1736
1737 if (my $action = $rule->{action}) {
1738 $action = $actions->{$action} if defined($actions->{$action});
1739 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1740 push @cmd, $goto ? "-g $action" : "-j $action";
1741 }
1742
1743 return scalar(@cmd) ? join(' ', @cmd) : undef;
1744 }
1745
1746 sub ruleset_generate_rule {
1747 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1748
1749 my $rules;
1750
1751 if ($rule->{macro}) {
1752 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1753 } else {
1754 $rules = [ $rule ];
1755 }
1756
1757 # update all or nothing
1758
1759 my @cmds = ();
1760 foreach my $tmp (@$rules) {
1761 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1762 push @cmds, $cmdstr;
1763 }
1764 }
1765
1766 foreach my $cmdstr (@cmds) {
1767 ruleset_addrule($ruleset, $chain, $cmdstr);
1768 }
1769 }
1770
1771 sub ruleset_generate_rule_insert {
1772 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1773
1774 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1775
1776 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1777 ruleset_insertrule($ruleset, $chain, $cmdstr);
1778 }
1779 }
1780
1781 sub ruleset_create_chain {
1782 my ($ruleset, $chain) = @_;
1783
1784 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1785 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1786
1787 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1788
1789 $ruleset->{$chain} = [];
1790 }
1791
1792 sub ruleset_chain_exist {
1793 my ($ruleset, $chain) = @_;
1794
1795 return $ruleset->{$chain} ? 1 : undef;
1796 }
1797
1798 sub ruleset_addrule {
1799 my ($ruleset, $chain, $rule) = @_;
1800
1801 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1802
1803 push @{$ruleset->{$chain}}, "-A $chain $rule";
1804 }
1805
1806 sub ruleset_insertrule {
1807 my ($ruleset, $chain, $rule) = @_;
1808
1809 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1810
1811 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1812 }
1813
1814 sub get_log_rule_base {
1815 my ($chain, $vmid, $msg, $loglevel) = @_;
1816
1817 die "internal error - no log level" if !defined($loglevel);
1818
1819 $vmid = 0 if !defined($vmid);
1820
1821 # Note: we use special format for prefix to pass further
1822 # info to log daemon (VMID, LOGVELEL and CHAIN)
1823
1824 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1825 }
1826
1827 sub ruleset_addlog {
1828 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1829
1830 return if !defined($loglevel);
1831
1832 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1833
1834 $logrule = "$rule $logrule" if defined($rule);
1835
1836 ruleset_addrule($ruleset, $chain, $logrule);
1837 }
1838
1839 sub ruleset_add_chain_policy {
1840 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1841
1842 if ($policy eq 'ACCEPT') {
1843
1844 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1845 { ACCEPT => $accept_action});
1846
1847 } elsif ($policy eq 'DROP') {
1848
1849 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1850
1851 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1852
1853 ruleset_addrule($ruleset, $chain, "-j DROP");
1854 } elsif ($policy eq 'REJECT') {
1855 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1856
1857 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1858
1859 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1860 } else {
1861 # should not happen
1862 die "internal error: unknown policy '$policy'";
1863 }
1864 }
1865
1866 sub ruleset_chain_add_ndp {
1867 my ($ruleset, $chain, $ipversion, $options) = @_;
1868 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
1869
1870 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-solicitation -j ACCEPT");
1871 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement -j ACCEPT");
1872 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-solicitation -j ACCEPT");
1873 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-advertisement -j ACCEPT");
1874 }
1875
1876 sub ruleset_chain_add_conn_filters {
1877 my ($ruleset, $chain, $accept) = @_;
1878
1879 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1880 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1881 }
1882
1883 sub ruleset_chain_add_input_filters {
1884 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
1885
1886 if ($cluster_conf->{ipset}->{blacklist}){
1887 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1888 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1889 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1890 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1891 }
1892 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1893 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
1894 }
1895
1896 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1897 if ($ipversion == 4) {
1898 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1899 }
1900 }
1901
1902 if ($options->{tcpflags}) {
1903 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1904 }
1905 }
1906
1907 sub ruleset_create_vm_chain {
1908 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1909
1910 ruleset_create_chain($ruleset, $chain);
1911 my $accept = generate_nfqueue($options);
1912
1913 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1914 if ($direction eq 'OUT') {
1915 ruleset_generate_rule($ruleset, $chain, $ipversion,
1916 { action => 'PVEFW-SET-ACCEPT-MARK',
1917 proto => 'udp', sport => 68, dport => 67 });
1918 } else {
1919 ruleset_generate_rule($ruleset, $chain, $ipversion,
1920 { action => 'ACCEPT',
1921 proto => 'udp', sport => 67, dport => 68 });
1922 }
1923 }
1924
1925 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
1926
1927 if ($direction eq 'OUT') {
1928 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1929 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
1930 }
1931 if ($ipfilter_ipset) {
1932 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP");
1933 }
1934 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1935 }
1936 }
1937
1938 sub ruleset_add_group_rule {
1939 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1940
1941 my $group = $rule->{action};
1942 my $group_chain = "GROUP-$group-$direction";
1943 if(!ruleset_chain_exist($ruleset, $group_chain)){
1944 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1945 }
1946
1947 if ($direction eq 'OUT' && $rule->{iface_out}) {
1948 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1949 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1950 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
1951 } else {
1952 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1953 }
1954
1955 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1956 }
1957
1958 sub ruleset_generate_vm_rules {
1959 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1960
1961 my $lc_direction = lc($direction);
1962
1963 my $in_accept = generate_nfqueue($options);
1964
1965 foreach my $rule (@$rules) {
1966 next if $rule->{iface} && $rule->{iface} ne $netid;
1967 next if !$rule->{enable} || $rule->{errors};
1968 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1969
1970 if ($rule->{type} eq 'group') {
1971 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1972 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1973 } else {
1974 next if $rule->{type} ne $lc_direction;
1975 eval {
1976 if ($direction eq 'OUT') {
1977 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1978 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
1979 undef, $cluster_conf, $vmfw_conf);
1980 } else {
1981 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1982 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
1983 undef, $cluster_conf, $vmfw_conf);
1984 }
1985 };
1986 warn $@ if $@;
1987 }
1988 }
1989 }
1990
1991 sub generate_nfqueue {
1992 my ($options) = @_;
1993
1994 if ($options->{ips}) {
1995 my $action = "NFQUEUE";
1996 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1997 if (defined($3) && defined($1)) {
1998 $action .= " --queue-balance $1:$3";
1999 } elsif (defined($1)) {
2000 $action .= " --queue-num $1";
2001 }
2002 }
2003 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
2004 return $action;
2005 } else {
2006 return "ACCEPT";
2007 }
2008 }
2009
2010 sub ruleset_generate_vm_ipsrules {
2011 my ($ruleset, $options, $direction, $iface) = @_;
2012
2013 if ($options->{ips} && $direction eq 'IN') {
2014 my $nfqueue = generate_nfqueue($options);
2015
2016 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
2017 ruleset_create_chain($ruleset, "PVEFW-IPS");
2018 }
2019
2020 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
2021 }
2022 }
2023
2024 sub generate_venet_rules_direction {
2025 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
2026
2027 my $lc_direction = lc($direction);
2028
2029 my $rules = $vmfw_conf->{rules};
2030
2031 my $options = $vmfw_conf->{options};
2032 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2033
2034 my $chain = "venet0-$vmid-$direction";
2035
2036 ruleset_create_vm_chain($ruleset, $chain, $ipversion, $options, undef, undef, $direction);
2037
2038 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
2039
2040 # implement policy
2041 my $policy;
2042
2043 if ($direction eq 'OUT') {
2044 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2045 } else {
2046 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2047 }
2048
2049 my $accept = generate_nfqueue($options);
2050 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
2051 ruleset_add_chain_policy($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2052
2053 if ($direction eq 'OUT') {
2054 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", $ipversion, {
2055 action => $chain,
2056 source => $ip,
2057 iface_in => 'venet0'});
2058 } else {
2059 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", $ipversion, {
2060 action => $chain,
2061 dest => $ip,
2062 iface_out => 'venet0'});
2063 }
2064 }
2065
2066 sub generate_tap_rules_direction {
2067 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2068
2069 my $lc_direction = lc($direction);
2070
2071 my $rules = $vmfw_conf->{rules};
2072
2073 my $options = $vmfw_conf->{options};
2074 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2075
2076 my $tapchain = "$iface-$direction";
2077
2078 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2079 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2080 if $vmfw_conf->{ipset}->{$ipfilter_name};
2081
2082 # create chain with mac and ip filter
2083 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2084
2085 if ($options->{enable}) {
2086 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2087
2088 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2089
2090 # implement policy
2091 my $policy;
2092
2093 if ($direction eq 'OUT') {
2094 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2095 } else {
2096 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2097 }
2098
2099 my $accept = generate_nfqueue($options);
2100 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
2101 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2102 } else {
2103 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
2104 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2105 }
2106
2107 # plug the tap chain to bridge chain
2108 if ($direction eq 'IN') {
2109 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
2110 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
2111 } else {
2112 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
2113 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
2114 }
2115 }
2116
2117 sub enable_host_firewall {
2118 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2119
2120 my $options = $hostfw_conf->{options};
2121 my $cluster_options = $cluster_conf->{options};
2122 my $rules = $hostfw_conf->{rules};
2123 my $cluster_rules = $cluster_conf->{rules};
2124
2125 # host inbound firewall
2126 my $chain = "PVEFW-HOST-IN";
2127 ruleset_create_chain($ruleset, $chain);
2128
2129 my $loglevel = get_option_log_level($options, "log_level_in");
2130
2131 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
2132
2133 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
2134 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2135 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2136
2137 # we use RETURN because we need to check also tap rules
2138 my $accept_action = 'RETURN';
2139
2140 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2141
2142 # add host rules first, so that cluster wide rules can be overwritten
2143 foreach my $rule (@$rules, @$cluster_rules) {
2144 next if !$rule->{enable} || $rule->{errors};
2145 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2146
2147 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2148
2149 eval {
2150 if ($rule->{type} eq 'group') {
2151 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2152 } elsif ($rule->{type} eq 'in') {
2153 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2154 { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2155 undef, $cluster_conf, $hostfw_conf);
2156 }
2157 };
2158 warn $@ if $@;
2159 delete $rule->{iface_in};
2160 }
2161
2162 # allow standard traffic for management ipset (includes cluster network)
2163 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management", $ipversion);
2164 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
2165 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
2166 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
2167 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2168 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
2169
2170 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2171 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2172
2173 # corosync
2174 if ($localnet && ($ipversion == $localnet_ver)) {
2175 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
2176 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
2177 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
2178 }
2179
2180 # implement input policy
2181 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2182 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2183
2184 # host outbound firewall
2185 $chain = "PVEFW-HOST-OUT";
2186 ruleset_create_chain($ruleset, $chain);
2187
2188 $loglevel = get_option_log_level($options, "log_level_out");
2189
2190 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
2191
2192 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
2193 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2194
2195 # we use RETURN because we may want to check other thigs later
2196 $accept_action = 'RETURN';
2197
2198 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2199
2200 # add host rules first, so that cluster wide rules can be overwritten
2201 foreach my $rule (@$rules, @$cluster_rules) {
2202 next if !$rule->{enable} || $rule->{errors};
2203 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2204
2205 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2206 eval {
2207 if ($rule->{type} eq 'group') {
2208 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2209 } elsif ($rule->{type} eq 'out') {
2210 ruleset_generate_rule($ruleset, $chain, $ipversion,
2211 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2212 undef, $cluster_conf, $hostfw_conf);
2213 }
2214 };
2215 warn $@ if $@;
2216 delete $rule->{iface_out};
2217 }
2218
2219 # allow standard traffic on cluster network
2220 if ($localnet && ($ipversion == $localnet_ver)) {
2221 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
2222 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
2223 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
2224 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2225
2226 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
2227 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
2228 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
2229 }
2230
2231 # implement output policy
2232 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2233 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2234
2235 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
2236 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
2237 }
2238
2239 sub generate_group_rules {
2240 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2241
2242 my $rules = $cluster_conf->{groups}->{$group};
2243
2244 if (!$rules) {
2245 warn "no such security group '$group'\n";
2246 $rules = []; # create empty chain
2247 }
2248
2249 my $chain = "GROUP-${group}-IN";
2250
2251 ruleset_create_chain($ruleset, $chain);
2252 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
2253
2254 foreach my $rule (@$rules) {
2255 next if $rule->{type} ne 'in';
2256 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2257 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2258 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2259 undef, $cluster_conf);
2260 }
2261
2262 $chain = "GROUP-${group}-OUT";
2263
2264 ruleset_create_chain($ruleset, $chain);
2265 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
2266
2267 foreach my $rule (@$rules) {
2268 next if $rule->{type} ne 'out';
2269 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2270 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2271 # check also other tap rules later
2272 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2273 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" },
2274 undef, $cluster_conf);
2275 }
2276 }
2277
2278 my $MAX_NETS = 32;
2279 my $valid_netdev_names = {};
2280 for (my $i = 0; $i < $MAX_NETS; $i++) {
2281 $valid_netdev_names->{"net$i"} = 1;
2282 }
2283
2284 sub parse_fw_rule {
2285 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2286
2287 my $orig_line = $line;
2288
2289 my $rule = {};
2290
2291 # we can add single line comments to the end of the rule
2292 if ($line =~ s/#\s*(.*?)\s*$//) {
2293 $rule->{comment} = decode('utf8', $1);
2294 }
2295
2296 # we can disable a rule when prefixed with '|'
2297
2298 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2299
2300 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2301 die "unable to parse rule: $line\n";
2302
2303 $rule->{type} = lc($1);
2304 $rule->{action} = $2;
2305
2306 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2307 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2308 $rule->{macro} = $1;
2309 $rule->{action} = $2;
2310 }
2311 }
2312
2313 while (length($line)) {
2314 if ($line =~ s/^-i (\S+)\s*//) {
2315 $rule->{iface} = $1;
2316 next;
2317 }
2318
2319 last if $rule->{type} eq 'group';
2320
2321 if ($line =~ s/^-p (\S+)\s*//) {
2322 $rule->{proto} = $1;
2323 next;
2324 }
2325
2326 if ($line =~ s/^-dport (\S+)\s*//) {
2327 $rule->{dport} = $1;
2328 next;
2329 }
2330
2331 if ($line =~ s/^-sport (\S+)\s*//) {
2332 $rule->{sport} = $1;
2333 next;
2334 }
2335 if ($line =~ s/^-source (\S+)\s*//) {
2336 $rule->{source} = $1;
2337 next;
2338 }
2339 if ($line =~ s/^-dest (\S+)\s*//) {
2340 $rule->{dest} = $1;
2341 next;
2342 }
2343
2344 last;
2345 }
2346
2347 die "unable to parse rule parameters: $line\n" if length($line);
2348
2349 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2350 if ($verbose && $rule->{errors}) {
2351 warn "$prefix - errors in rule parameters: $orig_line\n";
2352 foreach my $p (keys %{$rule->{errors}}) {
2353 warn " $p: $rule->{errors}->{$p}\n";
2354 }
2355 }
2356
2357 return $rule;
2358 }
2359
2360 sub parse_vmfw_option {
2361 my ($line) = @_;
2362
2363 my ($opt, $value);
2364
2365 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2366
2367 if ($line =~ m/^(enable|dhcp|ndp|macfilter|ips):\s*(0|1)\s*$/i) {
2368 $opt = lc($1);
2369 $value = int($2);
2370 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2371 $opt = lc($1);
2372 $value = $2 ? lc($3) : '';
2373 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2374 $opt = lc($1);
2375 $value = uc($3);
2376 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2377 $opt = lc($1);
2378 $value = $2;
2379 } else {
2380 die "can't parse option '$line'\n"
2381 }
2382
2383 return ($opt, $value);
2384 }
2385
2386 sub parse_hostfw_option {
2387 my ($line) = @_;
2388
2389 my ($opt, $value);
2390
2391 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2392
2393 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2394 $opt = lc($1);
2395 $value = int($2);
2396 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2397 $opt = lc($1);
2398 $value = $2 ? lc($3) : '';
2399 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2400 $opt = lc($1);
2401 $value = int($2);
2402 } else {
2403 die "can't parse option '$line'\n"
2404 }
2405
2406 return ($opt, $value);
2407 }
2408
2409 sub parse_clusterfw_option {
2410 my ($line) = @_;
2411
2412 my ($opt, $value);
2413
2414 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2415 $opt = lc($1);
2416 $value = int($2);
2417 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2418 $opt = lc($1);
2419 $value = uc($3);
2420 } else {
2421 die "can't parse option '$line'\n"
2422 }
2423
2424 return ($opt, $value);
2425 }
2426
2427 sub resolve_alias {
2428 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2429
2430 my $alias = lc($cidr);
2431 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2432 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2433
2434 die "no such alias '$cidr'\n" if !$e;;
2435
2436 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2437 }
2438
2439 sub parse_ip_or_cidr {
2440 my ($cidr) = @_;
2441
2442 my $ipversion;
2443
2444 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2445 $cidr =~ s|/128$||;
2446 $ipversion = 6;
2447 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2448 $cidr =~ s|/32$||;
2449 $ipversion = 4;
2450 } else {
2451 die "value does not look like a valid IP address or CIDR network\n";
2452 }
2453
2454 return wantarray ? ($cidr, $ipversion) : $cidr;
2455 }
2456
2457 sub parse_alias {
2458 my ($line) = @_;
2459
2460 # we can add single line comments to the end of the line
2461 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2462
2463 if ($line =~ m/^(\S+)\s(\S+)$/) {
2464 my ($name, $cidr) = ($1, $2);
2465 my $ipversion;
2466
2467 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2468
2469 my $data = {
2470 name => $name,
2471 cidr => $cidr,
2472 ipversion => $ipversion,
2473 };
2474 $data->{comment} = $comment if $comment;
2475 return $data;
2476 }
2477
2478 return undef;
2479 }
2480
2481 sub generic_fw_config_parser {
2482 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2483
2484 my $section;
2485 my $group;
2486
2487 my $res = $empty_conf;
2488
2489 while (defined(my $line = <$fh>)) {
2490 next if $line =~ m/^#/;
2491 next if $line =~ m/^\s*$/;
2492
2493 chomp $line;
2494
2495 my $linenr = $fh->input_line_number();
2496 my $prefix = "$filename (line $linenr)";
2497
2498 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2499 $section = 'options';
2500 next;
2501 }
2502
2503 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2504 $section = 'aliases';
2505 next;
2506 }
2507
2508 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2509 $section = 'groups';
2510 $group = lc($1);
2511 my $comment = $2;
2512 eval {
2513 die "security group name too long\n" if length($group) > $max_group_name_length;
2514 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2515 };
2516 if (my $err = $@) {
2517 ($section, $group, $comment) = undef;
2518 warn "$prefix: $err";
2519 next;
2520 }
2521
2522 $res->{$section}->{$group} = [];
2523 $res->{group_comments}->{$group} = decode('utf8', $comment)
2524 if $comment;
2525 next;
2526 }
2527
2528 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2529 $section = 'rules';
2530 next;
2531 }
2532
2533 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2534 $section = 'ipset';
2535 $group = lc($1);
2536 my $comment = $2;
2537 eval {
2538 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2539 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2540 };
2541 if (my $err = $@) {
2542 ($section, $group, $comment) = undef;
2543 warn "$prefix: $err";
2544 next;
2545 }
2546
2547 $res->{$section}->{$group} = [];
2548 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2549 if $comment;
2550 next;
2551 }
2552
2553 if (!$section) {
2554 warn "$prefix: skip line - no section\n";
2555 next;
2556 }
2557
2558 if ($section eq 'options') {
2559 eval {
2560 my ($opt, $value);
2561 if ($rule_env eq 'cluster') {
2562 ($opt, $value) = parse_clusterfw_option($line);
2563 } elsif ($rule_env eq 'host') {
2564 ($opt, $value) = parse_hostfw_option($line);
2565 } else {
2566 ($opt, $value) = parse_vmfw_option($line);
2567 }
2568 $res->{options}->{$opt} = $value;
2569 };
2570 warn "$prefix: $@" if $@;
2571 } elsif ($section eq 'aliases') {
2572 eval {
2573 my $data = parse_alias($line);
2574 $res->{aliases}->{lc($data->{name})} = $data;
2575 };
2576 warn "$prefix: $@" if $@;
2577 } elsif ($section eq 'rules') {
2578 my $rule;
2579 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2580 if (my $err = $@) {
2581 warn "$prefix: $err";
2582 next;
2583 }
2584 push @{$res->{$section}}, $rule;
2585 } elsif ($section eq 'groups') {
2586 my $rule;
2587 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
2588 if (my $err = $@) {
2589 warn "$prefix: $err";
2590 next;
2591 }
2592 push @{$res->{$section}->{$group}}, $rule;
2593 } elsif ($section eq 'ipset') {
2594 # we can add single line comments to the end of the rule
2595 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2596
2597 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2598 my $nomatch = $1;
2599 my $cidr = $2;
2600 my $errors;
2601
2602 if ($nomatch && !$feature_ipset_nomatch) {
2603 $errors->{nomatch} = "nomatch not supported by kernel";
2604 }
2605
2606 eval {
2607 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2608 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2609 } else {
2610 $cidr = parse_ip_or_cidr($cidr);
2611 }
2612 };
2613 if (my $err = $@) {
2614 chomp $err;
2615 $errors->{cidr} = $err;
2616 }
2617
2618 my $entry = { cidr => $cidr };
2619 $entry->{nomatch} = 1 if $nomatch;
2620 $entry->{comment} = $comment if $comment;
2621 $entry->{errors} = $errors if $errors;
2622
2623 if ($verbose && $errors) {
2624 warn "$prefix - errors in ipset '$group': $line\n";
2625 foreach my $p (keys %{$errors}) {
2626 warn " $p: $errors->{$p}\n";
2627 }
2628 }
2629
2630 push @{$res->{$section}->{$group}}, $entry;
2631 } else {
2632 warn "$prefix: skip line - unknown section\n";
2633 next;
2634 }
2635 }
2636
2637 return $res;
2638 }
2639
2640 sub parse_hostfw_config {
2641 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2642
2643 my $empty_conf = { rules => [], options => {}};
2644
2645 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
2646 }
2647
2648 sub parse_vmfw_config {
2649 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2650
2651 my $empty_conf = {
2652 rules => [],
2653 options => {},
2654 aliases => {},
2655 ipset => {} ,
2656 ipset_comments => {},
2657 };
2658
2659 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2660 }
2661
2662 sub parse_clusterfw_config {
2663 my ($filename, $fh, $verbose) = @_;
2664
2665 my $section;
2666 my $group;
2667
2668 my $empty_conf = {
2669 rules => [],
2670 options => {},
2671 aliases => {},
2672 groups => {},
2673 group_comments => {},
2674 ipset => {} ,
2675 ipset_comments => {},
2676 };
2677
2678 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
2679 }
2680
2681 sub run_locked {
2682 my ($code, @param) = @_;
2683
2684 my $timeout = 10;
2685
2686 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2687
2688 die $@ if $@;
2689
2690 return $res;
2691 }
2692
2693 sub read_local_vm_config {
2694
2695 my $openvz = {};
2696 my $qemu = {};
2697
2698 my $vmdata = { openvz => $openvz, qemu => $qemu };
2699
2700 my $vmlist = PVE::Cluster::get_vmlist();
2701 return $vmdata if !$vmlist || !$vmlist->{ids};
2702 my $ids = $vmlist->{ids};
2703
2704 foreach my $vmid (keys %$ids) {
2705 next if !$vmid; # skip VE0
2706 my $d = $ids->{$vmid};
2707 next if !$d->{node} || $d->{node} ne $nodename;
2708 next if !$d->{type};
2709 if ($d->{type} eq 'openvz') {
2710 if ($have_pve_manager) {
2711 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2712 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2713 $openvz->{$vmid} = $conf;
2714 }
2715 }
2716 } elsif ($d->{type} eq 'qemu') {
2717 if ($have_qemu_server) {
2718 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2719 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2720 $qemu->{$vmid} = $conf;
2721 }
2722 }
2723 }
2724 }
2725
2726 return $vmdata;
2727 };
2728
2729 sub load_vmfw_conf {
2730 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2731
2732 my $vmfw_conf = {};
2733
2734 $dir = $pvefw_conf_dir if !defined($dir);
2735
2736 my $filename = "$dir/$vmid.fw";
2737 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2738 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2739 $vmfw_conf->{vmid} = $vmid;
2740 }
2741
2742 return $vmfw_conf;
2743 }
2744
2745 my $format_rules = sub {
2746 my ($rules, $allow_iface) = @_;
2747
2748 my $raw = '';
2749
2750 foreach my $rule (@$rules) {
2751 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2752 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2753 $raw .= uc($rule->{type});
2754 if ($rule->{macro}) {
2755 $raw .= " $rule->{macro}($rule->{action})";
2756 } else {
2757 $raw .= " " . $rule->{action};
2758 }
2759 if ($allow_iface && $rule->{iface}) {
2760 $raw .= " -i $rule->{iface}";
2761 }
2762
2763 if ($rule->{type} ne 'group') {
2764 $raw .= " -source $rule->{source}" if $rule->{source};
2765 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2766 $raw .= " -p $rule->{proto}" if $rule->{proto};
2767 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2768 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2769 }
2770
2771 $raw .= " # " . encode('utf8', $rule->{comment})
2772 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2773 $raw .= "\n";
2774 } else {
2775 die "unknown rule type '$rule->{type}'";
2776 }
2777 }
2778
2779 return $raw;
2780 };
2781
2782 my $format_options = sub {
2783 my ($options) = @_;
2784
2785 my $raw = '';
2786
2787 $raw .= "[OPTIONS]\n\n";
2788 foreach my $opt (keys %$options) {
2789 $raw .= "$opt: $options->{$opt}\n";
2790 }
2791 $raw .= "\n";
2792
2793 return $raw;
2794 };
2795
2796 my $format_aliases = sub {
2797 my ($aliases) = @_;
2798
2799 my $raw = '';
2800
2801 $raw .= "[ALIASES]\n\n";
2802 foreach my $k (keys %$aliases) {
2803 my $e = $aliases->{$k};
2804 $raw .= "$e->{name} $e->{cidr}";
2805 $raw .= " # " . encode('utf8', $e->{comment})
2806 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2807 $raw .= "\n";
2808 }
2809 $raw .= "\n";
2810
2811 return $raw;
2812 };
2813
2814 my $format_ipsets = sub {
2815 my ($fw_conf) = @_;
2816
2817 my $raw = '';
2818
2819 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2820 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2821 my $utf8comment = encode('utf8', $comment);
2822 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2823 } else {
2824 $raw .= "[IPSET $ipset]\n\n";
2825 }
2826 my $options = $fw_conf->{ipset}->{$ipset};
2827
2828 my $nethash = {};
2829 foreach my $entry (@$options) {
2830 $nethash->{$entry->{cidr}} = $entry;
2831 }
2832
2833 foreach my $cidr (sort keys %$nethash) {
2834 my $entry = $nethash->{$cidr};
2835 my $line = $entry->{nomatch} ? '!' : '';
2836 $line .= $entry->{cidr};
2837 $line .= " # " . encode('utf8', $entry->{comment})
2838 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2839 $raw .= "$line\n";
2840 }
2841
2842 $raw .= "\n";
2843 }
2844
2845 return $raw;
2846 };
2847
2848 sub save_vmfw_conf {
2849 my ($vmid, $vmfw_conf) = @_;
2850
2851 my $raw = '';
2852
2853 my $options = $vmfw_conf->{options};
2854 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2855
2856 my $aliases = $vmfw_conf->{aliases};
2857 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2858
2859 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2860
2861 my $rules = $vmfw_conf->{rules} || [];
2862 if ($rules && scalar(@$rules)) {
2863 $raw .= "[RULES]\n\n";
2864 $raw .= &$format_rules($rules, 1);
2865 $raw .= "\n";
2866 }
2867
2868 mkdir $pvefw_conf_dir;
2869
2870 my $filename = "$pvefw_conf_dir/$vmid.fw";
2871 PVE::Tools::file_set_contents($filename, $raw);
2872 }
2873
2874 sub read_vm_firewall_configs {
2875 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2876
2877 my $vmfw_configs = {};
2878
2879 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2880 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
2881 next if !$vmfw_conf->{options}; # skip if file does not exists
2882 $vmfw_configs->{$vmid} = $vmfw_conf;
2883 }
2884 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2885 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
2886 next if !$vmfw_conf->{options}; # skip if file does not exists
2887 $vmfw_configs->{$vmid} = $vmfw_conf;
2888 }
2889
2890 return $vmfw_configs;
2891 }
2892
2893 sub get_option_log_level {
2894 my ($options, $k) = @_;
2895
2896 my $v = $options->{$k};
2897 $v = $default_log_level if !defined($v);
2898
2899 return undef if $v eq '' || $v eq 'nolog';
2900
2901 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2902
2903 return $v if ($v >= 0) && ($v <= 7);
2904
2905 warn "unknown log level ($k = '$v')\n";
2906
2907 return undef;
2908 }
2909
2910 sub generate_std_chains {
2911 my ($ruleset, $options, $ipversion) = @_;
2912
2913 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2914
2915 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2916
2917 my $chain;
2918
2919 if ($ipversion == 4) {
2920 # same as shorewall smurflog.
2921 $chain = 'PVEFW-smurflog';
2922 $std_chains->{$chain} = [];
2923
2924 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2925 push @{$std_chains->{$chain}}, "-j DROP";
2926 }
2927
2928 # same as shorewall logflags action.
2929 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2930 $chain = 'PVEFW-logflags';
2931 $std_chains->{$chain} = [];
2932
2933 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2934 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2935 push @{$std_chains->{$chain}}, "-j DROP";
2936
2937 foreach my $chain (keys %$std_chains) {
2938 ruleset_create_chain($ruleset, $chain);
2939 foreach my $rule (@{$std_chains->{$chain}}) {
2940 if (ref($rule)) {
2941 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
2942 } else {
2943 ruleset_addrule($ruleset, $chain, $rule);
2944 }
2945 }
2946 }
2947 }
2948
2949 sub generate_ipset_chains {
2950 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_; #fixme
2951
2952 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2953
2954 my $options = $fw_conf->{ipset}->{$ipset};
2955
2956 # remove duplicates
2957 my $nethash = {};
2958 foreach my $entry (@$options) {
2959 next if $entry->{errors}; # skip entries with errors
2960 eval {
2961 my ($cidr, $ver);
2962 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2963 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2964 } else {
2965 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
2966 }
2967 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2968 if ($ver == 6) {
2969 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2970 $cidr = inet_ntop(AF_INET6, $ipv6);
2971 $cidr =~ s|/128$||;
2972 } else {
2973 $cidr =~ s|/32$||;
2974 }
2975
2976 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2977 };
2978 warn $@ if $@;
2979 }
2980
2981 foreach my $ipversion (4, 6) {
2982 my $data = $nethash->{$ipversion};
2983
2984 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
2985
2986 my $hashsize = scalar(@$options);
2987 if ($hashsize <= 64) {
2988 $hashsize = 64;
2989 } else {
2990 $hashsize = round_powerof2($hashsize);
2991 }
2992
2993 my $family = $ipversion == "6" ? "inet6" : "inet";
2994
2995 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
2996
2997 foreach my $cidr (sort keys %$data) {
2998 my $entry = $data->{$cidr};
2999
3000 my $cmd = "add $name $cidr";
3001 if ($entry->{nomatch}) {
3002 if ($feature_ipset_nomatch) {
3003 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3004 } else {
3005 warn "ignore !$cidr - nomatch not supported by kernel\n";
3006 }
3007 } else {
3008 push @{$ipset_ruleset->{$name}}, $cmd;
3009 }
3010 }
3011 }
3012 }
3013 }
3014
3015 sub round_powerof2 {
3016 my ($int) = @_;
3017
3018 $int--;
3019 $int |= $int >> $_ foreach (1,2,4,8,16);
3020 return ++$int;
3021 }
3022
3023 sub load_clusterfw_conf {
3024 my ($filename, $verbose) = @_;
3025
3026 $filename = $clusterfw_conf_filename if !defined($filename);
3027
3028 my $cluster_conf = {};
3029 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3030 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3031 }
3032
3033 return $cluster_conf;
3034 }
3035
3036 sub save_clusterfw_conf {
3037 my ($cluster_conf) = @_;
3038
3039 my $raw = '';
3040
3041 my $options = $cluster_conf->{options};
3042 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3043
3044 my $aliases = $cluster_conf->{aliases};
3045 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3046
3047 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3048
3049 my $rules = $cluster_conf->{rules};
3050 if ($rules && scalar(@$rules)) {
3051 $raw .= "[RULES]\n\n";
3052 $raw .= &$format_rules($rules, 1);
3053 $raw .= "\n";
3054 }
3055
3056 if ($cluster_conf->{groups}) {
3057 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3058 my $rules = $cluster_conf->{groups}->{$group};
3059 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3060 my $utf8comment = encode('utf8', $comment);
3061 $raw .= "[group $group] # $utf8comment\n\n";
3062 } else {
3063 $raw .= "[group $group]\n\n";
3064 }
3065
3066 $raw .= &$format_rules($rules, 0);
3067 $raw .= "\n";
3068 }
3069 }
3070
3071 mkdir $pvefw_conf_dir;
3072 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3073 }
3074
3075 sub load_hostfw_conf {
3076 my ($cluster_conf, $filename, $verbose) = @_;
3077
3078 $filename = $hostfw_conf_filename if !defined($filename);
3079
3080 my $hostfw_conf = {};
3081 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3082 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3083 }
3084 return $hostfw_conf;
3085 }
3086
3087 sub save_hostfw_conf {
3088 my ($hostfw_conf) = @_;
3089
3090 my $raw = '';
3091
3092 my $options = $hostfw_conf->{options};
3093 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3094
3095 my $rules = $hostfw_conf->{rules};
3096 if ($rules && scalar(@$rules)) {
3097 $raw .= "[RULES]\n\n";
3098 $raw .= &$format_rules($rules, 1);
3099 $raw .= "\n";
3100 }
3101
3102 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3103 }
3104
3105 sub compile {
3106 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3107
3108 my $vmfw_configs;
3109
3110 if ($vmdata) { # test mode
3111 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3112 my $filename = "$testdir/cluster.fw";
3113 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3114
3115 $filename = "$testdir/host.fw";
3116 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3117
3118 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3119 } else { # normal operation
3120 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3121
3122 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3123
3124 $vmdata = read_local_vm_config();
3125 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3126 }
3127
3128 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3129 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3130
3131 return ($ruleset, $ipset_ruleset, $rulesetv6);
3132 }
3133
3134 sub compile_iptables_filter {
3135 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3136
3137 $cluster_conf->{ipset}->{venet0} = [];
3138 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0', $ipversion);
3139
3140 my $localnet;
3141 if ($cluster_conf->{aliases}->{local_network}) {
3142 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3143 } else {
3144 my $localnet_ver;
3145 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3146
3147 $cluster_conf->{aliases}->{local_network} = {
3148 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
3149 }
3150
3151 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3152
3153 return ({}, {}) if !$cluster_conf->{options}->{enable};
3154
3155 my $ruleset = {};
3156
3157 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3158 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3159
3160 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3161
3162 my $hostfw_options = $hostfw_conf->{options} || {};
3163
3164 # fixme: what log level should we use here?
3165 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3166
3167 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3168
3169
3170 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
3171 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3172 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3173
3174 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3175 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3176
3177 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3178
3179 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3180 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3181
3182 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
3183 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3184
3185 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3186
3187 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3188
3189 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3190
3191 my $ipset_ruleset = {};
3192
3193 if ($hostfw_enable) {
3194 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3195 warn $@ if $@; # just to be sure - should not happen
3196 }
3197
3198 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3199
3200 # generate firewall rules for QEMU VMs
3201 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3202 eval {
3203 my $conf = $vmdata->{qemu}->{$vmid};
3204 my $vmfw_conf = $vmfw_configs->{$vmid};
3205 return if !$vmfw_conf;
3206
3207 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3208
3209 foreach my $netid (keys %$conf) {
3210 next if $netid !~ m/^net(\d+)$/;
3211 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3212 next if !$net->{firewall};
3213 my $iface = "tap${vmid}i$1";
3214
3215 my $macaddr = $net->{macaddr};
3216 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3217 $vmfw_conf, $vmid, 'IN', $ipversion);
3218 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3219 $vmfw_conf, $vmid, 'OUT', $ipversion);
3220 }
3221 };
3222 warn $@ if $@; # just to be sure - should not happen
3223 }
3224
3225 # generate firewall rules for OpenVZ containers
3226 foreach my $vmid (keys %{$vmdata->{openvz}}) {
3227 eval {
3228 my $conf = $vmdata->{openvz}->{$vmid};
3229
3230 my $vmfw_conf = $vmfw_configs->{$vmid};
3231 return if !$vmfw_conf;
3232
3233 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3234
3235 if ($vmfw_conf->{options}->{enable}) {
3236 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3237 my $ip = $conf->{ip_address}->{value};
3238 $ip =~ s/\s+/,/g;
3239
3240 my @ips = ();
3241
3242 foreach my $singleip (split(',', $ip)) {
3243 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3244 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3245 push @ips, $singleip if $singleip_ver == $ipversion;
3246 }
3247
3248 if (scalar(@ips)) {
3249 my $ip_list = join(',', @ips);
3250 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN', $ipversion);
3251 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT', $ipversion);
3252 }
3253 }
3254 }
3255
3256 if ($conf->{netif} && $conf->{netif}->{value}) {
3257 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3258 foreach my $netid (keys %$netif) {
3259 my $d = $netif->{$netid};
3260 my $bridge = $d->{bridge};
3261 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3262 my $macaddr = $d->{mac};
3263 my $iface = $d->{host_ifname};
3264 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3265 $vmfw_conf, $vmid, 'IN', $ipversion);
3266 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3267 $vmfw_conf, $vmid, 'OUT', $ipversion);
3268 }
3269 }
3270 };
3271 warn $@ if $@; # just to be sure - should not happen
3272 }
3273
3274 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3275 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3276 }
3277
3278 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3279
3280 return ($ruleset, $ipset_ruleset);
3281 }
3282
3283 sub get_ruleset_status {
3284 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3285
3286 my $statushash = {};
3287
3288 foreach my $chain (sort keys %$ruleset) {
3289 my $sig = &$digest_fn($ruleset->{$chain});
3290
3291 $statushash->{$chain}->{sig} = $sig;
3292
3293 my $oldsig = $active_chains->{$chain};
3294 if (!defined($oldsig)) {
3295 $statushash->{$chain}->{action} = 'create';
3296 } else {
3297 if ($oldsig eq $sig) {
3298 $statushash->{$chain}->{action} = 'exists';
3299 } else {
3300 $statushash->{$chain}->{action} = 'update';
3301 }
3302 }
3303 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3304 foreach my $cmd (@{$ruleset->{$chain}}) {
3305 print "\t$cmd\n" if $verbose;
3306 }
3307 }
3308
3309 foreach my $chain (sort keys %$active_chains) {
3310 if (!defined($ruleset->{$chain})) {
3311 my $sig = $active_chains->{$chain};
3312 $statushash->{$chain}->{action} = 'delete';
3313 $statushash->{$chain}->{sig} = $sig;
3314 print "delete $chain ($sig)\n" if $verbose;
3315 }
3316 }
3317
3318 return $statushash;
3319 }
3320
3321 sub print_sig_rule {
3322 my ($chain, $sig) = @_;
3323
3324 # We just use this to store a SHA1 checksum used to detect changes
3325 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3326 }
3327
3328 sub get_ruleset_cmdlist {
3329 my ($ruleset, $verbose, $iptablescmd) = @_;
3330
3331 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3332
3333 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3334 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3335
3336 # create missing chains first
3337 foreach my $chain (sort keys %$ruleset) {
3338 my $stat = $statushash->{$chain};
3339 die "internal error" if !$stat;
3340 next if $stat->{action} ne 'create';
3341
3342 $cmdlist .= ":$chain - [0:0]\n";
3343 }
3344
3345 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3346 my $chain = "PVEFW-$h";
3347 if ($ruleset->{$chain} && !$hooks->{$h}) {
3348 $cmdlist .= "-A $h -j $chain\n";
3349 }
3350 }
3351
3352 foreach my $chain (sort keys %$ruleset) {
3353 my $stat = $statushash->{$chain};
3354 die "internal error" if !$stat;
3355
3356 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3357 $cmdlist .= "-F $chain\n";
3358 foreach my $cmd (@{$ruleset->{$chain}}) {
3359 $cmdlist .= "$cmd\n";
3360 }
3361 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3362 } elsif ($stat->{action} eq 'delete') {
3363 die "internal error"; # this should not happen
3364 } elsif ($stat->{action} eq 'exists') {
3365 # do nothing
3366 } else {
3367 die "internal error - unknown status '$stat->{action}'";
3368 }
3369 }
3370
3371 foreach my $chain (keys %$statushash) {
3372 next if $statushash->{$chain}->{action} ne 'delete';
3373 $cmdlist .= "-F $chain\n";
3374 }
3375 foreach my $chain (keys %$statushash) {
3376 next if $statushash->{$chain}->{action} ne 'delete';
3377 next if $chain eq 'PVEFW-INPUT';
3378 next if $chain eq 'PVEFW-OUTPUT';
3379 next if $chain eq 'PVEFW-FORWARD';
3380 $cmdlist .= "-X $chain\n";
3381 }
3382
3383 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
3384
3385 $cmdlist .= "COMMIT\n";
3386
3387 return wantarray ? ($cmdlist, $changes) : $cmdlist;
3388 }
3389
3390 sub get_ipset_cmdlist {
3391 my ($ruleset, $verbose) = @_;
3392
3393 my $cmdlist = "";
3394
3395 my $delete_cmdlist = "";
3396
3397 my $active_chains = ipset_get_chains();
3398 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
3399
3400 # remove stale _swap chains
3401 foreach my $chain (keys %$active_chains) {
3402 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3403 $cmdlist .= "destroy $chain\n";
3404 }
3405 }
3406
3407 foreach my $chain (keys %$ruleset) {
3408 my $stat = $statushash->{$chain};
3409 die "internal error" if !$stat;
3410
3411 if ($stat->{action} eq 'create') {
3412 foreach my $cmd (@{$ruleset->{$chain}}) {
3413 $cmdlist .= "$cmd\n";
3414 }
3415 }
3416 }
3417
3418 foreach my $chain (keys %$ruleset) {
3419 my $stat = $statushash->{$chain};
3420 die "internal error" if !$stat;
3421
3422 if ($stat->{action} eq 'update') {
3423 my $chain_swap = $chain."_swap";
3424
3425 foreach my $cmd (@{$ruleset->{$chain}}) {
3426 $cmd =~ s/$chain/$chain_swap/;
3427 $cmdlist .= "$cmd\n";
3428 }
3429 $cmdlist .= "swap $chain_swap $chain\n";
3430 $cmdlist .= "flush $chain_swap\n";
3431 $cmdlist .= "destroy $chain_swap\n";
3432 }
3433 }
3434
3435 # the remove unused chains
3436 foreach my $chain (keys %$statushash) {
3437 next if $statushash->{$chain}->{action} ne 'delete';
3438
3439 $delete_cmdlist .= "flush $chain\n";
3440 $delete_cmdlist .= "destroy $chain\n";
3441 }
3442
3443 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
3444
3445 return ($cmdlist, $delete_cmdlist, $changes);
3446 }
3447
3448 sub apply_ruleset {
3449 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3450
3451 enable_bridge_firewall();
3452
3453 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3454 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
3455
3456 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
3457 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
3458
3459 if ($verbose) {
3460 if ($ipset_changes) {
3461 print "ipset changes:\n";
3462 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3463 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3464 }
3465
3466 if ($changes) {
3467 print "iptables changes:\n";
3468 print $cmdlist;
3469 }
3470
3471 if ($changesv6) {
3472 print "ip6tables changes:\n";
3473 print $cmdlistv6;
3474 }
3475 }
3476
3477 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3478 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3479
3480 ipset_restore_cmdlist($ipset_create_cmdlist);
3481
3482 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3483 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3484
3485 iptables_restore_cmdlist($cmdlist);
3486
3487 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3488 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3489
3490 ip6tables_restore_cmdlist($cmdlistv6);
3491
3492 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3493 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3494
3495 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3496
3497 # test: re-read status and check if everything is up to date
3498 my $active_chains = iptables_get_chains();
3499 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3500
3501 my $errors;
3502 foreach my $chain (sort keys %$ruleset) {
3503 my $stat = $statushash->{$chain};
3504 if ($stat->{action} ne 'exists') {
3505 warn "unable to update chain '$chain'\n";
3506 $errors = 1;
3507 }
3508 }
3509
3510 my $active_chainsv6 = iptables_get_chains("ip6tables");
3511 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3512
3513 foreach my $chain (sort keys %$rulesetv6) {
3514 my $stat = $statushashv6->{$chain};
3515 if ($stat->{action} ne 'exists') {
3516 warn "unable to update chain '$chain'\n";
3517 $errors = 1;
3518 }
3519 }
3520
3521 die "unable to apply firewall changes\n" if $errors;
3522
3523 update_nf_conntrack_max($hostfw_conf);
3524
3525 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3526
3527 }
3528
3529 sub update_nf_conntrack_max {
3530 my ($hostfw_conf) = @_;
3531
3532 my $max = 65536; # reasonable default
3533
3534 my $options = $hostfw_conf->{options} || {};
3535
3536 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3537 $max = $options->{nf_conntrack_max};
3538 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3539 }
3540
3541 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3542 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3543
3544 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3545
3546 if ($current != $max) {
3547 my $hashsize = int($max/4);
3548 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3549 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3550 }
3551 }
3552
3553 sub update_nf_conntrack_tcp_timeout_established {
3554 my ($hostfw_conf) = @_;
3555
3556 my $options = $hostfw_conf->{options} || {};
3557
3558 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3559
3560 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3561 }
3562
3563 sub remove_pvefw_chains {
3564
3565 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3566 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3567 PVE::Firewall::remove_pvefw_chains_ipset();
3568
3569 }
3570
3571 sub remove_pvefw_chains_iptables {
3572 my ($iptablescmd) = @_;
3573
3574 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
3575 my $cmdlist = "*filter\n";
3576
3577 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3578 if ($hooks->{$h}) {
3579 $cmdlist .= "-D $h -j PVEFW-$h\n";
3580 }
3581 }
3582
3583 foreach my $chain (keys %$chash) {
3584 $cmdlist .= "-F $chain\n";
3585 }
3586
3587 foreach my $chain (keys %$chash) {
3588 $cmdlist .= "-X $chain\n";
3589 }
3590 $cmdlist .= "COMMIT\n";
3591
3592 if($iptablescmd eq "ip6tables") {
3593 ip6tables_restore_cmdlist($cmdlist);
3594 } else {
3595 iptables_restore_cmdlist($cmdlist);
3596 }
3597 }
3598
3599 sub remove_pvefw_chains_ipset {
3600
3601 my $ipset_chains = ipset_get_chains();
3602
3603 my $cmdlist = "";
3604
3605 foreach my $chain (keys %$ipset_chains) {
3606 $cmdlist .= "flush $chain\n";
3607 $cmdlist .= "destroy $chain\n";
3608 }
3609
3610 ipset_restore_cmdlist($cmdlist) if $cmdlist;
3611 }
3612
3613 sub init {
3614 my $cluster_conf = load_clusterfw_conf();
3615 my $cluster_options = $cluster_conf->{options};
3616 my $enable = $cluster_options->{enable};
3617
3618 return if !$enable;
3619
3620 # load required modules here
3621 }
3622
3623 sub update {
3624 my $code = sub {
3625
3626 my $cluster_conf = load_clusterfw_conf();
3627 my $cluster_options = $cluster_conf->{options};
3628
3629 if (!$cluster_options->{enable}) {
3630 PVE::Firewall::remove_pvefw_chains();
3631 return;
3632 }
3633
3634 my $hostfw_conf = load_hostfw_conf($cluster_conf);
3635
3636 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
3637
3638 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
3639 };
3640
3641 run_locked($code);
3642 }
3643
3644 1;