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