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