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