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