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