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