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