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