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