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