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