]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
iptables address matching in own subroutine
[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 # generate a src or dst match
1803 # $dir(ection) is either d or s
1804 sub ipt_gen_src_or_dst_match {
1805 my ($adr, $dir, $ipversion, $cluster_conf, $fw_conf) = @_;
1806
1807 my $srcdst;
1808 if ($dir eq 's') {
1809 $srcdst = "src";
1810 } elsif ($dir eq 'd') {
1811 $srcdst = "dst";
1812 } else {
1813 die "ipt_gen_src_or_dst_match: invalid direction $dir \n";
1814 }
1815
1816 my $match;
1817 if ($adr =~ m/^\+/) {
1818 if ($adr =~ m/^\+(${ipset_name_pattern})$/) {
1819 my $name = $1;
1820 my $ipset_chain;
1821 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
1822 $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
1823 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
1824 $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
1825 } else {
1826 die "no such ipset '$name'\n";
1827 }
1828 $match = "-m set --match-set ${ipset_chain} ${srcdst}";
1829 } else {
1830 die "invalid security group name '$adr'\n";
1831 }
1832 } elsif ($adr =~ m/^${ip_alias_pattern}$/){
1833 my $alias = lc($adr);
1834 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
1835 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1836 die "no such alias '$adr'\n" if !$e;
1837 $match = "-${dir} $e->{cidr}";
1838 } elsif ($adr =~ m/\-/){
1839 $match = "-m iprange --${srcdst}-range $adr";
1840 } else {
1841 $match = "-${dir} $adr";
1842 }
1843
1844 return $match;
1845 }
1846
1847 sub ruleset_generate_match {
1848 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1849
1850 return if defined($rule->{enable}) && !$rule->{enable};
1851 return if $rule->{errors};
1852
1853 return $rule->{match} if defined $rule->{match};
1854
1855 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1856
1857 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}, 1) : 0;
1858 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}, 0) : 0;
1859
1860 my @cmd = ();
1861
1862 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1863 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1864
1865 my $source = $rule->{source};
1866 my $dest = $rule->{dest};
1867
1868 push @cmd, ipt_gen_src_or_dst_match($source, 's', $ipversion, $cluster_conf, $fw_conf) if $source;
1869 push @cmd, ipt_gen_src_or_dst_match($dest, 'd', $ipversion, $cluster_conf, $fw_conf) if $dest;
1870
1871 if (my $proto = $rule->{proto}) {
1872 push @cmd, "-p $proto";
1873
1874 my $multiport = 0;
1875 $multiport++ if $nbdport > 1;
1876 $multiport++ if $nbsport > 1;
1877
1878 push @cmd, "--match multiport" if $multiport;
1879
1880 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1881 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1882
1883 if ($rule->{dport}) {
1884 if ($proto eq 'icmp') {
1885 # Note: we use dport to store --icmp-type
1886 die "unknown icmp-type '$rule->{dport}'\n"
1887 if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
1888 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1889 } elsif ($proto eq 'icmpv6') {
1890 # Note: we use dport to store --icmpv6-type
1891 die "unknown icmpv6-type '$rule->{dport}'\n"
1892 if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
1893 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1894 } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
1895 die "protocol $proto does not have ports\n";
1896 } else {
1897 if ($nbdport > 1) {
1898 if ($multiport == 2) {
1899 push @cmd, "--ports $rule->{dport}";
1900 } else {
1901 push @cmd, "--dports $rule->{dport}";
1902 }
1903 } else {
1904 push @cmd, "--dport $rule->{dport}";
1905 }
1906 }
1907 }
1908
1909 if ($rule->{sport}) {
1910 die "protocol $proto does not have ports\n"
1911 if !$PROTOCOLS_WITH_PORTS->{$proto};
1912 if ($nbsport > 1) {
1913 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1914 } else {
1915 push @cmd, "--sport $rule->{sport}";
1916 }
1917 }
1918 } elsif ($rule->{dport} || $rule->{sport}) {
1919 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1920 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
1921 }
1922
1923 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1924
1925 return scalar(@cmd) ? join(' ', @cmd) : undef;
1926 }
1927
1928 sub ruleset_generate_action {
1929 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1930
1931 return $rule->{target} if defined $rule->{target};
1932
1933 my @cmd = ();
1934
1935 if (my $action = $rule->{action}) {
1936 $action = $actions->{$action} if defined($actions->{$action});
1937 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1938 push @cmd, $goto ? "-g $action" : "-j $action";
1939 }
1940
1941 return scalar(@cmd) ? join(' ', @cmd) : undef;
1942 }
1943
1944 sub ruleset_generate_cmdstr {
1945 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1946 my $match = ruleset_generate_match($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1947 my $action = ruleset_generate_action($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1948
1949 return undef if !(defined($match) or defined($action));
1950 my $ret = defined($match) ? $match : "";
1951 $ret = "$ret $action" if defined($action);
1952 return $ret;
1953 }
1954
1955 sub ruleset_generate_rule {
1956 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1957
1958 my $rules;
1959
1960 if ($rule->{macro}) {
1961 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1962 } else {
1963 $rules = [ $rule ];
1964 }
1965
1966 # update all or nothing
1967
1968 # fixme: lots of temporary ugliness
1969 my @mstrs = ();
1970 my @astrs = ();
1971 my @logging = ();
1972 my @logmsg = ();
1973 foreach my $tmp (@$rules) {
1974 my $m = ruleset_generate_match($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1975 my $a = ruleset_generate_action($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1976 if (defined $m or defined $a) {
1977 push @mstrs, defined($m) ? $m : "";
1978 push @astrs, defined($a) ? $a : "";
1979 push @logging, $tmp->{log};
1980 push @logmsg, $tmp->{logmsg};
1981 }
1982 }
1983
1984 for my $i (0 .. $#mstrs) {
1985 ruleset_addrule($ruleset, $chain, $mstrs[$i], $astrs[$i], $logging[$i], $logmsg[$i]);
1986 }
1987 }
1988
1989 sub ruleset_generate_rule_insert {
1990 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1991
1992 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1993
1994 my $match = ruleset_generate_match($ruleset, $chain, $ipversion, $rule, $actions, $goto);
1995 my $action = ruleset_generate_action($ruleset, $chain, $ipversion, $rule, $actions, $goto);
1996 if (defined $match && defined $action) {
1997 ruleset_insertrule($ruleset, $chain, $match, $action);
1998 }
1999 }
2000
2001 sub ruleset_create_chain {
2002 my ($ruleset, $chain) = @_;
2003
2004 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
2005 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
2006
2007 die "chain '$chain' already exists\n" if $ruleset->{$chain};
2008
2009 $ruleset->{$chain} = [];
2010 }
2011
2012 sub ruleset_chain_exist {
2013 my ($ruleset, $chain) = @_;
2014
2015 return $ruleset->{$chain} ? 1 : undef;
2016 }
2017
2018 sub ruleset_addrule {
2019 my ($ruleset, $chain, $match, $action, $log, $logmsg, $vmid) = @_;
2020
2021 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2022
2023 if (defined($log) && $log) {
2024 my $logaction = get_log_rule_base($chain, $vmid, $logmsg, $log);
2025 push @{$ruleset->{$chain}}, "-A $chain $match $logaction";
2026 }
2027 push @{$ruleset->{$chain}}, "-A $chain $match $action";
2028 }
2029
2030 sub ruleset_insertrule {
2031 my ($ruleset, $chain, $match, $action, $log) = @_;
2032
2033 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2034
2035 unshift @{$ruleset->{$chain}}, "-A $chain $match $action";
2036 }
2037
2038 sub get_log_rule_base {
2039 my ($chain, $vmid, $msg, $loglevel) = @_;
2040
2041 $vmid = 0 if !defined($vmid);
2042 $msg = "" if !defined($msg);
2043
2044 # Note: we use special format for prefix to pass further
2045 # info to log daemon (VMID, LOGLEVEL and CHAIN)
2046
2047 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
2048 }
2049
2050 sub ruleset_add_chain_policy {
2051 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
2052
2053 if ($policy eq 'ACCEPT') {
2054
2055 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
2056 { ACCEPT => $accept_action});
2057
2058 } elsif ($policy eq 'DROP') {
2059
2060 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Drop");
2061
2062 ruleset_addrule($ruleset, $chain, "", "-j DROP", $loglevel, "policy $policy: ", $vmid);
2063 } elsif ($policy eq 'REJECT') {
2064 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Reject");
2065
2066 ruleset_addrule($ruleset, $chain, "", "-g PVEFW-reject", $loglevel, "policy $policy:", $vmid);
2067 } else {
2068 # should not happen
2069 die "internal error: unknown policy '$policy'";
2070 }
2071 }
2072
2073 sub ruleset_chain_add_ndp {
2074 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2075 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2076
2077 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-solicitation", $accept);
2078 if ($direction ne 'OUT' || $options->{radv}) {
2079 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", $accept);
2080 }
2081 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-solicitation", $accept);
2082 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type neighbor-advertisement", $accept);
2083 }
2084
2085 sub ruleset_chain_add_conn_filters {
2086 my ($ruleset, $chain, $accept) = @_;
2087
2088 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID", "-j DROP");
2089 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED", "-j $accept");
2090 }
2091
2092 sub ruleset_chain_add_input_filters {
2093 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2094
2095 if ($cluster_conf->{ipset}->{blacklist}){
2096 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
2097 ruleset_create_chain($ruleset, "PVEFW-blacklist");
2098 ruleset_addrule($ruleset, "PVEFW-blacklist", "", "-j DROP", $loglevel, "DROP: ");
2099 }
2100 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2101 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src", "-j PVEFW-blacklist");
2102 }
2103
2104 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2105 if ($ipversion == 4) {
2106 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW", "-j PVEFW-smurfs");
2107 }
2108 }
2109
2110 if ($options->{tcpflags}) {
2111 ruleset_addrule($ruleset, $chain, "-p tcp", "-j PVEFW-tcpflags");
2112 }
2113 }
2114
2115 sub ruleset_create_vm_chain {
2116 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2117
2118 ruleset_create_chain($ruleset, $chain);
2119 my $accept = generate_nfqueue($options);
2120
2121 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2122 if ($ipversion == 4) {
2123 if ($direction eq 'OUT') {
2124 ruleset_generate_rule($ruleset, $chain, $ipversion,
2125 { action => 'PVEFW-SET-ACCEPT-MARK',
2126 proto => 'udp', sport => 68, dport => 67 });
2127 } else {
2128 ruleset_generate_rule($ruleset, $chain, $ipversion,
2129 { action => 'ACCEPT',
2130 proto => 'udp', sport => 67, dport => 68 });
2131 }
2132 } elsif ($ipversion == 6) {
2133 if ($direction eq 'OUT') {
2134 ruleset_generate_rule($ruleset, $chain, $ipversion,
2135 { action => 'PVEFW-SET-ACCEPT-MARK',
2136 proto => 'udp', sport => 546, dport => 547 });
2137 } else {
2138 ruleset_generate_rule($ruleset, $chain, $ipversion,
2139 { action => 'ACCEPT',
2140 proto => 'udp', sport => 547, dport => 546 });
2141 }
2142 }
2143
2144 }
2145
2146 if ($direction eq 'OUT') {
2147 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2148 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr", "-j DROP");
2149 }
2150 if ($ipversion == 6 && !$options->{radv}) {
2151 ruleset_addrule($ruleset, $chain, "-p icmpv6 --icmpv6-type router-advertisement", "-j DROP");
2152 }
2153 if ($ipfilter_ipset) {
2154 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src", "-j DROP");
2155 }
2156 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
2157 }
2158
2159 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j $accept";
2160 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2161 }
2162
2163 sub ruleset_add_group_rule {
2164 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2165
2166 my $group = $rule->{action};
2167 my $group_chain = "GROUP-$group-$direction";
2168 if(!ruleset_chain_exist($ruleset, $group_chain)){
2169 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2170 }
2171
2172 if ($direction eq 'OUT' && $rule->{iface_out}) {
2173 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out}", "-j $group_chain");
2174 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2175 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in}", "-j $group_chain");
2176 } else {
2177 ruleset_addrule($ruleset, $chain, "", "-j $group_chain");
2178 }
2179
2180 ruleset_addrule($ruleset, $chain, "-m mark --mark $FWACCEPTMARK_ON", "-j $action");
2181 }
2182
2183 sub ruleset_generate_vm_rules {
2184 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2185
2186 my $lc_direction = lc($direction);
2187
2188 my $in_accept = generate_nfqueue($options);
2189
2190 foreach my $rule (@$rules) {
2191 next if $rule->{iface} && $rule->{iface} ne $netid;
2192 next if !$rule->{enable} || $rule->{errors};
2193 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2194
2195 if ($rule->{type} eq 'group') {
2196 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2197 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2198 } else {
2199 next if $rule->{type} ne $lc_direction;
2200 eval {
2201 if ($direction eq 'OUT') {
2202 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2203 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2204 undef, $cluster_conf, $vmfw_conf);
2205 } else {
2206 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2207 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
2208 undef, $cluster_conf, $vmfw_conf);
2209 }
2210 };
2211 warn $@ if $@;
2212 }
2213 }
2214 }
2215
2216 sub generate_nfqueue {
2217 my ($options) = @_;
2218
2219 if ($options->{ips}) {
2220 my $action = "NFQUEUE";
2221 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2222 if (defined($3) && defined($1)) {
2223 $action .= " --queue-balance $1:$3";
2224 } elsif (defined($1)) {
2225 $action .= " --queue-num $1";
2226 }
2227 }
2228 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
2229 return $action;
2230 } else {
2231 return "ACCEPT";
2232 }
2233 }
2234
2235 sub ruleset_generate_vm_ipsrules {
2236 my ($ruleset, $options, $direction, $iface) = @_;
2237
2238 if ($options->{ips} && $direction eq 'IN') {
2239 my $nfqueue = generate_nfqueue($options);
2240
2241 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
2242 ruleset_create_chain($ruleset, "PVEFW-IPS");
2243 }
2244
2245 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged", "-j $nfqueue");
2246 }
2247 }
2248
2249 sub generate_tap_rules_direction {
2250 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2251
2252 my $lc_direction = lc($direction);
2253
2254 my $rules = $vmfw_conf->{rules};
2255
2256 my $options = $vmfw_conf->{options};
2257 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2258
2259 my $tapchain = "$iface-$direction";
2260
2261 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2262 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2263 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2264
2265 # create chain with mac and ip filter
2266 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2267
2268 if ($options->{enable}) {
2269 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2270
2271 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2272
2273 # implement policy
2274 my $policy;
2275
2276 if ($direction eq 'OUT') {
2277 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2278 } else {
2279 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2280 }
2281
2282 my $accept = generate_nfqueue($options);
2283 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
2284 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2285 } else {
2286 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
2287 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2288 }
2289
2290 # plug the tap chain to bridge chain
2291 if ($direction eq 'IN') {
2292 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
2293 "-m physdev --physdev-is-bridged --physdev-out $iface", "-j $tapchain");
2294 } else {
2295 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
2296 "-m physdev --physdev-is-bridged --physdev-in $iface", "-j $tapchain");
2297 }
2298 }
2299
2300 sub enable_host_firewall {
2301 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2302
2303 my $options = $hostfw_conf->{options};
2304 my $cluster_options = $cluster_conf->{options};
2305 my $rules = $hostfw_conf->{rules};
2306 my $cluster_rules = $cluster_conf->{rules};
2307
2308 # host inbound firewall
2309 my $chain = "PVEFW-HOST-IN";
2310 ruleset_create_chain($ruleset, $chain);
2311
2312 my $loglevel = get_option_log_level($options, "log_level_in");
2313
2314 ruleset_addrule($ruleset, $chain, "-i lo", "-j ACCEPT");
2315
2316 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2317 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2318 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2319
2320 # we use RETURN because we need to check also tap rules
2321 my $accept_action = 'RETURN';
2322
2323 ruleset_addrule($ruleset, $chain, "-p igmp", "-j $accept_action"); # important for multicast
2324
2325 # add host rules first, so that cluster wide rules can be overwritten
2326 foreach my $rule (@$rules, @$cluster_rules) {
2327 next if !$rule->{enable} || $rule->{errors};
2328 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2329
2330 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2331
2332 eval {
2333 if ($rule->{type} eq 'group') {
2334 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2335 } elsif ($rule->{type} eq 'in') {
2336 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2337 { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2338 undef, $cluster_conf, $hostfw_conf);
2339 }
2340 };
2341 warn $@ if $@;
2342 delete $rule->{iface_in};
2343 }
2344
2345 # allow standard traffic for management ipset (includes cluster network)
2346 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management", $ipversion);
2347 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
2348 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006", "-j $accept_action"); # PVE API
2349 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999", "-j $accept_action"); # PVE VNC Console
2350 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128", "-j $accept_action"); # SPICE Proxy
2351 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22", "-j $accept_action"); # SSH
2352
2353 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2354 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2355
2356 # corosync
2357 if ($localnet && ($ipversion == $localnet_ver)) {
2358 my $corosync_rule = "-p udp --dport 5404:5405";
2359 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule", "-j $accept_action");
2360 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
2361 }
2362
2363 # implement input policy
2364 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2365 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2366
2367 # host outbound firewall
2368 $chain = "PVEFW-HOST-OUT";
2369 ruleset_create_chain($ruleset, $chain);
2370
2371 $loglevel = get_option_log_level($options, "log_level_out");
2372
2373 ruleset_addrule($ruleset, $chain, "-o lo", "-j ACCEPT");
2374
2375 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2376
2377 # we use RETURN because we may want to check other thigs later
2378 $accept_action = 'RETURN';
2379 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j $accept_action");
2380
2381 ruleset_addrule($ruleset, $chain, "-p igmp", "-j $accept_action"); # important for multicast
2382
2383 # add host rules first, so that cluster wide rules can be overwritten
2384 foreach my $rule (@$rules, @$cluster_rules) {
2385 next if !$rule->{enable} || $rule->{errors};
2386 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2387
2388 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2389 eval {
2390 if ($rule->{type} eq 'group') {
2391 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2392 } elsif ($rule->{type} eq 'out') {
2393 ruleset_generate_rule($ruleset, $chain, $ipversion,
2394 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2395 undef, $cluster_conf, $hostfw_conf);
2396 }
2397 };
2398 warn $@ if $@;
2399 delete $rule->{iface_out};
2400 }
2401
2402 # allow standard traffic on cluster network
2403 if ($localnet && ($ipversion == $localnet_ver)) {
2404 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006", "-j $accept_action"); # PVE API
2405 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22", "-j $accept_action"); # SSH
2406 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999", "-j $accept_action"); # PVE VNC Console
2407 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128", "-j $accept_action"); # SPICE Proxy
2408
2409 my $corosync_rule = "-p udp --dport 5404:5405";
2410 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule", "-j $accept_action");
2411 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule", "-j $accept_action");
2412 }
2413
2414 # implement output policy
2415 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2416 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2417
2418 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "", "-j PVEFW-HOST-OUT");
2419 ruleset_addrule($ruleset, "PVEFW-INPUT", "", "-j PVEFW-HOST-IN");
2420 }
2421
2422 sub generate_group_rules {
2423 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2424
2425 my $rules = $cluster_conf->{groups}->{$group};
2426
2427 if (!$rules) {
2428 warn "no such security group '$group'\n";
2429 $rules = []; # create empty chain
2430 }
2431
2432 my $chain = "GROUP-${group}-IN";
2433
2434 ruleset_create_chain($ruleset, $chain);
2435 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
2436
2437 foreach my $rule (@$rules) {
2438 next if $rule->{type} ne 'in';
2439 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2440 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2441 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2442 undef, $cluster_conf);
2443 }
2444
2445 $chain = "GROUP-${group}-OUT";
2446
2447 ruleset_create_chain($ruleset, $chain);
2448 ruleset_addrule($ruleset, $chain, "", "-j MARK --set-mark $FWACCEPTMARK_OFF"); # clear mark
2449
2450 foreach my $rule (@$rules) {
2451 next if $rule->{type} ne 'out';
2452 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2453 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2454 # check also other tap rules later
2455 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2456 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" },
2457 undef, $cluster_conf);
2458 }
2459 }
2460
2461 my $MAX_NETS = 32;
2462 my $valid_netdev_names = {};
2463 for (my $i = 0; $i < $MAX_NETS; $i++) {
2464 $valid_netdev_names->{"net$i"} = 1;
2465 }
2466
2467 sub get_mark_values {
2468 my ($value, $mask) = @_;
2469 $value = hex($value) if $value =~ /^0x/;
2470 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2471 $mask = 0xffffffff if !defined($mask);
2472 return ($value, $mask);
2473 }
2474
2475 sub parse_fw_rule {
2476 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2477
2478 my $orig_line = $line;
2479
2480 my $rule = {};
2481
2482 # we can add single line comments to the end of the rule
2483 if ($line =~ s/#\s*(.*?)\s*$//) {
2484 $rule->{comment} = decode('utf8', $1);
2485 }
2486
2487 # we can disable a rule when prefixed with '|'
2488
2489 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2490
2491 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2492 die "unable to parse rule: $line\n";
2493
2494 $rule->{type} = lc($1);
2495 $rule->{action} = $2;
2496
2497 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2498 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2499 $rule->{macro} = $1;
2500 $rule->{action} = $2;
2501 }
2502 }
2503
2504 while (length($line)) {
2505 if ($line =~ s/^-i (\S+)\s*//) {
2506 $rule->{iface} = $1;
2507 next;
2508 }
2509
2510 last if $rule->{type} eq 'group';
2511
2512 if ($line =~ s/^-p (\S+)\s*//) {
2513 $rule->{proto} = $1;
2514 next;
2515 }
2516
2517 if ($line =~ s/^-dport (\S+)\s*//) {
2518 $rule->{dport} = $1;
2519 next;
2520 }
2521
2522 if ($line =~ s/^-sport (\S+)\s*//) {
2523 $rule->{sport} = $1;
2524 next;
2525 }
2526 if ($line =~ s/^-source (\S+)\s*//) {
2527 $rule->{source} = $1;
2528 next;
2529 }
2530 if ($line =~ s/^-dest (\S+)\s*//) {
2531 $rule->{dest} = $1;
2532 next;
2533 }
2534
2535 last;
2536 }
2537
2538 die "unable to parse rule parameters: $line\n" if length($line);
2539
2540 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2541 if ($rule->{errors}) {
2542 # The verbose flag really means we're running from the CLI and want
2543 # output on the console - in the other case we really want such errors
2544 # to go into the syslog instead.
2545 my $log = $verbose ? sub { warn @_ } : sub { syslog(err => @_) };
2546 $log->("$prefix - errors in rule parameters: $orig_line\n");
2547 foreach my $p (keys %{$rule->{errors}}) {
2548 $log->(" $p: $rule->{errors}->{$p}\n");
2549 }
2550 }
2551
2552 return $rule;
2553 }
2554
2555 sub parse_vmfw_option {
2556 my ($line) = @_;
2557
2558 my ($opt, $value);
2559
2560 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2561
2562 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2563 $opt = lc($1);
2564 $value = int($2);
2565 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2566 $opt = lc($1);
2567 $value = $2 ? lc($3) : '';
2568 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2569 $opt = lc($1);
2570 $value = uc($3);
2571 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2572 $opt = lc($1);
2573 $value = $2;
2574 } else {
2575 die "can't parse option '$line'\n"
2576 }
2577
2578 return ($opt, $value);
2579 }
2580
2581 sub parse_hostfw_option {
2582 my ($line) = @_;
2583
2584 my ($opt, $value);
2585
2586 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2587
2588 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2589 $opt = lc($1);
2590 $value = int($2);
2591 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2592 $opt = lc($1);
2593 $value = $2 ? lc($3) : '';
2594 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2595 $opt = lc($1);
2596 $value = int($2);
2597 } else {
2598 die "can't parse option '$line'\n"
2599 }
2600
2601 return ($opt, $value);
2602 }
2603
2604 sub parse_clusterfw_option {
2605 my ($line) = @_;
2606
2607 my ($opt, $value);
2608
2609 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2610 $opt = lc($1);
2611 $value = int($2);
2612 if (($value > 1) && ((time() - $value) > 60)) {
2613 $value = 0
2614 }
2615 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2616 $opt = lc($1);
2617 $value = uc($3);
2618 } else {
2619 die "can't parse option '$line'\n"
2620 }
2621
2622 return ($opt, $value);
2623 }
2624
2625 sub resolve_alias {
2626 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2627
2628 my $alias = lc($cidr);
2629 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2630 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2631
2632 die "no such alias '$cidr'\n" if !$e;;
2633
2634 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2635 }
2636
2637 sub parse_ip_or_cidr {
2638 my ($cidr) = @_;
2639
2640 my $ipversion;
2641
2642 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2643 $cidr =~ s|/128$||;
2644 $ipversion = 6;
2645 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2646 $cidr =~ s|/32$||;
2647 $ipversion = 4;
2648 } else {
2649 die "value does not look like a valid IP address or CIDR network\n";
2650 }
2651
2652 return wantarray ? ($cidr, $ipversion) : $cidr;
2653 }
2654
2655 sub parse_alias {
2656 my ($line) = @_;
2657
2658 # we can add single line comments to the end of the line
2659 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2660
2661 if ($line =~ m/^(\S+)\s(\S+)$/) {
2662 my ($name, $cidr) = ($1, $2);
2663 my $ipversion;
2664
2665 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2666
2667 my $data = {
2668 name => $name,
2669 cidr => $cidr,
2670 ipversion => $ipversion,
2671 };
2672 $data->{comment} = $comment if $comment;
2673 return $data;
2674 }
2675
2676 return undef;
2677 }
2678
2679 sub generic_fw_config_parser {
2680 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2681
2682 my $section;
2683 my $group;
2684
2685 my $res = $empty_conf;
2686
2687 while (defined(my $line = <$fh>)) {
2688 next if $line =~ m/^#/;
2689 next if $line =~ m/^\s*$/;
2690
2691 chomp $line;
2692
2693 my $linenr = $fh->input_line_number();
2694 my $prefix = "$filename (line $linenr)";
2695
2696 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2697 $section = 'options';
2698 next;
2699 }
2700
2701 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2702 $section = 'aliases';
2703 next;
2704 }
2705
2706 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2707 $section = 'groups';
2708 $group = lc($1);
2709 my $comment = $2;
2710 eval {
2711 die "security group name too long\n" if length($group) > $max_group_name_length;
2712 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2713 };
2714 if (my $err = $@) {
2715 ($section, $group, $comment) = undef;
2716 warn "$prefix: $err";
2717 next;
2718 }
2719
2720 $res->{$section}->{$group} = [];
2721 $res->{group_comments}->{$group} = decode('utf8', $comment)
2722 if $comment;
2723 next;
2724 }
2725
2726 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2727 $section = 'rules';
2728 next;
2729 }
2730
2731 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2732 $section = 'ipset';
2733 $group = lc($1);
2734 my $comment = $2;
2735 eval {
2736 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2737 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2738 };
2739 if (my $err = $@) {
2740 ($section, $group, $comment) = undef;
2741 warn "$prefix: $err";
2742 next;
2743 }
2744
2745 $res->{$section}->{$group} = [];
2746 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2747 if $comment;
2748 next;
2749 }
2750
2751 if (!$section) {
2752 warn "$prefix: skip line - no section\n";
2753 next;
2754 }
2755
2756 if ($section eq 'options') {
2757 eval {
2758 my ($opt, $value);
2759 if ($rule_env eq 'cluster') {
2760 ($opt, $value) = parse_clusterfw_option($line);
2761 } elsif ($rule_env eq 'host') {
2762 ($opt, $value) = parse_hostfw_option($line);
2763 } else {
2764 ($opt, $value) = parse_vmfw_option($line);
2765 }
2766 $res->{options}->{$opt} = $value;
2767 };
2768 warn "$prefix: $@" if $@;
2769 } elsif ($section eq 'aliases') {
2770 eval {
2771 my $data = parse_alias($line);
2772 $res->{aliases}->{lc($data->{name})} = $data;
2773 };
2774 warn "$prefix: $@" if $@;
2775 } elsif ($section eq 'rules') {
2776 my $rule;
2777 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2778 if (my $err = $@) {
2779 warn "$prefix: $err";
2780 next;
2781 }
2782 push @{$res->{$section}}, $rule;
2783 } elsif ($section eq 'groups') {
2784 my $rule;
2785 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
2786 if (my $err = $@) {
2787 warn "$prefix: $err";
2788 next;
2789 }
2790 push @{$res->{$section}->{$group}}, $rule;
2791 } elsif ($section eq 'ipset') {
2792 # we can add single line comments to the end of the rule
2793 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2794
2795 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2796 my $nomatch = $1;
2797 my $cidr = $2;
2798 my $errors;
2799
2800 if ($nomatch && !$feature_ipset_nomatch) {
2801 $errors->{nomatch} = "nomatch not supported by kernel";
2802 }
2803
2804 eval {
2805 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2806 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2807 } else {
2808 $cidr = parse_ip_or_cidr($cidr);
2809 }
2810 };
2811 if (my $err = $@) {
2812 chomp $err;
2813 $errors->{cidr} = $err;
2814 }
2815
2816 if ($cidr =~ m!/0+$!) {
2817 $errors->{cidr} = "a zero prefix is not allowed in ipset entries\n";
2818 }
2819
2820 my $entry = { cidr => $cidr };
2821 $entry->{nomatch} = 1 if $nomatch;
2822 $entry->{comment} = $comment if $comment;
2823 $entry->{errors} = $errors if $errors;
2824
2825 if ($verbose && $errors) {
2826 warn "$prefix - errors in ipset '$group': $line\n";
2827 foreach my $p (keys %{$errors}) {
2828 warn " $p: $errors->{$p}\n";
2829 }
2830 }
2831
2832 push @{$res->{$section}->{$group}}, $entry;
2833 } else {
2834 warn "$prefix: skip line - unknown section\n";
2835 next;
2836 }
2837 }
2838
2839 return $res;
2840 }
2841
2842 sub parse_hostfw_config {
2843 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2844
2845 my $empty_conf = { rules => [], options => {}};
2846
2847 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
2848 }
2849
2850 sub parse_vmfw_config {
2851 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2852
2853 my $empty_conf = {
2854 rules => [],
2855 options => {},
2856 aliases => {},
2857 ipset => {} ,
2858 ipset_comments => {},
2859 };
2860
2861 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2862 }
2863
2864 sub parse_clusterfw_config {
2865 my ($filename, $fh, $verbose) = @_;
2866
2867 my $section;
2868 my $group;
2869
2870 my $empty_conf = {
2871 rules => [],
2872 options => {},
2873 aliases => {},
2874 groups => {},
2875 group_comments => {},
2876 ipset => {} ,
2877 ipset_comments => {},
2878 };
2879
2880 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
2881 }
2882
2883 sub run_locked {
2884 my ($code, @param) = @_;
2885
2886 my $timeout = 10;
2887
2888 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2889
2890 die $@ if $@;
2891
2892 return $res;
2893 }
2894
2895 sub read_local_vm_config {
2896
2897 my $qemu = {};
2898 my $lxc = {};
2899
2900 my $vmdata = { qemu => $qemu, lxc => $lxc };
2901
2902 my $vmlist = PVE::Cluster::get_vmlist();
2903 return $vmdata if !$vmlist || !$vmlist->{ids};
2904 my $ids = $vmlist->{ids};
2905
2906 foreach my $vmid (keys %$ids) {
2907 next if !$vmid; # skip VE0
2908 my $d = $ids->{$vmid};
2909 next if !$d->{node} || $d->{node} ne $nodename;
2910 next if !$d->{type};
2911 if ($d->{type} eq 'qemu') {
2912 if ($have_qemu_server) {
2913 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2914 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2915 $qemu->{$vmid} = $conf;
2916 }
2917 }
2918 } elsif ($d->{type} eq 'lxc') {
2919 if ($have_lxc) {
2920 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2921 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2922 $lxc->{$vmid} = $conf;
2923 }
2924 }
2925 }
2926 }
2927
2928 return $vmdata;
2929 };
2930
2931 sub load_vmfw_conf {
2932 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2933
2934 my $vmfw_conf = {};
2935
2936 $dir = $pvefw_conf_dir if !defined($dir);
2937
2938 my $filename = "$dir/$vmid.fw";
2939 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2940 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2941 $vmfw_conf->{vmid} = $vmid;
2942 }
2943
2944 return $vmfw_conf;
2945 }
2946
2947 my $format_rules = sub {
2948 my ($rules, $allow_iface) = @_;
2949
2950 my $raw = '';
2951
2952 foreach my $rule (@$rules) {
2953 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2954 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2955 $raw .= uc($rule->{type});
2956 if ($rule->{macro}) {
2957 $raw .= " $rule->{macro}($rule->{action})";
2958 } else {
2959 $raw .= " " . $rule->{action};
2960 }
2961 if ($allow_iface && $rule->{iface}) {
2962 $raw .= " -i $rule->{iface}";
2963 }
2964
2965 if ($rule->{type} ne 'group') {
2966 $raw .= " -source $rule->{source}" if $rule->{source};
2967 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2968 $raw .= " -p $rule->{proto}" if $rule->{proto};
2969 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2970 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2971 }
2972
2973 $raw .= " # " . encode('utf8', $rule->{comment})
2974 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2975 $raw .= "\n";
2976 } else {
2977 die "unknown rule type '$rule->{type}'";
2978 }
2979 }
2980
2981 return $raw;
2982 };
2983
2984 my $format_options = sub {
2985 my ($options) = @_;
2986
2987 my $raw = '';
2988
2989 $raw .= "[OPTIONS]\n\n";
2990 foreach my $opt (keys %$options) {
2991 $raw .= "$opt: $options->{$opt}\n";
2992 }
2993 $raw .= "\n";
2994
2995 return $raw;
2996 };
2997
2998 my $format_aliases = sub {
2999 my ($aliases) = @_;
3000
3001 my $raw = '';
3002
3003 $raw .= "[ALIASES]\n\n";
3004 foreach my $k (keys %$aliases) {
3005 my $e = $aliases->{$k};
3006 $raw .= "$e->{name} $e->{cidr}";
3007 $raw .= " # " . encode('utf8', $e->{comment})
3008 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
3009 $raw .= "\n";
3010 }
3011 $raw .= "\n";
3012
3013 return $raw;
3014 };
3015
3016 my $format_ipsets = sub {
3017 my ($fw_conf) = @_;
3018
3019 my $raw = '';
3020
3021 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
3022 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
3023 my $utf8comment = encode('utf8', $comment);
3024 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
3025 } else {
3026 $raw .= "[IPSET $ipset]\n\n";
3027 }
3028 my $options = $fw_conf->{ipset}->{$ipset};
3029
3030 my $nethash = {};
3031 foreach my $entry (@$options) {
3032 $nethash->{$entry->{cidr}} = $entry;
3033 }
3034
3035 foreach my $cidr (sort keys %$nethash) {
3036 my $entry = $nethash->{$cidr};
3037 my $line = $entry->{nomatch} ? '!' : '';
3038 $line .= $entry->{cidr};
3039 $line .= " # " . encode('utf8', $entry->{comment})
3040 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
3041 $raw .= "$line\n";
3042 }
3043
3044 $raw .= "\n";
3045 }
3046
3047 return $raw;
3048 };
3049
3050 sub save_vmfw_conf {
3051 my ($vmid, $vmfw_conf) = @_;
3052
3053 my $raw = '';
3054
3055 my $options = $vmfw_conf->{options};
3056 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3057
3058 my $aliases = $vmfw_conf->{aliases};
3059 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3060
3061 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
3062
3063 my $rules = $vmfw_conf->{rules} || [];
3064 if ($rules && scalar(@$rules)) {
3065 $raw .= "[RULES]\n\n";
3066 $raw .= &$format_rules($rules, 1);
3067 $raw .= "\n";
3068 }
3069
3070 my $filename = "$pvefw_conf_dir/$vmid.fw";
3071 if ($raw) {
3072 mkdir $pvefw_conf_dir;
3073 PVE::Tools::file_set_contents($filename, $raw);
3074 } else {
3075 unlink $filename;
3076 }
3077 }
3078
3079 sub remove_vmfw_conf {
3080 my ($vmid) = @_;
3081
3082 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3083
3084 unlink $vmfw_conffile;
3085 }
3086
3087 sub clone_vmfw_conf {
3088 my ($vmid, $newid) = @_;
3089
3090 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3091 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3092
3093 if (-f $clonevm_conffile) {
3094 unlink $clonevm_conffile;
3095 }
3096 if (-f $sourcevm_conffile) {
3097 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3098 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3099 }
3100 }
3101
3102 sub read_vm_firewall_configs {
3103 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3104
3105 my $vmfw_configs = {};
3106
3107 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3108 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
3109 next if !$vmfw_conf->{options}; # skip if file does not exists
3110 $vmfw_configs->{$vmid} = $vmfw_conf;
3111 }
3112 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3113 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
3114 next if !$vmfw_conf->{options}; # skip if file does not exists
3115 $vmfw_configs->{$vmid} = $vmfw_conf;
3116 }
3117
3118 return $vmfw_configs;
3119 }
3120
3121 sub get_option_log_level {
3122 my ($options, $k) = @_;
3123
3124 my $v = $options->{$k};
3125 $v = $default_log_level if !defined($v);
3126
3127 return undef if $v eq '' || $v eq 'nolog';
3128
3129 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3130
3131 return $v if ($v >= 0) && ($v <= 7);
3132
3133 warn "unknown log level ($k = '$v')\n";
3134
3135 return undef;
3136 }
3137
3138 sub generate_std_chains {
3139 my ($ruleset, $options, $ipversion) = @_;
3140
3141 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3142
3143 my $loglevel = get_option_log_level($options, 'smurf_log_level');
3144 my $chain = 'PVEFW-smurflog';
3145 if ( $std_chains->{$chain} ) {
3146 foreach my $r (@{$std_chains->{$chain}}) {
3147 $r->{log} = $loglevel;
3148 }
3149 }
3150
3151 # same as shorewall logflags action.
3152 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
3153 $chain = 'PVEFW-logflags';
3154 if ( $std_chains->{$chain} ) {
3155 foreach my $r (@{$std_chains->{$chain}}) {
3156 $r->{log} = $loglevel;
3157 }
3158 }
3159
3160 foreach my $chain (keys %$std_chains) {
3161 ruleset_create_chain($ruleset, $chain);
3162 foreach my $rule (@{$std_chains->{$chain}}) {
3163 if (ref($rule)) {
3164 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3165 } else {
3166 die "rule $rule as string - should not happen";
3167 }
3168 }
3169 }
3170 }
3171
3172 sub generate_ipset_chains {
3173 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3174
3175 foreach my $ipset (keys %{$ipsets}) {
3176
3177 my $options = $ipsets->{$ipset};
3178
3179 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3180 if (my $ips = $device_ips->{$1}) {
3181 $options = [@$options, @$ips];
3182 }
3183 }
3184
3185 # remove duplicates
3186 my $nethash = {};
3187 foreach my $entry (@$options) {
3188 next if $entry->{errors}; # skip entries with errors
3189 eval {
3190 my ($cidr, $ver);
3191 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3192 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3193 } else {
3194 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3195 }
3196 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3197 if ($ver == 6) {
3198 # ip_compress_address takes an address only, no CIDR
3199 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3200 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3201 $cidr .= $prefix_len if defined($prefix_len);
3202 $cidr =~ s|/128$||;
3203 } else {
3204 $cidr =~ s|/32$||;
3205 }
3206
3207 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3208 };
3209 warn $@ if $@;
3210 }
3211
3212 foreach my $ipversion (4, 6) {
3213 my $data = $nethash->{$ipversion};
3214
3215 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3216
3217 my $hashsize = scalar(@$options);
3218 if ($hashsize <= 64) {
3219 $hashsize = 64;
3220 } else {
3221 $hashsize = round_powerof2($hashsize);
3222 }
3223
3224 my $family = $ipversion == "6" ? "inet6" : "inet";
3225
3226 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3227
3228 foreach my $cidr (sort keys %$data) {
3229 my $entry = $data->{$cidr};
3230
3231 my $cmd = "add $name $cidr";
3232 if ($entry->{nomatch}) {
3233 if ($feature_ipset_nomatch) {
3234 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3235 } else {
3236 warn "ignore !$cidr - nomatch not supported by kernel\n";
3237 }
3238 } else {
3239 push @{$ipset_ruleset->{$name}}, $cmd;
3240 }
3241 }
3242 }
3243 }
3244 }
3245
3246 sub round_powerof2 {
3247 my ($int) = @_;
3248
3249 $int--;
3250 $int |= $int >> $_ foreach (1,2,4,8,16);
3251 return ++$int;
3252 }
3253
3254 sub load_clusterfw_conf {
3255 my ($filename, $verbose) = @_;
3256
3257 $filename = $clusterfw_conf_filename if !defined($filename);
3258
3259 my $cluster_conf = {};
3260 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3261 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3262 }
3263
3264 return $cluster_conf;
3265 }
3266
3267 sub save_clusterfw_conf {
3268 my ($cluster_conf) = @_;
3269
3270 my $raw = '';
3271
3272 my $options = $cluster_conf->{options};
3273 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3274
3275 my $aliases = $cluster_conf->{aliases};
3276 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3277
3278 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3279
3280 my $rules = $cluster_conf->{rules};
3281 if ($rules && scalar(@$rules)) {
3282 $raw .= "[RULES]\n\n";
3283 $raw .= &$format_rules($rules, 1);
3284 $raw .= "\n";
3285 }
3286
3287 if ($cluster_conf->{groups}) {
3288 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3289 my $rules = $cluster_conf->{groups}->{$group};
3290 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3291 my $utf8comment = encode('utf8', $comment);
3292 $raw .= "[group $group] # $utf8comment\n\n";
3293 } else {
3294 $raw .= "[group $group]\n\n";
3295 }
3296
3297 $raw .= &$format_rules($rules, 0);
3298 $raw .= "\n";
3299 }
3300 }
3301
3302 if ($raw) {
3303 mkdir $pvefw_conf_dir;
3304 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3305 } else {
3306 unlink $clusterfw_conf_filename;
3307 }
3308 }
3309
3310 sub load_hostfw_conf {
3311 my ($cluster_conf, $filename, $verbose) = @_;
3312
3313 $filename = $hostfw_conf_filename if !defined($filename);
3314
3315 my $hostfw_conf = {};
3316 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3317 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3318 }
3319 return $hostfw_conf;
3320 }
3321
3322 sub save_hostfw_conf {
3323 my ($hostfw_conf) = @_;
3324
3325 my $raw = '';
3326
3327 my $options = $hostfw_conf->{options};
3328 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3329
3330 my $rules = $hostfw_conf->{rules};
3331 if ($rules && scalar(@$rules)) {
3332 $raw .= "[RULES]\n\n";
3333 $raw .= &$format_rules($rules, 1);
3334 $raw .= "\n";
3335 }
3336
3337 if ($raw) {
3338 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3339 } else {
3340 unlink $hostfw_conf_filename;
3341 }
3342 }
3343
3344 sub compile {
3345 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3346
3347 my $vmfw_configs;
3348
3349 # fixme: once we read standard chains from config this needs to be put in test/standard cases below
3350 $pve_std_chains = dclone($pve_std_chains_conf);
3351
3352 if ($vmdata) { # test mode
3353 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3354 my $filename = "$testdir/cluster.fw";
3355 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3356
3357 $filename = "$testdir/host.fw";
3358 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3359
3360 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3361 } else { # normal operation
3362 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3363
3364 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3365
3366 $vmdata = read_local_vm_config();
3367 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3368 }
3369
3370 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3371
3372 my $localnet;
3373 if ($cluster_conf->{aliases}->{local_network}) {
3374 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3375 } else {
3376 my $localnet_ver;
3377 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3378
3379 $cluster_conf->{aliases}->{local_network} = {
3380 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
3381 }
3382
3383 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3384
3385 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3386 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3387 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3388
3389 return ($ruleset, $ipset_ruleset, $rulesetv6);
3390 }
3391
3392 sub compile_iptables_filter {
3393 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3394
3395 my $ruleset = {};
3396
3397 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3398 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3399
3400 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3401
3402 my $hostfw_options = $hostfw_conf->{options} || {};
3403
3404 # fixme: what log level should we use here?
3405 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3406
3407 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3408
3409 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3410 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3411
3412 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+", "-j PVEFW-FWBR-IN");
3413
3414 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3415 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+", "-j PVEFW-FWBR-OUT");
3416
3417 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3418
3419 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3420
3421 if ($hostfw_enable) {
3422 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3423 warn $@ if $@; # just to be sure - should not happen
3424 }
3425
3426 # generate firewall rules for QEMU VMs
3427 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3428 eval {
3429 my $conf = $vmdata->{qemu}->{$vmid};
3430 my $vmfw_conf = $vmfw_configs->{$vmid};
3431 return if !$vmfw_conf;
3432
3433 foreach my $netid (sort keys %$conf) {
3434 next if $netid !~ m/^net(\d+)$/;
3435 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3436 next if !$net->{firewall};
3437 my $iface = "tap${vmid}i$1";
3438
3439 my $macaddr = $net->{macaddr};
3440 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3441 $vmfw_conf, $vmid, 'IN', $ipversion);
3442 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3443 $vmfw_conf, $vmid, 'OUT', $ipversion);
3444 }
3445 };
3446 warn $@ if $@; # just to be sure - should not happen
3447 }
3448
3449 # generate firewall rules for LXC containers
3450 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3451 eval {
3452 my $conf = $vmdata->{lxc}->{$vmid};
3453 my $vmfw_conf = $vmfw_configs->{$vmid};
3454 return if !$vmfw_conf;
3455
3456 if ($vmfw_conf->{options}->{enable}) {
3457 foreach my $netid (sort keys %$conf) {
3458 next if $netid !~ m/^net(\d+)$/;
3459 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3460 next if !$net->{firewall};
3461 my $iface = "veth${vmid}i$1";
3462 my $macaddr = $net->{hwaddr};
3463 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3464 $vmfw_conf, $vmid, 'IN', $ipversion);
3465 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3466 $vmfw_conf, $vmid, 'OUT', $ipversion);
3467 }
3468 }
3469 };
3470 warn $@ if $@; # just to be sure - should not happen
3471 }
3472
3473 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3474 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED", "-j PVEFW-IPS");
3475 }
3476
3477 return $ruleset;
3478 }
3479
3480 sub mac_to_linklocal {
3481 my ($macaddr) = @_;
3482 my @parts = split(/:/, $macaddr);
3483 # The standard link local address uses the fe80::/64 prefix with the
3484 # modified EUI-64 identifier derived from the MAC address by flipping the
3485 # universal/local bit and inserting FF:FE in the middle.
3486 # See RFC 4291.
3487 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3488 my @meui64 = (@parts[0,1,2], 'ff', 'fe', @parts[3,4,5]);
3489 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3490 }
3491
3492 sub compile_ipsets {
3493 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3494
3495 my $localnet;
3496 if ($cluster_conf->{aliases}->{local_network}) {
3497 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3498 } else {
3499 my $localnet_ver;
3500 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3501
3502 $cluster_conf->{aliases}->{local_network} = {
3503 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
3504 }
3505
3506 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3507
3508
3509 my $ipset_ruleset = {};
3510
3511 # generate ipsets for QEMU VMs
3512 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3513 eval {
3514 my $conf = $vmdata->{qemu}->{$vmid};
3515 my $vmfw_conf = $vmfw_configs->{$vmid};
3516 return if !$vmfw_conf;
3517
3518 # When the 'ipfilter' option is enabled every device for which there
3519 # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
3520 # ipset.
3521 # The reason is that ipfilter ipsets are always filled with standard
3522 # IPv6 link-local filters.
3523 my $ipsets = $vmfw_conf->{ipset};
3524 my $implicit_sets = {};
3525
3526 my $device_ips = {};
3527 foreach my $netid (keys %$conf) {
3528 next if $netid !~ m/^net(\d+)$/;
3529 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3530 next if !$net->{firewall};
3531
3532 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3533 $implicit_sets->{"ipfilter-$netid"} = [];
3534 }
3535
3536 my $macaddr = $net->{macaddr};
3537 my $linklocal = mac_to_linklocal($macaddr);
3538 $device_ips->{$netid} = [
3539 { cidr => $linklocal },
3540 { cidr => 'fe80::/10', nomatch => 1 }
3541 ];
3542 }
3543
3544 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3545 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3546 };
3547 warn $@ if $@; # just to be sure - should not happen
3548 }
3549
3550 # generate firewall rules for LXC containers
3551 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3552 eval {
3553 my $conf = $vmdata->{lxc}->{$vmid};
3554 my $vmfw_conf = $vmfw_configs->{$vmid};
3555 return if !$vmfw_conf;
3556
3557 # When the 'ipfilter' option is enabled every device for which there
3558 # is no 'ipfilter-netX' ipset defiend gets an implicit empty default
3559 # ipset.
3560 # The reason is that ipfilter ipsets are always filled with standard
3561 # IPv6 link-local filters, as well as the IP addresses configured
3562 # for the container.
3563 my $ipsets = $vmfw_conf->{ipset};
3564 my $implicit_sets = {};
3565
3566 my $device_ips = {};
3567 foreach my $netid (keys %$conf) {
3568 next if $netid !~ m/^net(\d+)$/;
3569 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3570 next if !$net->{firewall};
3571
3572 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3573 $implicit_sets->{"ipfilter-$netid"} = [];
3574 }
3575
3576 my $macaddr = $net->{hwaddr};
3577 my $linklocal = mac_to_linklocal($macaddr);
3578 my $set = $device_ips->{$netid} = [
3579 { cidr => $linklocal },
3580 { cidr => 'fe80::/10', nomatch => 1 }
3581 ];
3582 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3583 push @$set, { cidr => $1 };
3584 }
3585 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3586 push @$set, { cidr => $1 };
3587 }
3588 }
3589
3590 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3591 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3592 };
3593 warn $@ if $@; # just to be sure - should not happen
3594 }
3595
3596 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3597
3598 return $ipset_ruleset;
3599 }
3600
3601 sub get_ruleset_status {
3602 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3603
3604 my $statushash = {};
3605
3606 foreach my $chain (sort keys %$ruleset) {
3607 my $sig = &$digest_fn($ruleset->{$chain});
3608
3609 $statushash->{$chain}->{sig} = $sig;
3610
3611 my $oldsig = $active_chains->{$chain};
3612 if (!defined($oldsig)) {
3613 $statushash->{$chain}->{action} = 'create';
3614 } else {
3615 if ($oldsig eq $sig) {
3616 $statushash->{$chain}->{action} = 'exists';
3617 } else {
3618 $statushash->{$chain}->{action} = 'update';
3619 }
3620 }
3621 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3622 foreach my $cmd (@{$ruleset->{$chain}}) {
3623 print "\t$cmd\n" if $verbose;
3624 }
3625 }
3626
3627 foreach my $chain (sort keys %$active_chains) {
3628 if (!defined($ruleset->{$chain})) {
3629 my $sig = $active_chains->{$chain};
3630 $statushash->{$chain}->{action} = 'delete';
3631 $statushash->{$chain}->{sig} = $sig;
3632 print "delete $chain ($sig)\n" if $verbose;
3633 }
3634 }
3635
3636 return $statushash;
3637 }
3638
3639 sub print_sig_rule {
3640 my ($chain, $sig) = @_;
3641
3642 # We just use this to store a SHA1 checksum used to detect changes
3643 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3644 }
3645
3646 sub get_ruleset_cmdlist {
3647 my ($ruleset, $verbose, $iptablescmd) = @_;
3648
3649 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3650
3651 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3652 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3653
3654 # create missing chains first
3655 foreach my $chain (sort keys %$ruleset) {
3656 my $stat = $statushash->{$chain};
3657 die "internal error" if !$stat;
3658 next if $stat->{action} ne 'create';
3659
3660 $cmdlist .= ":$chain - [0:0]\n";
3661 }
3662
3663 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3664 my $chain = "PVEFW-$h";
3665 if ($ruleset->{$chain} && !$hooks->{$h}) {
3666 $cmdlist .= "-A $h -j $chain\n";
3667 }
3668 }
3669
3670 foreach my $chain (sort keys %$ruleset) {
3671 my $stat = $statushash->{$chain};
3672 die "internal error" if !$stat;
3673
3674 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3675 $cmdlist .= "-F $chain\n";
3676 foreach my $cmd (@{$ruleset->{$chain}}) {
3677 $cmdlist .= "$cmd\n";
3678 }
3679 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3680 } elsif ($stat->{action} eq 'delete') {
3681 die "internal error"; # this should not happen
3682 } elsif ($stat->{action} eq 'exists') {
3683 # do nothing
3684 } else {
3685 die "internal error - unknown status '$stat->{action}'";
3686 }
3687 }
3688
3689 foreach my $chain (keys %$statushash) {
3690 next if $statushash->{$chain}->{action} ne 'delete';
3691 $cmdlist .= "-F $chain\n";
3692 }
3693 foreach my $chain (keys %$statushash) {
3694 next if $statushash->{$chain}->{action} ne 'delete';
3695 next if $chain eq 'PVEFW-INPUT';
3696 next if $chain eq 'PVEFW-OUTPUT';
3697 next if $chain eq 'PVEFW-FORWARD';
3698 $cmdlist .= "-X $chain\n";
3699 }
3700
3701 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
3702
3703 $cmdlist .= "COMMIT\n";
3704
3705 return wantarray ? ($cmdlist, $changes) : $cmdlist;
3706 }
3707
3708 sub get_ipset_cmdlist {
3709 my ($ruleset, $verbose) = @_;
3710
3711 my $cmdlist = "";
3712
3713 my $delete_cmdlist = "";
3714
3715 my $active_chains = ipset_get_chains();
3716 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
3717
3718 # remove stale _swap chains
3719 foreach my $chain (keys %$active_chains) {
3720 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3721 $cmdlist .= "destroy $chain\n";
3722 }
3723 }
3724
3725 foreach my $chain (keys %$ruleset) {
3726 my $stat = $statushash->{$chain};
3727 die "internal error" if !$stat;
3728
3729 if ($stat->{action} eq 'create') {
3730 foreach my $cmd (@{$ruleset->{$chain}}) {
3731 $cmdlist .= "$cmd\n";
3732 }
3733 }
3734 }
3735
3736 foreach my $chain (keys %$ruleset) {
3737 my $stat = $statushash->{$chain};
3738 die "internal error" if !$stat;
3739
3740 if ($stat->{action} eq 'update') {
3741 my $chain_swap = $chain."_swap";
3742
3743 foreach my $cmd (@{$ruleset->{$chain}}) {
3744 $cmd =~ s/$chain/$chain_swap/;
3745 $cmdlist .= "$cmd\n";
3746 }
3747 $cmdlist .= "swap $chain_swap $chain\n";
3748 $cmdlist .= "flush $chain_swap\n";
3749 $cmdlist .= "destroy $chain_swap\n";
3750 }
3751 }
3752
3753 # the remove unused chains
3754 foreach my $chain (keys %$statushash) {
3755 next if $statushash->{$chain}->{action} ne 'delete';
3756
3757 $delete_cmdlist .= "flush $chain\n";
3758 $delete_cmdlist .= "destroy $chain\n";
3759 }
3760
3761 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
3762
3763 return ($cmdlist, $delete_cmdlist, $changes);
3764 }
3765
3766 sub apply_ruleset {
3767 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3768
3769 enable_bridge_firewall();
3770
3771 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3772 get_ipset_cmdlist($ipset_ruleset, $verbose);
3773
3774 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
3775 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
3776
3777 if ($verbose) {
3778 if ($ipset_changes) {
3779 print "ipset changes:\n";
3780 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3781 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3782 }
3783
3784 if ($changes) {
3785 print "iptables changes:\n";
3786 print $cmdlist;
3787 }
3788
3789 if ($changesv6) {
3790 print "ip6tables changes:\n";
3791 print $cmdlistv6;
3792 }
3793 }
3794
3795 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3796 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3797
3798 ipset_restore_cmdlist($ipset_create_cmdlist);
3799
3800 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3801 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3802
3803 iptables_restore_cmdlist($cmdlist);
3804
3805 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3806 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3807
3808 ip6tables_restore_cmdlist($cmdlistv6);
3809
3810 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3811 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3812
3813 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3814
3815 # test: re-read status and check if everything is up to date
3816 my $active_chains = iptables_get_chains();
3817 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3818
3819 my $errors;
3820 foreach my $chain (sort keys %$ruleset) {
3821 my $stat = $statushash->{$chain};
3822 if ($stat->{action} ne 'exists') {
3823 warn "unable to update chain '$chain'\n";
3824 $errors = 1;
3825 }
3826 }
3827
3828 my $active_chainsv6 = iptables_get_chains("ip6tables");
3829 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3830
3831 foreach my $chain (sort keys %$rulesetv6) {
3832 my $stat = $statushashv6->{$chain};
3833 if ($stat->{action} ne 'exists') {
3834 warn "unable to update chain '$chain'\n";
3835 $errors = 1;
3836 }
3837 }
3838
3839 die "unable to apply firewall changes\n" if $errors;
3840
3841 update_nf_conntrack_max($hostfw_conf);
3842
3843 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3844
3845 }
3846
3847 sub update_nf_conntrack_max {
3848 my ($hostfw_conf) = @_;
3849
3850 my $max = 65536; # reasonable default
3851
3852 my $options = $hostfw_conf->{options} || {};
3853
3854 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3855 $max = $options->{nf_conntrack_max};
3856 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3857 }
3858
3859 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3860 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3861
3862 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3863
3864 if ($current != $max) {
3865 my $hashsize = int($max/4);
3866 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3867 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3868 }
3869 }
3870
3871 sub update_nf_conntrack_tcp_timeout_established {
3872 my ($hostfw_conf) = @_;
3873
3874 my $options = $hostfw_conf->{options} || {};
3875
3876 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3877
3878 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3879 }
3880
3881 sub remove_pvefw_chains {
3882
3883 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3884 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3885 PVE::Firewall::remove_pvefw_chains_ipset();
3886
3887 }
3888
3889 sub remove_pvefw_chains_iptables {
3890 my ($iptablescmd) = @_;
3891
3892 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
3893 my $cmdlist = "*filter\n";
3894
3895 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3896 if ($hooks->{$h}) {
3897 $cmdlist .= "-D $h -j PVEFW-$h\n";
3898 }
3899 }
3900
3901 foreach my $chain (keys %$chash) {
3902 $cmdlist .= "-F $chain\n";
3903 }
3904
3905 foreach my $chain (keys %$chash) {
3906 $cmdlist .= "-X $chain\n";
3907 }
3908 $cmdlist .= "COMMIT\n";
3909
3910 if($iptablescmd eq "ip6tables") {
3911 ip6tables_restore_cmdlist($cmdlist);
3912 } else {
3913 iptables_restore_cmdlist($cmdlist);
3914 }
3915 }
3916
3917 sub remove_pvefw_chains_ipset {
3918
3919 my $ipset_chains = ipset_get_chains();
3920
3921 my $cmdlist = "";
3922
3923 foreach my $chain (keys %$ipset_chains) {
3924 $cmdlist .= "flush $chain\n";
3925 $cmdlist .= "destroy $chain\n";
3926 }
3927
3928 ipset_restore_cmdlist($cmdlist) if $cmdlist;
3929 }
3930
3931 sub init {
3932 my $cluster_conf = load_clusterfw_conf();
3933 my $cluster_options = $cluster_conf->{options};
3934 my $enable = $cluster_options->{enable};
3935
3936 return if !$enable;
3937
3938 # load required modules here
3939 }
3940
3941 sub update {
3942 my $code = sub {
3943
3944 my $cluster_conf = load_clusterfw_conf();
3945 my $cluster_options = $cluster_conf->{options};
3946
3947 if (!$cluster_options->{enable}) {
3948 PVE::Firewall::remove_pvefw_chains();
3949 return;
3950 }
3951
3952 my $hostfw_conf = load_hostfw_conf($cluster_conf);
3953
3954 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
3955
3956 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
3957 };
3958
3959 run_locked($code);
3960 }
3961
3962 1;