]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
add dhcpv6 support to the dhcp option
[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", # allow DHCP
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-(?:$security_group_name_pattern)-(?: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"
1706 if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
1707 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1708 } elsif ($rule->{proto} && $rule->{proto} eq 'icmpv6') {
1709 # Note: we use dport to store --icmpv6-type
1710 die "unknown icmpv6-type '$rule->{dport}'\n"
1711 if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
1712 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1713 } else {
1714 if ($nbdport > 1) {
1715 if ($multiport == 2) {
1716 push @cmd, "--ports $rule->{dport}";
1717 } else {
1718 push @cmd, "--dports $rule->{dport}";
1719 }
1720 } else {
1721 push @cmd, "--dport $rule->{dport}";
1722 }
1723 }
1724 }
1725
1726 if ($rule->{sport}) {
1727 if ($nbsport > 1) {
1728 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1729 } else {
1730 push @cmd, "--sport $rule->{sport}";
1731 }
1732 }
1733 } elsif ($rule->{dport} || $rule->{sport}) {
1734 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1735 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
1736 }
1737
1738 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1739
1740 if (my $action = $rule->{action}) {
1741 $action = $actions->{$action} if defined($actions->{$action});
1742 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1743 push @cmd, $goto ? "-g $action" : "-j $action";
1744 }
1745
1746 return scalar(@cmd) ? join(' ', @cmd) : undef;
1747 }
1748
1749 sub ruleset_generate_rule {
1750 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1751
1752 my $rules;
1753
1754 if ($rule->{macro}) {
1755 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1756 } else {
1757 $rules = [ $rule ];
1758 }
1759
1760 # update all or nothing
1761
1762 my @cmds = ();
1763 foreach my $tmp (@$rules) {
1764 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1765 push @cmds, $cmdstr;
1766 }
1767 }
1768
1769 foreach my $cmdstr (@cmds) {
1770 ruleset_addrule($ruleset, $chain, $cmdstr);
1771 }
1772 }
1773
1774 sub ruleset_generate_rule_insert {
1775 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1776
1777 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1778
1779 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1780 ruleset_insertrule($ruleset, $chain, $cmdstr);
1781 }
1782 }
1783
1784 sub ruleset_create_chain {
1785 my ($ruleset, $chain) = @_;
1786
1787 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1788 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1789
1790 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1791
1792 $ruleset->{$chain} = [];
1793 }
1794
1795 sub ruleset_chain_exist {
1796 my ($ruleset, $chain) = @_;
1797
1798 return $ruleset->{$chain} ? 1 : undef;
1799 }
1800
1801 sub ruleset_addrule {
1802 my ($ruleset, $chain, $rule) = @_;
1803
1804 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1805
1806 push @{$ruleset->{$chain}}, "-A $chain $rule";
1807 }
1808
1809 sub ruleset_insertrule {
1810 my ($ruleset, $chain, $rule) = @_;
1811
1812 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1813
1814 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1815 }
1816
1817 sub get_log_rule_base {
1818 my ($chain, $vmid, $msg, $loglevel) = @_;
1819
1820 die "internal error - no log level" if !defined($loglevel);
1821
1822 $vmid = 0 if !defined($vmid);
1823
1824 # Note: we use special format for prefix to pass further
1825 # info to log daemon (VMID, LOGVELEL and CHAIN)
1826
1827 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1828 }
1829
1830 sub ruleset_addlog {
1831 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1832
1833 return if !defined($loglevel);
1834
1835 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1836
1837 $logrule = "$rule $logrule" if defined($rule);
1838
1839 ruleset_addrule($ruleset, $chain, $logrule);
1840 }
1841
1842 sub ruleset_add_chain_policy {
1843 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1844
1845 if ($policy eq 'ACCEPT') {
1846
1847 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1848 { ACCEPT => $accept_action});
1849
1850 } elsif ($policy eq 'DROP') {
1851
1852 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1853
1854 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1855
1856 ruleset_addrule($ruleset, $chain, "-j DROP");
1857 } elsif ($policy eq 'REJECT') {
1858 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1859
1860 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1861
1862 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1863 } else {
1864 # should not happen
1865 die "internal error: unknown policy '$policy'";
1866 }
1867 }
1868
1869 sub ruleset_chain_add_conn_filters {
1870 my ($ruleset, $chain, $accept) = @_;
1871
1872 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1873 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1874 }
1875
1876 sub ruleset_chain_add_input_filters {
1877 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
1878
1879 if ($cluster_conf->{ipset}->{blacklist}){
1880 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1881 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1882 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1883 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1884 }
1885 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1886 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
1887 }
1888
1889 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1890 if ($ipversion == 4) {
1891 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1892 }
1893 }
1894
1895 if ($options->{tcpflags}) {
1896 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1897 }
1898 }
1899
1900 sub ruleset_create_vm_chain {
1901 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1902
1903 ruleset_create_chain($ruleset, $chain);
1904 my $accept = generate_nfqueue($options);
1905
1906 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1907 if ($ipversion == 4) {
1908 if ($direction eq 'OUT') {
1909 ruleset_generate_rule($ruleset, $chain, $ipversion,
1910 { action => 'PVEFW-SET-ACCEPT-MARK',
1911 proto => 'udp', sport => 68, dport => 67 });
1912 } else {
1913 ruleset_generate_rule($ruleset, $chain, $ipversion,
1914 { action => 'ACCEPT',
1915 proto => 'udp', sport => 67, dport => 68 });
1916 }
1917 } elsif ($ipversion == 6) {
1918 if ($direction eq 'OUT') {
1919 ruleset_generate_rule($ruleset, $chain, $ipversion,
1920 { action => 'PVEFW-SET-ACCEPT-MARK',
1921 proto => 'udp', sport => 546, dport => 547 });
1922 } else {
1923 ruleset_generate_rule($ruleset, $chain, $ipversion,
1924 { action => 'ACCEPT',
1925 proto => 'udp', sport => 547, dport => 546 });
1926 }
1927 }
1928
1929 }
1930
1931 if ($direction eq 'OUT') {
1932 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1933 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
1934 }
1935 if ($ipfilter_ipset) {
1936 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP");
1937 }
1938 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1939 }
1940 }
1941
1942 sub ruleset_add_group_rule {
1943 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1944
1945 my $group = $rule->{action};
1946 my $group_chain = "GROUP-$group-$direction";
1947 if(!ruleset_chain_exist($ruleset, $group_chain)){
1948 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1949 }
1950
1951 if ($direction eq 'OUT' && $rule->{iface_out}) {
1952 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1953 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1954 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
1955 } else {
1956 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1957 }
1958
1959 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1960 }
1961
1962 sub ruleset_generate_vm_rules {
1963 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1964
1965 my $lc_direction = lc($direction);
1966
1967 my $in_accept = generate_nfqueue($options);
1968
1969 foreach my $rule (@$rules) {
1970 next if $rule->{iface} && $rule->{iface} ne $netid;
1971 next if !$rule->{enable} || $rule->{errors};
1972 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1973
1974 if ($rule->{type} eq 'group') {
1975 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1976 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1977 } else {
1978 next if $rule->{type} ne $lc_direction;
1979 eval {
1980 if ($direction eq 'OUT') {
1981 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1982 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
1983 undef, $cluster_conf, $vmfw_conf);
1984 } else {
1985 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1986 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
1987 undef, $cluster_conf, $vmfw_conf);
1988 }
1989 };
1990 warn $@ if $@;
1991 }
1992 }
1993 }
1994
1995 sub generate_nfqueue {
1996 my ($options) = @_;
1997
1998 if ($options->{ips}) {
1999 my $action = "NFQUEUE";
2000 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2001 if (defined($3) && defined($1)) {
2002 $action .= " --queue-balance $1:$3";
2003 } elsif (defined($1)) {
2004 $action .= " --queue-num $1";
2005 }
2006 }
2007 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
2008 return $action;
2009 } else {
2010 return "ACCEPT";
2011 }
2012 }
2013
2014 sub ruleset_generate_vm_ipsrules {
2015 my ($ruleset, $options, $direction, $iface) = @_;
2016
2017 if ($options->{ips} && $direction eq 'IN') {
2018 my $nfqueue = generate_nfqueue($options);
2019
2020 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
2021 ruleset_create_chain($ruleset, "PVEFW-IPS");
2022 }
2023
2024 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
2025 }
2026 }
2027
2028 sub generate_tap_rules_direction {
2029 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2030
2031 my $lc_direction = lc($direction);
2032
2033 my $rules = $vmfw_conf->{rules};
2034
2035 my $options = $vmfw_conf->{options};
2036 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2037
2038 my $tapchain = "$iface-$direction";
2039
2040 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2041 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2042 if $vmfw_conf->{ipset}->{$ipfilter_name};
2043
2044 # create chain with mac and ip filter
2045 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2046
2047 if ($options->{enable}) {
2048 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2049
2050 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2051
2052 # implement policy
2053 my $policy;
2054
2055 if ($direction eq 'OUT') {
2056 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2057 } else {
2058 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2059 }
2060
2061 my $accept = generate_nfqueue($options);
2062 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
2063 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2064 } else {
2065 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
2066 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2067 }
2068
2069 # plug the tap chain to bridge chain
2070 if ($direction eq 'IN') {
2071 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
2072 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
2073 } else {
2074 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
2075 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
2076 }
2077 }
2078
2079 sub enable_host_firewall {
2080 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2081
2082 my $options = $hostfw_conf->{options};
2083 my $cluster_options = $cluster_conf->{options};
2084 my $rules = $hostfw_conf->{rules};
2085 my $cluster_rules = $cluster_conf->{rules};
2086
2087 # host inbound firewall
2088 my $chain = "PVEFW-HOST-IN";
2089 ruleset_create_chain($ruleset, $chain);
2090
2091 my $loglevel = get_option_log_level($options, "log_level_in");
2092
2093 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
2094
2095 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2096 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2097
2098 # we use RETURN because we need to check also tap rules
2099 my $accept_action = 'RETURN';
2100
2101 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2102
2103 # add host rules first, so that cluster wide rules can be overwritten
2104 foreach my $rule (@$rules, @$cluster_rules) {
2105 next if !$rule->{enable} || $rule->{errors};
2106 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2107
2108 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2109
2110 eval {
2111 if ($rule->{type} eq 'group') {
2112 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2113 } elsif ($rule->{type} eq 'in') {
2114 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2115 { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2116 undef, $cluster_conf, $hostfw_conf);
2117 }
2118 };
2119 warn $@ if $@;
2120 delete $rule->{iface_in};
2121 }
2122
2123 # allow standard traffic for management ipset (includes cluster network)
2124 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management", $ipversion);
2125 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
2126 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
2127 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
2128 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2129 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
2130
2131 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2132 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2133
2134 # corosync
2135 if ($localnet && ($ipversion == $localnet_ver)) {
2136 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
2137 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
2138 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
2139 }
2140
2141 # implement input policy
2142 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2143 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2144
2145 # host outbound firewall
2146 $chain = "PVEFW-HOST-OUT";
2147 ruleset_create_chain($ruleset, $chain);
2148
2149 $loglevel = get_option_log_level($options, "log_level_out");
2150
2151 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
2152
2153 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2154
2155 # we use RETURN because we may want to check other thigs later
2156 $accept_action = 'RETURN';
2157
2158 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2159
2160 # add host rules first, so that cluster wide rules can be overwritten
2161 foreach my $rule (@$rules, @$cluster_rules) {
2162 next if !$rule->{enable} || $rule->{errors};
2163 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2164
2165 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2166 eval {
2167 if ($rule->{type} eq 'group') {
2168 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2169 } elsif ($rule->{type} eq 'out') {
2170 ruleset_generate_rule($ruleset, $chain, $ipversion,
2171 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
2172 undef, $cluster_conf, $hostfw_conf);
2173 }
2174 };
2175 warn $@ if $@;
2176 delete $rule->{iface_out};
2177 }
2178
2179 # allow standard traffic on cluster network
2180 if ($localnet && ($ipversion == $localnet_ver)) {
2181 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
2182 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
2183 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
2184 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2185
2186 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
2187 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
2188 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
2189 }
2190
2191 # implement output policy
2192 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2193 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2194
2195 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
2196 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
2197 }
2198
2199 sub generate_group_rules {
2200 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2201
2202 my $rules = $cluster_conf->{groups}->{$group};
2203
2204 if (!$rules) {
2205 warn "no such security group '$group'\n";
2206 $rules = []; # create empty chain
2207 }
2208
2209 my $chain = "GROUP-${group}-IN";
2210
2211 ruleset_create_chain($ruleset, $chain);
2212 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
2213
2214 foreach my $rule (@$rules) {
2215 next if $rule->{type} ne 'in';
2216 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2217 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2218 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2219 undef, $cluster_conf);
2220 }
2221
2222 $chain = "GROUP-${group}-OUT";
2223
2224 ruleset_create_chain($ruleset, $chain);
2225 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
2226
2227 foreach my $rule (@$rules) {
2228 next if $rule->{type} ne 'out';
2229 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2230 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2231 # check also other tap rules later
2232 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2233 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" },
2234 undef, $cluster_conf);
2235 }
2236 }
2237
2238 my $MAX_NETS = 32;
2239 my $valid_netdev_names = {};
2240 for (my $i = 0; $i < $MAX_NETS; $i++) {
2241 $valid_netdev_names->{"net$i"} = 1;
2242 }
2243
2244 sub parse_fw_rule {
2245 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2246
2247 my $orig_line = $line;
2248
2249 my $rule = {};
2250
2251 # we can add single line comments to the end of the rule
2252 if ($line =~ s/#\s*(.*?)\s*$//) {
2253 $rule->{comment} = decode('utf8', $1);
2254 }
2255
2256 # we can disable a rule when prefixed with '|'
2257
2258 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2259
2260 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2261 die "unable to parse rule: $line\n";
2262
2263 $rule->{type} = lc($1);
2264 $rule->{action} = $2;
2265
2266 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2267 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2268 $rule->{macro} = $1;
2269 $rule->{action} = $2;
2270 }
2271 }
2272
2273 while (length($line)) {
2274 if ($line =~ s/^-i (\S+)\s*//) {
2275 $rule->{iface} = $1;
2276 next;
2277 }
2278
2279 last if $rule->{type} eq 'group';
2280
2281 if ($line =~ s/^-p (\S+)\s*//) {
2282 $rule->{proto} = $1;
2283 next;
2284 }
2285
2286 if ($line =~ s/^-dport (\S+)\s*//) {
2287 $rule->{dport} = $1;
2288 next;
2289 }
2290
2291 if ($line =~ s/^-sport (\S+)\s*//) {
2292 $rule->{sport} = $1;
2293 next;
2294 }
2295 if ($line =~ s/^-source (\S+)\s*//) {
2296 $rule->{source} = $1;
2297 next;
2298 }
2299 if ($line =~ s/^-dest (\S+)\s*//) {
2300 $rule->{dest} = $1;
2301 next;
2302 }
2303
2304 last;
2305 }
2306
2307 die "unable to parse rule parameters: $line\n" if length($line);
2308
2309 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2310 if ($verbose && $rule->{errors}) {
2311 warn "$prefix - errors in rule parameters: $orig_line\n";
2312 foreach my $p (keys %{$rule->{errors}}) {
2313 warn " $p: $rule->{errors}->{$p}\n";
2314 }
2315 }
2316
2317 return $rule;
2318 }
2319
2320 sub parse_vmfw_option {
2321 my ($line) = @_;
2322
2323 my ($opt, $value);
2324
2325 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2326
2327 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2328 $opt = lc($1);
2329 $value = int($2);
2330 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2331 $opt = lc($1);
2332 $value = $2 ? lc($3) : '';
2333 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2334 $opt = lc($1);
2335 $value = uc($3);
2336 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2337 $opt = lc($1);
2338 $value = $2;
2339 } else {
2340 die "can't parse option '$line'\n"
2341 }
2342
2343 return ($opt, $value);
2344 }
2345
2346 sub parse_hostfw_option {
2347 my ($line) = @_;
2348
2349 my ($opt, $value);
2350
2351 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2352
2353 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2354 $opt = lc($1);
2355 $value = int($2);
2356 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2357 $opt = lc($1);
2358 $value = $2 ? lc($3) : '';
2359 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2360 $opt = lc($1);
2361 $value = int($2);
2362 } else {
2363 die "can't parse option '$line'\n"
2364 }
2365
2366 return ($opt, $value);
2367 }
2368
2369 sub parse_clusterfw_option {
2370 my ($line) = @_;
2371
2372 my ($opt, $value);
2373
2374 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2375 $opt = lc($1);
2376 $value = int($2);
2377 if (($value > 1) && ((time() - $value) > 60)) {
2378 $value = 0
2379 }
2380 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2381 $opt = lc($1);
2382 $value = uc($3);
2383 } else {
2384 die "can't parse option '$line'\n"
2385 }
2386
2387 return ($opt, $value);
2388 }
2389
2390 sub resolve_alias {
2391 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2392
2393 my $alias = lc($cidr);
2394 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2395 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2396
2397 die "no such alias '$cidr'\n" if !$e;;
2398
2399 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2400 }
2401
2402 sub parse_ip_or_cidr {
2403 my ($cidr) = @_;
2404
2405 my $ipversion;
2406
2407 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2408 $cidr =~ s|/128$||;
2409 $ipversion = 6;
2410 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2411 $cidr =~ s|/32$||;
2412 $ipversion = 4;
2413 } else {
2414 die "value does not look like a valid IP address or CIDR network\n";
2415 }
2416
2417 return wantarray ? ($cidr, $ipversion) : $cidr;
2418 }
2419
2420 sub parse_alias {
2421 my ($line) = @_;
2422
2423 # we can add single line comments to the end of the line
2424 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2425
2426 if ($line =~ m/^(\S+)\s(\S+)$/) {
2427 my ($name, $cidr) = ($1, $2);
2428 my $ipversion;
2429
2430 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2431
2432 my $data = {
2433 name => $name,
2434 cidr => $cidr,
2435 ipversion => $ipversion,
2436 };
2437 $data->{comment} = $comment if $comment;
2438 return $data;
2439 }
2440
2441 return undef;
2442 }
2443
2444 sub generic_fw_config_parser {
2445 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2446
2447 my $section;
2448 my $group;
2449
2450 my $res = $empty_conf;
2451
2452 while (defined(my $line = <$fh>)) {
2453 next if $line =~ m/^#/;
2454 next if $line =~ m/^\s*$/;
2455
2456 chomp $line;
2457
2458 my $linenr = $fh->input_line_number();
2459 my $prefix = "$filename (line $linenr)";
2460
2461 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2462 $section = 'options';
2463 next;
2464 }
2465
2466 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2467 $section = 'aliases';
2468 next;
2469 }
2470
2471 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2472 $section = 'groups';
2473 $group = lc($1);
2474 my $comment = $2;
2475 eval {
2476 die "security group name too long\n" if length($group) > $max_group_name_length;
2477 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2478 };
2479 if (my $err = $@) {
2480 ($section, $group, $comment) = undef;
2481 warn "$prefix: $err";
2482 next;
2483 }
2484
2485 $res->{$section}->{$group} = [];
2486 $res->{group_comments}->{$group} = decode('utf8', $comment)
2487 if $comment;
2488 next;
2489 }
2490
2491 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2492 $section = 'rules';
2493 next;
2494 }
2495
2496 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2497 $section = 'ipset';
2498 $group = lc($1);
2499 my $comment = $2;
2500 eval {
2501 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2502 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2503 };
2504 if (my $err = $@) {
2505 ($section, $group, $comment) = undef;
2506 warn "$prefix: $err";
2507 next;
2508 }
2509
2510 $res->{$section}->{$group} = [];
2511 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2512 if $comment;
2513 next;
2514 }
2515
2516 if (!$section) {
2517 warn "$prefix: skip line - no section\n";
2518 next;
2519 }
2520
2521 if ($section eq 'options') {
2522 eval {
2523 my ($opt, $value);
2524 if ($rule_env eq 'cluster') {
2525 ($opt, $value) = parse_clusterfw_option($line);
2526 } elsif ($rule_env eq 'host') {
2527 ($opt, $value) = parse_hostfw_option($line);
2528 } else {
2529 ($opt, $value) = parse_vmfw_option($line);
2530 }
2531 $res->{options}->{$opt} = $value;
2532 };
2533 warn "$prefix: $@" if $@;
2534 } elsif ($section eq 'aliases') {
2535 eval {
2536 my $data = parse_alias($line);
2537 $res->{aliases}->{lc($data->{name})} = $data;
2538 };
2539 warn "$prefix: $@" if $@;
2540 } elsif ($section eq 'rules') {
2541 my $rule;
2542 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2543 if (my $err = $@) {
2544 warn "$prefix: $err";
2545 next;
2546 }
2547 push @{$res->{$section}}, $rule;
2548 } elsif ($section eq 'groups') {
2549 my $rule;
2550 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
2551 if (my $err = $@) {
2552 warn "$prefix: $err";
2553 next;
2554 }
2555 push @{$res->{$section}->{$group}}, $rule;
2556 } elsif ($section eq 'ipset') {
2557 # we can add single line comments to the end of the rule
2558 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2559
2560 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2561 my $nomatch = $1;
2562 my $cidr = $2;
2563 my $errors;
2564
2565 if ($nomatch && !$feature_ipset_nomatch) {
2566 $errors->{nomatch} = "nomatch not supported by kernel";
2567 }
2568
2569 eval {
2570 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2571 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2572 } else {
2573 $cidr = parse_ip_or_cidr($cidr);
2574 }
2575 };
2576 if (my $err = $@) {
2577 chomp $err;
2578 $errors->{cidr} = $err;
2579 }
2580
2581 my $entry = { cidr => $cidr };
2582 $entry->{nomatch} = 1 if $nomatch;
2583 $entry->{comment} = $comment if $comment;
2584 $entry->{errors} = $errors if $errors;
2585
2586 if ($verbose && $errors) {
2587 warn "$prefix - errors in ipset '$group': $line\n";
2588 foreach my $p (keys %{$errors}) {
2589 warn " $p: $errors->{$p}\n";
2590 }
2591 }
2592
2593 push @{$res->{$section}->{$group}}, $entry;
2594 } else {
2595 warn "$prefix: skip line - unknown section\n";
2596 next;
2597 }
2598 }
2599
2600 return $res;
2601 }
2602
2603 sub parse_hostfw_config {
2604 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2605
2606 my $empty_conf = { rules => [], options => {}};
2607
2608 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
2609 }
2610
2611 sub parse_vmfw_config {
2612 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2613
2614 my $empty_conf = {
2615 rules => [],
2616 options => {},
2617 aliases => {},
2618 ipset => {} ,
2619 ipset_comments => {},
2620 };
2621
2622 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2623 }
2624
2625 sub parse_clusterfw_config {
2626 my ($filename, $fh, $verbose) = @_;
2627
2628 my $section;
2629 my $group;
2630
2631 my $empty_conf = {
2632 rules => [],
2633 options => {},
2634 aliases => {},
2635 groups => {},
2636 group_comments => {},
2637 ipset => {} ,
2638 ipset_comments => {},
2639 };
2640
2641 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
2642 }
2643
2644 sub run_locked {
2645 my ($code, @param) = @_;
2646
2647 my $timeout = 10;
2648
2649 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2650
2651 die $@ if $@;
2652
2653 return $res;
2654 }
2655
2656 sub read_local_vm_config {
2657
2658 my $qemu = {};
2659 my $lxc = {};
2660
2661 my $vmdata = { qemu => $qemu, lxc => $lxc };
2662
2663 my $vmlist = PVE::Cluster::get_vmlist();
2664 return $vmdata if !$vmlist || !$vmlist->{ids};
2665 my $ids = $vmlist->{ids};
2666
2667 foreach my $vmid (keys %$ids) {
2668 next if !$vmid; # skip VE0
2669 my $d = $ids->{$vmid};
2670 next if !$d->{node} || $d->{node} ne $nodename;
2671 next if !$d->{type};
2672 if ($d->{type} eq 'qemu') {
2673 if ($have_qemu_server) {
2674 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2675 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2676 $qemu->{$vmid} = $conf;
2677 }
2678 }
2679 } elsif ($d->{type} eq 'lxc') {
2680 if ($have_lxc) {
2681 my $cfspath = PVE::LXC::cfs_config_path($vmid);
2682 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2683 $lxc->{$vmid} = $conf;
2684 }
2685 }
2686 }
2687 }
2688
2689 return $vmdata;
2690 };
2691
2692 sub load_vmfw_conf {
2693 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2694
2695 my $vmfw_conf = {};
2696
2697 $dir = $pvefw_conf_dir if !defined($dir);
2698
2699 my $filename = "$dir/$vmid.fw";
2700 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2701 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2702 $vmfw_conf->{vmid} = $vmid;
2703 }
2704
2705 return $vmfw_conf;
2706 }
2707
2708 my $format_rules = sub {
2709 my ($rules, $allow_iface) = @_;
2710
2711 my $raw = '';
2712
2713 foreach my $rule (@$rules) {
2714 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2715 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2716 $raw .= uc($rule->{type});
2717 if ($rule->{macro}) {
2718 $raw .= " $rule->{macro}($rule->{action})";
2719 } else {
2720 $raw .= " " . $rule->{action};
2721 }
2722 if ($allow_iface && $rule->{iface}) {
2723 $raw .= " -i $rule->{iface}";
2724 }
2725
2726 if ($rule->{type} ne 'group') {
2727 $raw .= " -source $rule->{source}" if $rule->{source};
2728 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2729 $raw .= " -p $rule->{proto}" if $rule->{proto};
2730 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2731 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2732 }
2733
2734 $raw .= " # " . encode('utf8', $rule->{comment})
2735 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2736 $raw .= "\n";
2737 } else {
2738 die "unknown rule type '$rule->{type}'";
2739 }
2740 }
2741
2742 return $raw;
2743 };
2744
2745 my $format_options = sub {
2746 my ($options) = @_;
2747
2748 my $raw = '';
2749
2750 $raw .= "[OPTIONS]\n\n";
2751 foreach my $opt (keys %$options) {
2752 $raw .= "$opt: $options->{$opt}\n";
2753 }
2754 $raw .= "\n";
2755
2756 return $raw;
2757 };
2758
2759 my $format_aliases = sub {
2760 my ($aliases) = @_;
2761
2762 my $raw = '';
2763
2764 $raw .= "[ALIASES]\n\n";
2765 foreach my $k (keys %$aliases) {
2766 my $e = $aliases->{$k};
2767 $raw .= "$e->{name} $e->{cidr}";
2768 $raw .= " # " . encode('utf8', $e->{comment})
2769 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2770 $raw .= "\n";
2771 }
2772 $raw .= "\n";
2773
2774 return $raw;
2775 };
2776
2777 my $format_ipsets = sub {
2778 my ($fw_conf) = @_;
2779
2780 my $raw = '';
2781
2782 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2783 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2784 my $utf8comment = encode('utf8', $comment);
2785 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2786 } else {
2787 $raw .= "[IPSET $ipset]\n\n";
2788 }
2789 my $options = $fw_conf->{ipset}->{$ipset};
2790
2791 my $nethash = {};
2792 foreach my $entry (@$options) {
2793 $nethash->{$entry->{cidr}} = $entry;
2794 }
2795
2796 foreach my $cidr (sort keys %$nethash) {
2797 my $entry = $nethash->{$cidr};
2798 my $line = $entry->{nomatch} ? '!' : '';
2799 $line .= $entry->{cidr};
2800 $line .= " # " . encode('utf8', $entry->{comment})
2801 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2802 $raw .= "$line\n";
2803 }
2804
2805 $raw .= "\n";
2806 }
2807
2808 return $raw;
2809 };
2810
2811 sub save_vmfw_conf {
2812 my ($vmid, $vmfw_conf) = @_;
2813
2814 my $raw = '';
2815
2816 my $options = $vmfw_conf->{options};
2817 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2818
2819 my $aliases = $vmfw_conf->{aliases};
2820 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2821
2822 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2823
2824 my $rules = $vmfw_conf->{rules} || [];
2825 if ($rules && scalar(@$rules)) {
2826 $raw .= "[RULES]\n\n";
2827 $raw .= &$format_rules($rules, 1);
2828 $raw .= "\n";
2829 }
2830
2831 mkdir $pvefw_conf_dir;
2832
2833 my $filename = "$pvefw_conf_dir/$vmid.fw";
2834 PVE::Tools::file_set_contents($filename, $raw);
2835 }
2836
2837 sub remove_vmfw_conf {
2838 my ($vmid) = @_;
2839
2840 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
2841
2842 unlink $vmfw_conffile;
2843 }
2844
2845 sub clone_vmfw_conf {
2846 my ($vmid, $newid) = @_;
2847
2848 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
2849 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
2850
2851 if (-f $clonevm_conffile) {
2852 unlink $clonevm_conffile;
2853 }
2854 if (-f $sourcevm_conffile) {
2855 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
2856 PVE::Tools::file_set_contents($clonevm_conffile, $data);
2857 }
2858 }
2859
2860 sub read_vm_firewall_configs {
2861 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2862
2863 my $vmfw_configs = {};
2864
2865 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2866 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
2867 next if !$vmfw_conf->{options}; # skip if file does not exists
2868 $vmfw_configs->{$vmid} = $vmfw_conf;
2869 }
2870 foreach my $vmid (keys %{$vmdata->{lxc}}) {
2871 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
2872 next if !$vmfw_conf->{options}; # skip if file does not exists
2873 $vmfw_configs->{$vmid} = $vmfw_conf;
2874 }
2875
2876 return $vmfw_configs;
2877 }
2878
2879 sub get_option_log_level {
2880 my ($options, $k) = @_;
2881
2882 my $v = $options->{$k};
2883 $v = $default_log_level if !defined($v);
2884
2885 return undef if $v eq '' || $v eq 'nolog';
2886
2887 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2888
2889 return $v if ($v >= 0) && ($v <= 7);
2890
2891 warn "unknown log level ($k = '$v')\n";
2892
2893 return undef;
2894 }
2895
2896 sub generate_std_chains {
2897 my ($ruleset, $options, $ipversion) = @_;
2898
2899 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2900
2901 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2902
2903 my $chain;
2904
2905 if ($ipversion == 4) {
2906 # same as shorewall smurflog.
2907 $chain = 'PVEFW-smurflog';
2908 $std_chains->{$chain} = [];
2909
2910 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2911 push @{$std_chains->{$chain}}, "-j DROP";
2912 }
2913
2914 # same as shorewall logflags action.
2915 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2916 $chain = 'PVEFW-logflags';
2917 $std_chains->{$chain} = [];
2918
2919 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2920 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2921 push @{$std_chains->{$chain}}, "-j DROP";
2922
2923 foreach my $chain (keys %$std_chains) {
2924 ruleset_create_chain($ruleset, $chain);
2925 foreach my $rule (@{$std_chains->{$chain}}) {
2926 if (ref($rule)) {
2927 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
2928 } else {
2929 ruleset_addrule($ruleset, $chain, $rule);
2930 }
2931 }
2932 }
2933 }
2934
2935 sub generate_ipset_chains {
2936 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_; #fixme
2937
2938 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2939
2940 my $options = $fw_conf->{ipset}->{$ipset};
2941
2942 # remove duplicates
2943 my $nethash = {};
2944 foreach my $entry (@$options) {
2945 next if $entry->{errors}; # skip entries with errors
2946 eval {
2947 my ($cidr, $ver);
2948 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2949 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2950 } else {
2951 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
2952 }
2953 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2954 if ($ver == 6) {
2955 $cidr = lc(Net::IP::ip_compress_address($cidr, 6));
2956 $cidr =~ s|/128$||;
2957 } else {
2958 $cidr =~ s|/32$||;
2959 }
2960
2961 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2962 };
2963 warn $@ if $@;
2964 }
2965
2966 foreach my $ipversion (4, 6) {
2967 my $data = $nethash->{$ipversion};
2968
2969 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
2970
2971 my $hashsize = scalar(@$options);
2972 if ($hashsize <= 64) {
2973 $hashsize = 64;
2974 } else {
2975 $hashsize = round_powerof2($hashsize);
2976 }
2977
2978 my $family = $ipversion == "6" ? "inet6" : "inet";
2979
2980 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
2981
2982 foreach my $cidr (sort keys %$data) {
2983 my $entry = $data->{$cidr};
2984
2985 my $cmd = "add $name $cidr";
2986 if ($entry->{nomatch}) {
2987 if ($feature_ipset_nomatch) {
2988 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2989 } else {
2990 warn "ignore !$cidr - nomatch not supported by kernel\n";
2991 }
2992 } else {
2993 push @{$ipset_ruleset->{$name}}, $cmd;
2994 }
2995 }
2996 }
2997 }
2998 }
2999
3000 sub round_powerof2 {
3001 my ($int) = @_;
3002
3003 $int--;
3004 $int |= $int >> $_ foreach (1,2,4,8,16);
3005 return ++$int;
3006 }
3007
3008 sub load_clusterfw_conf {
3009 my ($filename, $verbose) = @_;
3010
3011 $filename = $clusterfw_conf_filename if !defined($filename);
3012
3013 my $cluster_conf = {};
3014 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3015 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3016 }
3017
3018 return $cluster_conf;
3019 }
3020
3021 sub save_clusterfw_conf {
3022 my ($cluster_conf) = @_;
3023
3024 my $raw = '';
3025
3026 my $options = $cluster_conf->{options};
3027 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3028
3029 my $aliases = $cluster_conf->{aliases};
3030 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3031
3032 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3033
3034 my $rules = $cluster_conf->{rules};
3035 if ($rules && scalar(@$rules)) {
3036 $raw .= "[RULES]\n\n";
3037 $raw .= &$format_rules($rules, 1);
3038 $raw .= "\n";
3039 }
3040
3041 if ($cluster_conf->{groups}) {
3042 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3043 my $rules = $cluster_conf->{groups}->{$group};
3044 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3045 my $utf8comment = encode('utf8', $comment);
3046 $raw .= "[group $group] # $utf8comment\n\n";
3047 } else {
3048 $raw .= "[group $group]\n\n";
3049 }
3050
3051 $raw .= &$format_rules($rules, 0);
3052 $raw .= "\n";
3053 }
3054 }
3055
3056 mkdir $pvefw_conf_dir;
3057 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3058 }
3059
3060 sub load_hostfw_conf {
3061 my ($cluster_conf, $filename, $verbose) = @_;
3062
3063 $filename = $hostfw_conf_filename if !defined($filename);
3064
3065 my $hostfw_conf = {};
3066 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3067 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3068 }
3069 return $hostfw_conf;
3070 }
3071
3072 sub save_hostfw_conf {
3073 my ($hostfw_conf) = @_;
3074
3075 my $raw = '';
3076
3077 my $options = $hostfw_conf->{options};
3078 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3079
3080 my $rules = $hostfw_conf->{rules};
3081 if ($rules && scalar(@$rules)) {
3082 $raw .= "[RULES]\n\n";
3083 $raw .= &$format_rules($rules, 1);
3084 $raw .= "\n";
3085 }
3086
3087 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3088 }
3089
3090 sub compile {
3091 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3092
3093 my $vmfw_configs;
3094
3095 if ($vmdata) { # test mode
3096 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3097 my $filename = "$testdir/cluster.fw";
3098 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3099
3100 $filename = "$testdir/host.fw";
3101 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3102
3103 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3104 } else { # normal operation
3105 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3106
3107 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3108
3109 $vmdata = read_local_vm_config();
3110 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3111 }
3112
3113 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3114 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3115
3116 return ($ruleset, $ipset_ruleset, $rulesetv6);
3117 }
3118
3119 sub compile_iptables_filter {
3120 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3121
3122 my $localnet;
3123 if ($cluster_conf->{aliases}->{local_network}) {
3124 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3125 } else {
3126 my $localnet_ver;
3127 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3128
3129 $cluster_conf->{aliases}->{local_network} = {
3130 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
3131 }
3132
3133 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3134
3135 return ({}, {}) if !$cluster_conf->{options}->{enable};
3136
3137 my $ruleset = {};
3138
3139 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3140 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3141
3142 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3143
3144 my $hostfw_options = $hostfw_conf->{options} || {};
3145
3146 # fixme: what log level should we use here?
3147 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3148
3149 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3150
3151 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3152 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3153
3154 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3155
3156 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3157 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3158
3159 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3160
3161 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3162
3163 my $ipset_ruleset = {};
3164
3165 if ($hostfw_enable) {
3166 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3167 warn $@ if $@; # just to be sure - should not happen
3168 }
3169
3170 # generate firewall rules for QEMU VMs
3171 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3172 eval {
3173 my $conf = $vmdata->{qemu}->{$vmid};
3174 my $vmfw_conf = $vmfw_configs->{$vmid};
3175 return if !$vmfw_conf;
3176
3177 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3178
3179 foreach my $netid (keys %$conf) {
3180 next if $netid !~ m/^net(\d+)$/;
3181 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3182 next if !$net->{firewall};
3183 my $iface = "tap${vmid}i$1";
3184
3185 my $macaddr = $net->{macaddr};
3186 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3187 $vmfw_conf, $vmid, 'IN', $ipversion);
3188 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3189 $vmfw_conf, $vmid, 'OUT', $ipversion);
3190 }
3191 };
3192 warn $@ if $@; # just to be sure - should not happen
3193 }
3194
3195 # generate firewall rules for LXC containers
3196 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3197 eval {
3198 my $conf = $vmdata->{lxc}->{$vmid};
3199 my $vmfw_conf = $vmfw_configs->{$vmid};
3200 return if !$vmfw_conf;
3201
3202 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3203
3204 if ($vmfw_conf->{options}->{enable}) {
3205 foreach my $netid (keys %$conf) {
3206 next if $netid !~ m/^net(\d+)$/;
3207 my $net = PVE::LXC::parse_lxc_network($conf->{$netid});
3208 next if !$net->{firewall};
3209 my $iface = "veth${vmid}i$1";
3210 my $macaddr = $net->{hwaddr};
3211 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3212 $vmfw_conf, $vmid, 'IN', $ipversion);
3213 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3214 $vmfw_conf, $vmid, 'OUT', $ipversion);
3215 }
3216 }
3217 };
3218 warn $@ if $@; # just to be sure - should not happen
3219 }
3220
3221 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3222 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3223 }
3224
3225 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3226
3227 return ($ruleset, $ipset_ruleset);
3228 }
3229
3230 sub get_ruleset_status {
3231 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3232
3233 my $statushash = {};
3234
3235 foreach my $chain (sort keys %$ruleset) {
3236 my $sig = &$digest_fn($ruleset->{$chain});
3237
3238 $statushash->{$chain}->{sig} = $sig;
3239
3240 my $oldsig = $active_chains->{$chain};
3241 if (!defined($oldsig)) {
3242 $statushash->{$chain}->{action} = 'create';
3243 } else {
3244 if ($oldsig eq $sig) {
3245 $statushash->{$chain}->{action} = 'exists';
3246 } else {
3247 $statushash->{$chain}->{action} = 'update';
3248 }
3249 }
3250 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3251 foreach my $cmd (@{$ruleset->{$chain}}) {
3252 print "\t$cmd\n" if $verbose;
3253 }
3254 }
3255
3256 foreach my $chain (sort keys %$active_chains) {
3257 if (!defined($ruleset->{$chain})) {
3258 my $sig = $active_chains->{$chain};
3259 $statushash->{$chain}->{action} = 'delete';
3260 $statushash->{$chain}->{sig} = $sig;
3261 print "delete $chain ($sig)\n" if $verbose;
3262 }
3263 }
3264
3265 return $statushash;
3266 }
3267
3268 sub print_sig_rule {
3269 my ($chain, $sig) = @_;
3270
3271 # We just use this to store a SHA1 checksum used to detect changes
3272 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3273 }
3274
3275 sub get_ruleset_cmdlist {
3276 my ($ruleset, $verbose, $iptablescmd) = @_;
3277
3278 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3279
3280 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3281 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3282
3283 # create missing chains first
3284 foreach my $chain (sort keys %$ruleset) {
3285 my $stat = $statushash->{$chain};
3286 die "internal error" if !$stat;
3287 next if $stat->{action} ne 'create';
3288
3289 $cmdlist .= ":$chain - [0:0]\n";
3290 }
3291
3292 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3293 my $chain = "PVEFW-$h";
3294 if ($ruleset->{$chain} && !$hooks->{$h}) {
3295 $cmdlist .= "-A $h -j $chain\n";
3296 }
3297 }
3298
3299 foreach my $chain (sort keys %$ruleset) {
3300 my $stat = $statushash->{$chain};
3301 die "internal error" if !$stat;
3302
3303 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3304 $cmdlist .= "-F $chain\n";
3305 foreach my $cmd (@{$ruleset->{$chain}}) {
3306 $cmdlist .= "$cmd\n";
3307 }
3308 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3309 } elsif ($stat->{action} eq 'delete') {
3310 die "internal error"; # this should not happen
3311 } elsif ($stat->{action} eq 'exists') {
3312 # do nothing
3313 } else {
3314 die "internal error - unknown status '$stat->{action}'";
3315 }
3316 }
3317
3318 foreach my $chain (keys %$statushash) {
3319 next if $statushash->{$chain}->{action} ne 'delete';
3320 $cmdlist .= "-F $chain\n";
3321 }
3322 foreach my $chain (keys %$statushash) {
3323 next if $statushash->{$chain}->{action} ne 'delete';
3324 next if $chain eq 'PVEFW-INPUT';
3325 next if $chain eq 'PVEFW-OUTPUT';
3326 next if $chain eq 'PVEFW-FORWARD';
3327 $cmdlist .= "-X $chain\n";
3328 }
3329
3330 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
3331
3332 $cmdlist .= "COMMIT\n";
3333
3334 return wantarray ? ($cmdlist, $changes) : $cmdlist;
3335 }
3336
3337 sub get_ipset_cmdlist {
3338 my ($ruleset, $verbose) = @_;
3339
3340 my $cmdlist = "";
3341
3342 my $delete_cmdlist = "";
3343
3344 my $active_chains = ipset_get_chains();
3345 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
3346
3347 # remove stale _swap chains
3348 foreach my $chain (keys %$active_chains) {
3349 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3350 $cmdlist .= "destroy $chain\n";
3351 }
3352 }
3353
3354 foreach my $chain (keys %$ruleset) {
3355 my $stat = $statushash->{$chain};
3356 die "internal error" if !$stat;
3357
3358 if ($stat->{action} eq 'create') {
3359 foreach my $cmd (@{$ruleset->{$chain}}) {
3360 $cmdlist .= "$cmd\n";
3361 }
3362 }
3363 }
3364
3365 foreach my $chain (keys %$ruleset) {
3366 my $stat = $statushash->{$chain};
3367 die "internal error" if !$stat;
3368
3369 if ($stat->{action} eq 'update') {
3370 my $chain_swap = $chain."_swap";
3371
3372 foreach my $cmd (@{$ruleset->{$chain}}) {
3373 $cmd =~ s/$chain/$chain_swap/;
3374 $cmdlist .= "$cmd\n";
3375 }
3376 $cmdlist .= "swap $chain_swap $chain\n";
3377 $cmdlist .= "flush $chain_swap\n";
3378 $cmdlist .= "destroy $chain_swap\n";
3379 }
3380 }
3381
3382 # the remove unused chains
3383 foreach my $chain (keys %$statushash) {
3384 next if $statushash->{$chain}->{action} ne 'delete';
3385
3386 $delete_cmdlist .= "flush $chain\n";
3387 $delete_cmdlist .= "destroy $chain\n";
3388 }
3389
3390 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
3391
3392 return ($cmdlist, $delete_cmdlist, $changes);
3393 }
3394
3395 sub apply_ruleset {
3396 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3397
3398 enable_bridge_firewall();
3399
3400 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3401 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
3402
3403 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
3404 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
3405
3406 if ($verbose) {
3407 if ($ipset_changes) {
3408 print "ipset changes:\n";
3409 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3410 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3411 }
3412
3413 if ($changes) {
3414 print "iptables changes:\n";
3415 print $cmdlist;
3416 }
3417
3418 if ($changesv6) {
3419 print "ip6tables changes:\n";
3420 print $cmdlistv6;
3421 }
3422 }
3423
3424 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3425 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3426
3427 ipset_restore_cmdlist($ipset_create_cmdlist);
3428
3429 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3430 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3431
3432 iptables_restore_cmdlist($cmdlist);
3433
3434 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3435 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3436
3437 ip6tables_restore_cmdlist($cmdlistv6);
3438
3439 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3440 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3441
3442 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3443
3444 # test: re-read status and check if everything is up to date
3445 my $active_chains = iptables_get_chains();
3446 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3447
3448 my $errors;
3449 foreach my $chain (sort keys %$ruleset) {
3450 my $stat = $statushash->{$chain};
3451 if ($stat->{action} ne 'exists') {
3452 warn "unable to update chain '$chain'\n";
3453 $errors = 1;
3454 }
3455 }
3456
3457 my $active_chainsv6 = iptables_get_chains("ip6tables");
3458 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3459
3460 foreach my $chain (sort keys %$rulesetv6) {
3461 my $stat = $statushashv6->{$chain};
3462 if ($stat->{action} ne 'exists') {
3463 warn "unable to update chain '$chain'\n";
3464 $errors = 1;
3465 }
3466 }
3467
3468 die "unable to apply firewall changes\n" if $errors;
3469
3470 update_nf_conntrack_max($hostfw_conf);
3471
3472 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3473
3474 }
3475
3476 sub update_nf_conntrack_max {
3477 my ($hostfw_conf) = @_;
3478
3479 my $max = 65536; # reasonable default
3480
3481 my $options = $hostfw_conf->{options} || {};
3482
3483 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3484 $max = $options->{nf_conntrack_max};
3485 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3486 }
3487
3488 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3489 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3490
3491 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3492
3493 if ($current != $max) {
3494 my $hashsize = int($max/4);
3495 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3496 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3497 }
3498 }
3499
3500 sub update_nf_conntrack_tcp_timeout_established {
3501 my ($hostfw_conf) = @_;
3502
3503 my $options = $hostfw_conf->{options} || {};
3504
3505 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3506
3507 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3508 }
3509
3510 sub remove_pvefw_chains {
3511
3512 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3513 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3514 PVE::Firewall::remove_pvefw_chains_ipset();
3515
3516 }
3517
3518 sub remove_pvefw_chains_iptables {
3519 my ($iptablescmd) = @_;
3520
3521 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
3522 my $cmdlist = "*filter\n";
3523
3524 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3525 if ($hooks->{$h}) {
3526 $cmdlist .= "-D $h -j PVEFW-$h\n";
3527 }
3528 }
3529
3530 foreach my $chain (keys %$chash) {
3531 $cmdlist .= "-F $chain\n";
3532 }
3533
3534 foreach my $chain (keys %$chash) {
3535 $cmdlist .= "-X $chain\n";
3536 }
3537 $cmdlist .= "COMMIT\n";
3538
3539 if($iptablescmd eq "ip6tables") {
3540 ip6tables_restore_cmdlist($cmdlist);
3541 } else {
3542 iptables_restore_cmdlist($cmdlist);
3543 }
3544 }
3545
3546 sub remove_pvefw_chains_ipset {
3547
3548 my $ipset_chains = ipset_get_chains();
3549
3550 my $cmdlist = "";
3551
3552 foreach my $chain (keys %$ipset_chains) {
3553 $cmdlist .= "flush $chain\n";
3554 $cmdlist .= "destroy $chain\n";
3555 }
3556
3557 ipset_restore_cmdlist($cmdlist) if $cmdlist;
3558 }
3559
3560 sub init {
3561 my $cluster_conf = load_clusterfw_conf();
3562 my $cluster_options = $cluster_conf->{options};
3563 my $enable = $cluster_options->{enable};
3564
3565 return if !$enable;
3566
3567 # load required modules here
3568 }
3569
3570 sub update {
3571 my $code = sub {
3572
3573 my $cluster_conf = load_clusterfw_conf();
3574 my $cluster_options = $cluster_conf->{options};
3575
3576 if (!$cluster_options->{enable}) {
3577 PVE::Firewall::remove_pvefw_chains();
3578 return;
3579 }
3580
3581 my $hostfw_conf = load_hostfw_conf($cluster_conf);
3582
3583 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
3584
3585 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
3586 };
3587
3588 run_locked($code);
3589 }
3590
3591 1;