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