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