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