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