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