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