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