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