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