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