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