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