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