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