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