]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
allow tests without cluster.fw and host.fw configuration
[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 cluster_network {
711 my ($new_value) = @_;
712
713 $__cluster_network = $new_value if defined($new_value);
714
715 return $__cluster_network if defined($__cluster_network);
716
717 eval {
718 my $nodename = PVE::INotify::nodename();
719
720 my $ip = PVE::Cluster::remote_node_ip($nodename);
721
722 my $testip = Net::IP->new($ip);
723
724 my $routes = PVE::ProcFSTools::read_proc_net_route();
725 foreach my $entry (@$routes) {
726 my $mask = $ipv4_mask_hash_clusternet->{$entry->{mask}};
727 next if !defined($mask);
728 return if $mask eq '0.0.0.0';
729 my $cidr = "$entry->{dest}/$mask";
730 my $testnet = Net::IP->new($cidr);
731 if ($testnet->overlaps($testip)) {
732 $__cluster_network = $cidr;
733 return;
734 }
735 }
736 };
737 warn $@ if $@;
738
739 return $__cluster_network;
740 }
741
742 sub parse_address_list {
743 my ($str) = @_;
744
745 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
746 return if $str =~ m/^${ip_alias_pattern}$/;
747
748 my $count = 0;
749 my $iprange = 0;
750 foreach my $elem (split(/,/, $str)) {
751 $count++;
752 if (!Net::IP->new($elem)) {
753 my $err = Net::IP::Error();
754 die "invalid IP address: $err\n";
755 }
756 $iprange = 1 if $elem =~ m/-/;
757 }
758
759 die "you can use a range in a list\n" if $iprange && $count > 1;
760 }
761
762 sub parse_port_name_number_or_range {
763 my ($str) = @_;
764
765 my $services = PVE::Firewall::get_etc_services();
766 my $count = 0;
767 my $icmp_port = 0;
768
769 foreach my $item (split(/,/, $str)) {
770 $count++;
771 if ($item =~ m/^(\d+):(\d+)$/) {
772 my ($port1, $port2) = ($1, $2);
773 die "invalid port '$port1'\n" if $port1 > 65535;
774 die "invalid port '$port2'\n" if $port2 > 65535;
775 } elsif ($item =~ m/^(\d+)$/) {
776 my $port = $1;
777 die "invalid port '$port'\n" if $port > 65535;
778 } else {
779 if ($icmp_type_names->{$item}) {
780 $icmp_port = 1;
781 } else {
782 die "invalid port '$item'\n" if !$services->{byname}->{$item};
783 }
784 }
785 }
786
787 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
788
789 return $count;
790 }
791
792 PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
793 sub pve_fw_verify_port_spec {
794 my ($portstr) = @_;
795
796 parse_port_name_number_or_range($portstr);
797
798 return $portstr;
799 }
800
801 PVE::JSONSchema::register_format('pve-fw-v4addr-spec', \&pve_fw_verify_v4addr_spec);
802 sub pve_fw_verify_v4addr_spec {
803 my ($list) = @_;
804
805 parse_address_list($list);
806
807 return $list;
808 }
809
810 PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
811 sub pve_fw_verify_protocol_spec {
812 my ($proto) = @_;
813
814 my $protocols = get_etc_protocols();
815
816 die "unknown protocol '$proto'\n" if $proto &&
817 !(defined($protocols->{byname}->{$proto}) ||
818 defined($protocols->{byid}->{$proto}));
819
820 return $proto;
821 }
822
823
824 # helper function for API
825
826 sub copy_opject_with_digest {
827 my ($object) = @_;
828
829 my $sha = Digest::SHA->new('sha1');
830
831 my $res = {};
832 foreach my $k (sort keys %$object) {
833 my $v = $object->{$k};
834 next if !defined($v);
835 $res->{$k} = $v;
836 $sha->add($k, ':', $v, "\n");
837 }
838
839 my $digest = $sha->hexdigest;
840
841 $res->{digest} = $digest;
842
843 return wantarray ? ($res, $digest) : $res;
844 }
845
846 sub copy_list_with_digest {
847 my ($list) = @_;
848
849 my $sha = Digest::SHA->new('sha1');
850
851 my $res = [];
852 foreach my $entry (@$list) {
853 my $data = {};
854 foreach my $k (sort keys %$entry) {
855 my $v = $entry->{$k};
856 next if !defined($v);
857 $data->{$k} = $v;
858 $sha->add($k, ':', $v, "\n");
859 }
860 push @$res, $data;
861 }
862
863 my $digest = $sha->hexdigest;
864
865 foreach my $entry (@$res) {
866 $entry->{digest} = $digest;
867 }
868
869 return wantarray ? ($res, $digest) : $res;
870 }
871
872 my $rule_properties = {
873 pos => {
874 description => "Update rule at position <pos>.",
875 type => 'integer',
876 minimum => 0,
877 optional => 1,
878 },
879 digest => get_standard_option('pve-config-digest'),
880 type => {
881 type => 'string',
882 optional => 1,
883 enum => ['in', 'out', 'group'],
884 },
885 action => {
886 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
887 type => 'string',
888 optional => 1,
889 pattern => $security_group_name_pattern,
890 maxLength => 20,
891 minLength => 2,
892 },
893 macro => {
894 type => 'string',
895 optional => 1,
896 maxLength => 128,
897 },
898 iface => get_standard_option('pve-iface', { optional => 1 }),
899 source => {
900 type => 'string', format => 'pve-fw-v4addr-spec',
901 optional => 1,
902 },
903 dest => {
904 type => 'string', format => 'pve-fw-v4addr-spec',
905 optional => 1,
906 },
907 proto => {
908 type => 'string', format => 'pve-fw-protocol-spec',
909 optional => 1,
910 },
911 enable => {
912 type => 'boolean',
913 optional => 1,
914 },
915 sport => {
916 type => 'string', format => 'pve-fw-port-spec',
917 optional => 1,
918 },
919 dport => {
920 type => 'string', format => 'pve-fw-port-spec',
921 optional => 1,
922 },
923 comment => {
924 type => 'string',
925 optional => 1,
926 },
927 };
928
929 sub add_rule_properties {
930 my ($properties) = @_;
931
932 foreach my $k (keys %$rule_properties) {
933 my $h = $rule_properties->{$k};
934 # copy data, so that we can modify later without side effects
935 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
936 }
937
938 return $properties;
939 }
940
941 sub delete_rule_properties {
942 my ($rule, $delete_str) = @_;
943
944 foreach my $opt (PVE::Tools::split_list($delete_str)) {
945 raise_param_exc({ 'delete' => "no such property ('$opt')"})
946 if !defined($rule_properties->{$opt});
947 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
948 if $opt eq 'type' || $opt eq 'action';
949 delete $rule->{$opt};
950 }
951
952 return $rule;
953 }
954
955 my $apply_macro = sub {
956 my ($macro_name, $param, $verify) = @_;
957
958 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
959 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
960
961 my $rules = [];
962
963 foreach my $templ (@$macro_rules) {
964 my $rule = {};
965 my $param_used = {};
966 foreach my $k (keys %$templ) {
967 my $v = $templ->{$k};
968 if ($v eq 'PARAM') {
969 $v = $param->{$k};
970 $param_used->{$k} = 1;
971 } elsif ($v eq 'DEST') {
972 $v = $param->{dest};
973 $param_used->{dest} = 1;
974 } elsif ($v eq 'SOURCE') {
975 $v = $param->{source};
976 $param_used->{source} = 1;
977 }
978
979 if (!defined($v)) {
980 my $msg = "missing parameter '$k' in macro '$macro_name'";
981 raise_param_exc({ macro => $msg }) if $verify;
982 die "$msg\n";
983 }
984 $rule->{$k} = $v;
985 }
986 foreach my $k (keys %$param) {
987 next if $k eq 'macro';
988 next if !defined($param->{$k});
989 next if $param_used->{$k};
990 if (defined($rule->{$k})) {
991 if ($rule->{$k} ne $param->{$k}) {
992 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
993 raise_param_exc({ $k => $msg }) if $verify;
994 die "$msg\n";
995 }
996 } else {
997 $rule->{$k} = $param->{$k};
998 }
999 }
1000 push @$rules, $rule;
1001 }
1002
1003 return $rules;
1004 };
1005
1006 sub verify_rule {
1007 my ($rule, $allow_groups) = @_;
1008
1009 my $type = $rule->{type};
1010
1011 raise_param_exc({ type => "missing property"}) if !$type;
1012 raise_param_exc({ action => "missing property"}) if !$rule->{action};
1013
1014 if ($type eq 'in' || $type eq 'out') {
1015 raise_param_exc({ action => "unknown action '$rule->{action}'"})
1016 if $rule->{action} !~ m/^(ACCEPT|DROP|REJECT)$/;
1017 } elsif ($type eq 'group') {
1018 raise_param_exc({ type => "security groups not allowed"})
1019 if !$allow_groups;
1020 raise_param_exc({ action => "invalid characters in security group name"})
1021 if $rule->{action} !~ m/^${security_group_name_pattern}$/;
1022 } else {
1023 raise_param_exc({ type => "unknown rule type '$type'"});
1024 }
1025
1026 if ($rule->{iface}) {
1027 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
1028 raise_param_exc({ iface => $@ }) if $@;
1029 }
1030
1031 if ($rule->{macro}) {
1032 my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})};
1033 raise_param_exc({ macro => "unknown macro '$rule->{macro}'"}) if !$preferred_name;
1034 $rule->{macro} = $preferred_name;
1035 }
1036
1037 if ($rule->{dport}) {
1038 eval { parse_port_name_number_or_range($rule->{dport}); };
1039 raise_param_exc({ dport => $@ }) if $@;
1040 }
1041
1042 if ($rule->{sport}) {
1043 eval { parse_port_name_number_or_range($rule->{sport}); };
1044 raise_param_exc({ sport => $@ }) if $@;
1045 }
1046
1047 if ($rule->{source}) {
1048 eval { parse_address_list($rule->{source}); };
1049 raise_param_exc({ source => $@ }) if $@;
1050 }
1051
1052 if ($rule->{dest}) {
1053 eval { parse_address_list($rule->{dest}); };
1054 raise_param_exc({ dest => $@ }) if $@;
1055 }
1056
1057 if ($rule->{macro}) {
1058 &$apply_macro($rule->{macro}, $rule, 1);
1059 }
1060
1061 return $rule;
1062 }
1063
1064 sub copy_rule_data {
1065 my ($rule, $param) = @_;
1066
1067 foreach my $k (keys %$rule_properties) {
1068 if (defined(my $v = $param->{$k})) {
1069 if ($v eq '' || $v eq '-') {
1070 delete $rule->{$k};
1071 } else {
1072 $rule->{$k} = $v;
1073 }
1074 } else {
1075 delete $rule->{$k};
1076 }
1077 }
1078
1079 # verify rule now
1080
1081 return $rule;
1082 }
1083
1084 # core functions
1085 my $bridge_firewall_enabled = 0;
1086
1087 sub enable_bridge_firewall {
1088
1089 return if $bridge_firewall_enabled; # only once
1090
1091 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1092 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1093
1094 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1095 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1096
1097 $bridge_firewall_enabled = 1;
1098 }
1099
1100 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1101
1102 sub iptables_restore_cmdlist {
1103 my ($cmdlist) = @_;
1104
1105 run_command("/sbin/iptables-restore -n", input => $cmdlist);
1106 }
1107
1108 sub ipset_restore_cmdlist {
1109 my ($cmdlist) = @_;
1110
1111 run_command("/usr/sbin/ipset restore", input => $cmdlist);
1112 }
1113
1114 sub iptables_get_chains {
1115
1116 my $res = {};
1117
1118 # check what chains we want to track
1119 my $is_pvefw_chain = sub {
1120 my $name = shift;
1121
1122 return 1 if $name =~ m/^PVEFW-\S+$/;
1123
1124 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1125
1126 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1127
1128 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1129
1130 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1131 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1132
1133 return undef;
1134 };
1135
1136 my $table = '';
1137
1138 my $hooks = {};
1139
1140 my $parser = sub {
1141 my $line = shift;
1142
1143 return if $line =~ m/^#/;
1144 return if $line =~ m/^\s*$/;
1145
1146 if ($line =~ m/^\*(\S+)$/) {
1147 $table = $1;
1148 return;
1149 }
1150
1151 return if $table ne 'filter';
1152
1153 if ($line =~ m/^:(\S+)\s/) {
1154 my $chain = $1;
1155 return if !&$is_pvefw_chain($chain);
1156 $res->{$chain} = "unknown";
1157 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1158 my ($chain, $sig) = ($1, $2);
1159 return if !&$is_pvefw_chain($chain);
1160 $res->{$chain} = $sig;
1161 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1162 $hooks->{$1} = 1;
1163 } else {
1164 # simply ignore the rest
1165 return;
1166 }
1167 };
1168
1169 run_command("/sbin/iptables-save", outfunc => $parser);
1170
1171 return wantarray ? ($res, $hooks) : $res;
1172 }
1173
1174 sub iptables_chain_digest {
1175 my ($rules) = @_;
1176 my $digest = Digest::SHA->new('sha1');
1177 foreach my $rule (@$rules) { # order is important
1178 $digest->add($rule);
1179 }
1180 return $digest->b64digest;
1181 }
1182
1183 sub ipset_chain_digest {
1184 my ($rules) = @_;
1185
1186 my $digest = Digest::SHA->new('sha1');
1187 foreach my $rule (sort @$rules) { # note: sorted
1188 $digest->add($rule);
1189 }
1190 return $digest->b64digest;
1191 }
1192
1193 sub ipset_get_chains {
1194
1195 my $res = {};
1196 my $chains = {};
1197
1198 my $parser = sub {
1199 my $line = shift;
1200
1201 return if $line =~ m/^#/;
1202 return if $line =~ m/^\s*$/;
1203 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1204 my $chain = $1;
1205 $line =~ s/\s+$//; # delete trailing white space
1206 push @{$chains->{$chain}}, $line;
1207 } else {
1208 # simply ignore the rest
1209 return;
1210 }
1211 };
1212
1213 run_command("/usr/sbin/ipset save", outfunc => $parser);
1214
1215 # compute digest for each chain
1216 foreach my $chain (keys %$chains) {
1217 $res->{$chain} = ipset_chain_digest($chains->{$chain});
1218 }
1219
1220 return $res;
1221 }
1222
1223 sub ruleset_generate_cmdstr {
1224 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1225
1226 return if defined($rule->{enable}) && !$rule->{enable};
1227
1228 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1229
1230 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1231 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
1232
1233 my @cmd = ();
1234
1235 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1236 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1237
1238 my $source = $rule->{source};
1239 my $dest = $rule->{dest};
1240
1241 if ($source) {
1242 if ($source =~ m/^\+/) {
1243 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1244 die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1};
1245 push @cmd, "-m set --match-set PVEFW-$1 src";
1246 } else {
1247 die "invalid security group name '$source'\n";
1248 }
1249 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1250 my $alias = lc($source);
1251 my $e = $cluster_conf->{aliases}->{$alias};
1252 die "no such alias $source\n" if !$e;
1253 push @cmd, "-s $e->{cidr}";
1254 } elsif ($source =~ m/\-/){
1255 push @cmd, "-m iprange --src-range $source";
1256
1257 } else {
1258 push @cmd, "-s $source";
1259 }
1260 }
1261
1262 if ($dest) {
1263 if ($dest =~ m/^\+/) {
1264 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1265 die "no such ipset '$1'\n" if !$cluster_conf->{ipset}->{$1};
1266 push @cmd, "-m set --match-set PVEFW-$1 dst";
1267 } else {
1268 die "invalid security group name '$dest'\n";
1269 }
1270 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1271 my $alias = lc($dest);
1272 my $e = $cluster_conf->{aliases}->{$alias};
1273 die "no such alias $dest" if !$e;
1274 push @cmd, "-d $e->{cidr}";
1275 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1276 push @cmd, "-m iprange --dst-range $dest";
1277
1278 } else {
1279 push @cmd, "-d $dest";
1280 }
1281 }
1282
1283 if ($rule->{proto}) {
1284 push @cmd, "-p $rule->{proto}";
1285
1286 my $multiport = 0;
1287 $multiport++ if $nbdport > 1;
1288 $multiport++ if $nbsport > 1;
1289
1290 push @cmd, "--match multiport" if $multiport;
1291
1292 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1293 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1294
1295 if ($rule->{dport}) {
1296 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1297 # Note: we use dport to store --icmp-type
1298 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
1299 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1300 } else {
1301 if ($nbdport > 1) {
1302 if ($multiport == 2) {
1303 push @cmd, "--ports $rule->{dport}";
1304 } else {
1305 push @cmd, "--dports $rule->{dport}";
1306 }
1307 } else {
1308 push @cmd, "--dport $rule->{dport}";
1309 }
1310 }
1311 }
1312
1313 if ($rule->{sport}) {
1314 if ($nbsport > 1) {
1315 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1316 } else {
1317 push @cmd, "--sport $rule->{sport}";
1318 }
1319 }
1320 } elsif ($rule->{dport} || $rule->{sport}) {
1321 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport};
1322 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport};
1323 }
1324
1325 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
1326
1327 if (my $action = $rule->{action}) {
1328 $action = $actions->{$action} if defined($actions->{$action});
1329 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1330 push @cmd, $goto ? "-g $action" : "-j $action";
1331 }
1332
1333 return scalar(@cmd) ? join(' ', @cmd) : undef;
1334 }
1335
1336 sub ruleset_generate_rule {
1337 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1338
1339 my $rules;
1340
1341 if ($rule->{macro}) {
1342 $rules = &$apply_macro($rule->{macro}, $rule);
1343 } else {
1344 $rules = [ $rule ];
1345 }
1346
1347 # update all or nothing
1348
1349 my @cmds = ();
1350 foreach my $tmp (@$rules) {
1351 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1352 push @cmds, $cmdstr;
1353 }
1354 }
1355
1356 foreach my $cmdstr (@cmds) {
1357 ruleset_addrule($ruleset, $chain, $cmdstr);
1358 }
1359 }
1360
1361 sub ruleset_generate_rule_insert {
1362 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1363
1364 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1365
1366 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $rule, $actions, $goto)) {
1367 ruleset_insertrule($ruleset, $chain, $cmdstr);
1368 }
1369 }
1370
1371 sub ruleset_create_chain {
1372 my ($ruleset, $chain) = @_;
1373
1374 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1375 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1376
1377 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1378
1379 $ruleset->{$chain} = [];
1380 }
1381
1382 sub ruleset_chain_exist {
1383 my ($ruleset, $chain) = @_;
1384
1385 return $ruleset->{$chain} ? 1 : undef;
1386 }
1387
1388 sub ruleset_addrule {
1389 my ($ruleset, $chain, $rule) = @_;
1390
1391 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1392
1393 push @{$ruleset->{$chain}}, "-A $chain $rule";
1394 }
1395
1396 sub ruleset_insertrule {
1397 my ($ruleset, $chain, $rule) = @_;
1398
1399 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1400
1401 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1402 }
1403
1404 sub get_log_rule_base {
1405 my ($chain, $vmid, $msg, $loglevel) = @_;
1406
1407 die "internal error - no log level" if !defined($loglevel);
1408
1409 $vmid = 0 if !defined($vmid);
1410
1411 # Note: we use special format for prefix to pass further
1412 # info to log daemon (VMID, LOGVELEL and CHAIN)
1413
1414 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1415 }
1416
1417 sub ruleset_addlog {
1418 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1419
1420 return if !defined($loglevel);
1421
1422 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1423
1424 $logrule = "$rule $logrule" if defined($rule);
1425
1426 ruleset_addrule($ruleset, $chain, $logrule);
1427 }
1428
1429 sub ruleset_add_chain_policy {
1430 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1431
1432 if ($policy eq 'ACCEPT') {
1433
1434 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1435 { ACCEPT => $accept_action});
1436
1437 } elsif ($policy eq 'DROP') {
1438
1439 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1440
1441 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1442
1443 ruleset_addrule($ruleset, $chain, "-j DROP");
1444 } elsif ($policy eq 'REJECT') {
1445 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1446
1447 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
1448
1449 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1450 } else {
1451 # should not happen
1452 die "internal error: unknown policy '$policy'";
1453 }
1454 }
1455
1456 sub ruleset_chain_add_conn_filters {
1457 my ($ruleset, $chain, $accept) = @_;
1458
1459 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1460 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1461 }
1462
1463 sub ruleset_chain_add_input_filters {
1464 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1465
1466 if ($cluster_conf->{ipset}->{blacklist}){
1467 ruleset_addlog($ruleset, $chain, 0, "DROP: ", $loglevel, "-m set --match-set PVEFW-blacklist src");
1468 ruleset_addrule($ruleset, $chain, "-m set --match-set PVEFW-blacklist src -j DROP");
1469 }
1470
1471 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1472 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1473 }
1474
1475 if ($options->{tcpflags}) {
1476 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1477 }
1478 }
1479
1480 sub ruleset_create_vm_chain {
1481 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1482
1483 ruleset_create_chain($ruleset, $chain);
1484 my $accept = generate_nfqueue($options);
1485
1486 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1487 if ($direction eq 'OUT') {
1488 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1489 proto => 'udp', sport => 68, dport => 67 });
1490 } else {
1491 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1492 proto => 'udp', sport => 67, dport => 68 });
1493 }
1494 }
1495
1496 if ($direction eq 'OUT') {
1497 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1498 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
1499 }
1500 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1501 }
1502 }
1503
1504 sub ruleset_add_group_rule {
1505 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1506
1507 my $group = $rule->{action};
1508 my $group_chain = "GROUP-$group-$direction";
1509 if(!ruleset_chain_exist($ruleset, $group_chain)){
1510 generate_group_rules($ruleset, $cluster_conf, $group);
1511 }
1512
1513 if ($direction eq 'OUT' && $rule->{iface_out}) {
1514 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1515 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1516 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
1517 } else {
1518 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1519 }
1520
1521 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1522 }
1523
1524 sub ruleset_generate_vm_rules {
1525 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1526
1527 my $lc_direction = lc($direction);
1528
1529 my $in_accept = generate_nfqueue($options);
1530
1531 foreach my $rule (@$rules) {
1532 next if $rule->{iface} && $rule->{iface} ne $netid;
1533 next if !$rule->{enable};
1534 if ($rule->{type} eq 'group') {
1535 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1536 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1537 } else {
1538 next if $rule->{type} ne $lc_direction;
1539 eval {
1540 if ($direction eq 'OUT') {
1541 ruleset_generate_rule($ruleset, $chain, $rule,
1542 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
1543 undef, $cluster_conf);
1544 } else {
1545 ruleset_generate_rule($ruleset, $chain, $rule,
1546 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
1547 undef, $cluster_conf);
1548 }
1549 };
1550 warn $@ if $@;
1551 }
1552 }
1553 }
1554
1555 sub generate_nfqueue {
1556 my ($options) = @_;
1557
1558 if ($options->{ips}) {
1559 my $action = "NFQUEUE";
1560 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1561 if (defined($3) && defined($1)) {
1562 $action .= " --queue-balance $1:$3";
1563 } elsif (defined($1)) {
1564 $action .= " --queue-num $1";
1565 }
1566 }
1567 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
1568 return $action;
1569 } else {
1570 return "ACCEPT";
1571 }
1572 }
1573
1574 sub ruleset_generate_vm_ipsrules {
1575 my ($ruleset, $options, $direction, $iface) = @_;
1576
1577 if ($options->{ips} && $direction eq 'IN') {
1578 my $nfqueue = generate_nfqueue($options);
1579
1580 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
1581 ruleset_create_chain($ruleset, "PVEFW-IPS");
1582 }
1583
1584 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
1585 }
1586 }
1587
1588 sub generate_venet_rules_direction {
1589 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1590
1591 my $lc_direction = lc($direction);
1592
1593 my $rules = $vmfw_conf->{rules};
1594
1595 my $options = $vmfw_conf->{options};
1596 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1597
1598 my $chain = "venet0-$vmid-$direction";
1599
1600 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1601
1602 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1603
1604 # implement policy
1605 my $policy;
1606
1607 if ($direction eq 'OUT') {
1608 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1609 } else {
1610 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1611 }
1612
1613 my $accept = generate_nfqueue($options);
1614 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1615 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1616
1617 if ($direction eq 'OUT') {
1618 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT", {
1619 action => $chain,
1620 source => $ip,
1621 iface_in => 'venet0'});
1622 } else {
1623 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN", {
1624 action => $chain,
1625 dest => $ip,
1626 iface_out => 'venet0'});
1627 }
1628 }
1629
1630 sub generate_tap_rules_direction {
1631 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1632
1633 my $lc_direction = lc($direction);
1634
1635 my $rules = $vmfw_conf->{rules};
1636
1637 my $options = $vmfw_conf->{options};
1638 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1639
1640 my $tapchain = "$iface-$direction";
1641
1642 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1643
1644 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1645
1646 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1647
1648 # implement policy
1649 my $policy;
1650
1651 if ($direction eq 'OUT') {
1652 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1653 } else {
1654 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1655 }
1656
1657 my $accept = generate_nfqueue($options);
1658 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1659 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1660
1661 # plug the tap chain to bridge chain
1662 if ($direction eq 'IN') {
1663 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
1664 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1665 } else {
1666 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
1667 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
1668 }
1669 }
1670
1671 sub enable_host_firewall {
1672 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1673
1674 my $options = $hostfw_conf->{options};
1675 my $cluster_options = $cluster_conf->{options};
1676 my $rules = $hostfw_conf->{rules};
1677 my $cluster_rules = $cluster_conf->{rules};
1678
1679 # host inbound firewall
1680 my $chain = "PVEFW-HOST-IN";
1681 ruleset_create_chain($ruleset, $chain);
1682
1683 my $loglevel = get_option_log_level($options, "log_level_in");
1684
1685 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1686
1687 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1688 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1689
1690 # we use RETURN because we need to check also tap rules
1691 my $accept_action = 'RETURN';
1692
1693 # add host rules first, so that cluster wide rules can be overwritten
1694 foreach my $rule (@$rules, @$cluster_rules) {
1695 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1696 if ($rule->{type} eq 'group') {
1697 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1698 } elsif ($rule->{type} eq 'in') {
1699 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1700 undef, $cluster_conf);
1701 }
1702 delete $rule->{iface_in};
1703 }
1704
1705 my $clusternet = cluster_network();
1706
1707 # allow standard traffic on cluster network
1708 if ($clusternet) {
1709 ruleset_addrule($ruleset, $chain, "-s $clusternet -p tcp --dport 8006 -j $accept_action"); # PVE API
1710 ruleset_addrule($ruleset, $chain, "-s $clusternet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1711 ruleset_addrule($ruleset, $chain, "-s $clusternet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1712 ruleset_addrule($ruleset, $chain, "-s $clusternet -p tcp --dport 22 -j $accept_action"); # SSH
1713
1714 # corosync
1715 my $corosync_rule = "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j $accept_action";
1716 ruleset_addrule($ruleset, $chain, "-s $clusternet -d $clusternet $corosync_rule");
1717 ruleset_addrule($ruleset, $chain, "-s $clusternet -m addrtype --dst-type MULTICAST $corosync_rule");
1718 }
1719
1720 # implement input policy
1721 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1722 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1723
1724 # host outbound firewall
1725 $chain = "PVEFW-HOST-OUT";
1726 ruleset_create_chain($ruleset, $chain);
1727
1728 $loglevel = get_option_log_level($options, "log_level_out");
1729
1730 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1731
1732 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1733
1734 # we use RETURN because we may want to check other thigs later
1735 $accept_action = 'RETURN';
1736
1737 # add host rules first, so that cluster wide rules can be overwritten
1738 foreach my $rule (@$rules, @$cluster_rules) {
1739 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1740 if ($rule->{type} eq 'group') {
1741 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1742 } elsif ($rule->{type} eq 'out') {
1743 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
1744 undef, $cluster_conf);
1745 }
1746 delete $rule->{iface_out};
1747 }
1748
1749 # allow standard traffic on cluster network
1750 if ($clusternet) {
1751 ruleset_addrule($ruleset, $chain, "-d $clusternet -p tcp --dport 8006 -j $accept_action"); # PVE API
1752 ruleset_addrule($ruleset, $chain, "-d $clusternet -p tcp --dport 22 -j $accept_action"); # SSH
1753 ruleset_addrule($ruleset, $chain, "-d $clusternet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
1754 ruleset_addrule($ruleset, $chain, "-d $clusternet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
1755
1756 my $corosync_rule = "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j $accept_action";
1757 ruleset_addrule($ruleset, $chain, "-d $clusternet $corosync_rule");
1758 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
1759 }
1760
1761 # implement output policy
1762 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1763 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1764
1765 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1766 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
1767 }
1768
1769 sub generate_group_rules {
1770 my ($ruleset, $cluster_conf, $group) = @_;
1771
1772 my $rules = $cluster_conf->{groups}->{$group};
1773
1774 if (!$rules) {
1775 warn "no such security group '$group'\n";
1776 $rules = []; # create empty chain
1777 }
1778
1779 my $chain = "GROUP-${group}-IN";
1780
1781 ruleset_create_chain($ruleset, $chain);
1782 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1783
1784 foreach my $rule (@$rules) {
1785 next if $rule->{type} ne 'in';
1786 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1787 }
1788
1789 $chain = "GROUP-${group}-OUT";
1790
1791 ruleset_create_chain($ruleset, $chain);
1792 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1793
1794 foreach my $rule (@$rules) {
1795 next if $rule->{type} ne 'out';
1796 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1797 # check also other tap rules later
1798 ruleset_generate_rule($ruleset, $chain, $rule,
1799 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1800 }
1801 }
1802
1803 my $MAX_NETS = 32;
1804 my $valid_netdev_names = {};
1805 for (my $i = 0; $i < $MAX_NETS; $i++) {
1806 $valid_netdev_names->{"net$i"} = 1;
1807 }
1808
1809 sub parse_fw_rule {
1810 my ($line, $allow_iface, $allow_groups) = @_;
1811
1812 my ($type, $action, $macro, $iface, $source, $dest, $proto, $dport, $sport);
1813
1814 chomp $line;
1815
1816 # we can add single line comments to the end of the rule
1817 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1818
1819 # we can disable a rule when prefixed with '|'
1820 my $enable = 1;
1821
1822 $enable = 0 if $line =~ s/^\|//;
1823
1824 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1825 die "unable to parse rule: $line\n";
1826
1827 $type = lc($1);
1828 $action = $2;
1829
1830 if ($type eq 'in' || $type eq 'out') {
1831 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1832 # OK
1833 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1834 $action = $2;
1835 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1836 die "unknown macro '$1'\n" if !$preferred_name;
1837 $macro = $preferred_name;
1838 } else {
1839 die "unknown action '$action'\n";
1840 }
1841 } elsif ($type eq 'group') {
1842 die "groups disabled\n" if !$allow_groups;
1843 die "invalid characters in group name\n" if $action !~ m/^${security_group_name_pattern}$/;
1844 } else {
1845 die "unknown rule type '$type'\n";
1846 }
1847
1848 while (length($line)) {
1849 if ($line =~ s/^-i (\S+)\s*//) {
1850 die "parameter -i not allowed\n" if !$allow_iface;
1851 $iface = $1;
1852 PVE::JSONSchema::pve_verify_iface($iface);
1853 next;
1854 }
1855
1856 last if $type eq 'group';
1857
1858 if ($line =~ s/^-p (\S+)\s*//) {
1859 $proto = $1;
1860 pve_fw_verify_protocol_spec($proto);
1861 next;
1862 }
1863 if ($line =~ s/^-dport (\S+)\s*//) {
1864 $dport = $1;
1865 parse_port_name_number_or_range($dport);
1866 next;
1867 }
1868 if ($line =~ s/^-sport (\S+)\s*//) {
1869 $sport = $1;
1870 parse_port_name_number_or_range($sport);
1871 next;
1872 }
1873 if ($line =~ s/^-source (\S+)\s*//) {
1874 $source = $1;
1875 parse_address_list($source);
1876 next;
1877 }
1878 if ($line =~ s/^-dest (\S+)\s*//) {
1879 $dest = $1;
1880 parse_address_list($dest);
1881 next;
1882 }
1883
1884 last;
1885 }
1886
1887 die "unable to parse rule parameters: $line\n" if length($line);
1888
1889 return {
1890 type => $type,
1891 enable => $enable,
1892 comment => $comment,
1893 action => $action,
1894 macro => $macro,
1895 iface => $iface,
1896 source => $source,
1897 dest => $dest,
1898 proto => $proto,
1899 dport => $dport,
1900 sport => $sport,
1901 };
1902 }
1903
1904 sub parse_vmfw_option {
1905 my ($line) = @_;
1906
1907 my ($opt, $value);
1908
1909 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1910
1911 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
1912 $opt = lc($1);
1913 $value = int($2);
1914 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1915 $opt = lc($1);
1916 $value = $2 ? lc($3) : '';
1917 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1918 $opt = lc($1);
1919 $value = uc($3);
1920 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1921 $opt = lc($1);
1922 $value = $2;
1923 } else {
1924 chomp $line;
1925 die "can't parse option '$line'\n"
1926 }
1927
1928 return ($opt, $value);
1929 }
1930
1931 sub parse_hostfw_option {
1932 my ($line) = @_;
1933
1934 my ($opt, $value);
1935
1936 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1937
1938 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
1939 $opt = lc($1);
1940 $value = int($2);
1941 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1942 $opt = lc($1);
1943 $value = $2 ? lc($3) : '';
1944 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
1945 $opt = lc($1);
1946 $value = int($2);
1947 } else {
1948 chomp $line;
1949 die "can't parse option '$line'\n"
1950 }
1951
1952 return ($opt, $value);
1953 }
1954
1955 sub parse_clusterfw_option {
1956 my ($line) = @_;
1957
1958 my ($opt, $value);
1959
1960 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1961 $opt = lc($1);
1962 $value = int($2);
1963 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1964 $opt = lc($1);
1965 $value = uc($3);
1966 } else {
1967 chomp $line;
1968 die "can't parse option '$line'\n"
1969 }
1970
1971 return ($opt, $value);
1972 }
1973
1974 sub parse_clusterfw_alias {
1975 my ($line) = @_;
1976
1977 # we can add single line comments to the end of the line
1978 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
1979
1980 if ($line =~ m/^(\S+)\s(\S+)$/) {
1981 my ($name, $cidr) = ($1, $2);
1982 $cidr =~ s|/32$||;
1983 pve_verify_ipv4_or_cidr($cidr);
1984 my $data = {
1985 name => $name,
1986 cidr => $cidr,
1987 };
1988 $data->{comment} = $comment if $comment;
1989 return $data;
1990 }
1991
1992 return undef;
1993 }
1994
1995 sub parse_vm_fw_rules {
1996 my ($filename, $fh) = @_;
1997
1998 my $res = { rules => [], options => {}};
1999
2000 my $section;
2001
2002 while (defined(my $line = <$fh>)) {
2003 next if $line =~ m/^#/;
2004 next if $line =~ m/^\s*$/;
2005
2006 my $linenr = $fh->input_line_number();
2007 my $prefix = "$filename (line $linenr)";
2008
2009 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2010 $section = lc($1);
2011 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2012 next;
2013 }
2014 if (!$section) {
2015 warn "$prefix: skip line - no section";
2016 next;
2017 }
2018
2019 next if !$res->{$section}; # skip undefined section
2020
2021 if ($section eq 'options') {
2022 eval {
2023 my ($opt, $value) = parse_vmfw_option($line);
2024 $res->{options}->{$opt} = $value;
2025 };
2026 warn "$prefix: $@" if $@;
2027 next;
2028 }
2029
2030 my $rule;
2031 eval { $rule = parse_fw_rule($line, 1, 1); };
2032 if (my $err = $@) {
2033 warn "$prefix: $err";
2034 next;
2035 }
2036
2037 push @{$res->{$section}}, $rule;
2038 }
2039
2040 return $res;
2041 }
2042
2043 sub parse_host_fw_rules {
2044 my ($filename, $fh) = @_;
2045
2046 my $res = { rules => [], options => {}};
2047
2048 my $section;
2049
2050 while (defined(my $line = <$fh>)) {
2051 next if $line =~ m/^#/;
2052 next if $line =~ m/^\s*$/;
2053
2054 my $linenr = $fh->input_line_number();
2055 my $prefix = "$filename (line $linenr)";
2056
2057 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2058 $section = lc($1);
2059 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2060 next;
2061 }
2062 if (!$section) {
2063 warn "$prefix: skip line - no section";
2064 next;
2065 }
2066
2067 next if !$res->{$section}; # skip undefined section
2068
2069 if ($section eq 'options') {
2070 eval {
2071 my ($opt, $value) = parse_hostfw_option($line);
2072 $res->{options}->{$opt} = $value;
2073 };
2074 warn "$prefix: $@" if $@;
2075 next;
2076 }
2077
2078 my $rule;
2079 eval { $rule = parse_fw_rule($line, 1, 1); };
2080 if (my $err = $@) {
2081 warn "$prefix: $err";
2082 next;
2083 }
2084
2085 push @{$res->{$section}}, $rule;
2086 }
2087
2088 return $res;
2089 }
2090
2091 sub parse_cluster_fw_rules {
2092 my ($filename, $fh) = @_;
2093
2094 my $section;
2095 my $group;
2096
2097 my $res = {
2098 rules => [],
2099 options => {},
2100 aliases => {},
2101 groups => {},
2102 group_comments => {},
2103 ipset => {} ,
2104 ipset_comments => {},
2105 };
2106
2107 while (defined(my $line = <$fh>)) {
2108 next if $line =~ m/^#/;
2109 next if $line =~ m/^\s*$/;
2110
2111 my $linenr = $fh->input_line_number();
2112 my $prefix = "$filename (line $linenr)";
2113
2114 if ($line =~ m/^\[options\]$/i) {
2115 $section = 'options';
2116 next;
2117 }
2118
2119 if ($line =~ m/^\[aliases\]$/i) {
2120 $section = 'aliases';
2121 next;
2122 }
2123
2124 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2125 $section = 'groups';
2126 $group = lc($1);
2127 my $comment = $2;
2128 $res->{$section}->{$group} = [];
2129 $res->{group_comments}->{$group} = decode('utf8', $comment)
2130 if $comment;
2131 next;
2132 }
2133
2134 if ($line =~ m/^\[rules\]$/i) {
2135 $section = 'rules';
2136 next;
2137 }
2138
2139 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2140 $section = 'ipset';
2141 $group = lc($1);
2142 my $comment = $2;
2143 $res->{$section}->{$group} = [];
2144 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2145 if $comment;
2146 next;
2147 }
2148
2149 if (!$section) {
2150 warn "$prefix: skip line - no section\n";
2151 next;
2152 }
2153
2154 if ($section eq 'options') {
2155 eval {
2156 my ($opt, $value) = parse_clusterfw_option($line);
2157 $res->{options}->{$opt} = $value;
2158 };
2159 warn "$prefix: $@" if $@;
2160 } elsif ($section eq 'aliases') {
2161 eval {
2162 my $data = parse_clusterfw_alias($line);
2163 $res->{aliases}->{lc($data->{name})} = $data;
2164 };
2165 warn "$prefix: $@" if $@;
2166 } elsif ($section eq 'rules') {
2167 my $rule;
2168 eval { $rule = parse_fw_rule($line, 1, 1); };
2169 if (my $err = $@) {
2170 warn "$prefix: $err";
2171 next;
2172 }
2173 push @{$res->{$section}}, $rule;
2174 } elsif ($section eq 'groups') {
2175 my $rule;
2176 eval { $rule = parse_fw_rule($line, 0, 0); };
2177 if (my $err = $@) {
2178 warn "$prefix: $err";
2179 next;
2180 }
2181 push @{$res->{$section}->{$group}}, $rule;
2182 } elsif ($section eq 'ipset') {
2183 # we can add single line comments to the end of the rule
2184 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2185
2186 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2187 my $nomatch = $1;
2188 my $cidr = $2;
2189
2190 if($cidr !~ m/^${ip_alias_pattern}$/) {
2191 $cidr =~ s|/32$||;
2192
2193 eval { pve_verify_ipv4_or_cidr($cidr); };
2194 if (my $err = $@) {
2195 warn "$prefix: $cidr - $err";
2196 next;
2197 }
2198 }
2199
2200 my $entry = { cidr => $cidr };
2201 $entry->{nomatch} = 1 if $nomatch;
2202 $entry->{comment} = $comment if $comment;
2203
2204 push @{$res->{$section}->{$group}}, $entry;
2205 }
2206 }
2207
2208 return $res;
2209 }
2210
2211 sub run_locked {
2212 my ($code, @param) = @_;
2213
2214 my $timeout = 10;
2215
2216 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2217
2218 die $@ if $@;
2219
2220 return $res;
2221 }
2222
2223 sub read_local_vm_config {
2224
2225 my $openvz = {};
2226 my $qemu = {};
2227
2228 my $vmdata = { openvz => $openvz, qemu => $qemu };
2229
2230 my $vmlist = PVE::Cluster::get_vmlist();
2231 return $vmdata if !$vmlist || !$vmlist->{ids};
2232 my $ids = $vmlist->{ids};
2233
2234 foreach my $vmid (keys %$ids) {
2235 next if !$vmid; # skip VE0
2236 my $d = $ids->{$vmid};
2237 next if !$d->{node} || $d->{node} ne $nodename;
2238 next if !$d->{type};
2239 if ($d->{type} eq 'openvz') {
2240 if ($have_pve_manager) {
2241 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2242 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2243 $openvz->{$vmid} = $conf;
2244 }
2245 }
2246 } elsif ($d->{type} eq 'qemu') {
2247 if ($have_qemu_server) {
2248 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2249 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2250 $qemu->{$vmid} = $conf;
2251 }
2252 }
2253 }
2254 }
2255
2256 return $vmdata;
2257 };
2258
2259 sub load_vmfw_conf {
2260 my ($vmid, $dir) = @_;
2261
2262 my $vmfw_conf = {};
2263
2264 $dir = "/etc/pve/firewall" if !defined($dir);
2265
2266 my $filename = "$dir/$vmid.fw";
2267 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2268 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2269 }
2270
2271 return $vmfw_conf;
2272 }
2273
2274 my $format_rules = sub {
2275 my ($rules, $allow_iface) = @_;
2276
2277 my $raw = '';
2278
2279 foreach my $rule (@$rules) {
2280 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2281 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2282 $raw .= uc($rule->{type});
2283 if ($rule->{macro}) {
2284 $raw .= " $rule->{macro}($rule->{action})";
2285 } else {
2286 $raw .= " " . $rule->{action};
2287 }
2288 if ($allow_iface && $rule->{iface}) {
2289 $raw .= " -i $rule->{iface}";
2290 }
2291
2292 if ($rule->{type} ne 'group') {
2293 $raw .= " -source $rule->{source}" if $rule->{source};
2294 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2295 $raw .= " -p $rule->{proto}" if $rule->{proto};
2296 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2297 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2298 }
2299
2300 $raw .= " # " . encode('utf8', $rule->{comment})
2301 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2302 $raw .= "\n";
2303 } else {
2304 die "unknown rule type '$rule->{type}'";
2305 }
2306 }
2307
2308 return $raw;
2309 };
2310
2311 my $format_options = sub {
2312 my ($options) = @_;
2313
2314 my $raw = '';
2315
2316 $raw .= "[OPTIONS]\n\n";
2317 foreach my $opt (keys %$options) {
2318 $raw .= "$opt: $options->{$opt}\n";
2319 }
2320 $raw .= "\n";
2321
2322 return $raw;
2323 };
2324
2325 my $format_aliases = sub {
2326 my ($aliases) = @_;
2327
2328 my $raw = '';
2329
2330 $raw .= "[ALIASES]\n\n";
2331 foreach my $k (keys %$aliases) {
2332 my $e = $aliases->{$k};
2333 $raw .= "$e->{name} $e->{cidr}";
2334 $raw .= " # " . encode('utf8', $e->{comment})
2335 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2336 $raw .= "\n";
2337 }
2338 $raw .= "\n";
2339
2340 return $raw;
2341 };
2342
2343 my $format_ipset = sub {
2344 my ($options) = @_;
2345
2346 my $raw = '';
2347
2348 my $nethash = {};
2349 foreach my $entry (@$options) {
2350 $nethash->{$entry->{cidr}} = $entry;
2351 }
2352
2353 foreach my $cidr (sort keys %$nethash) {
2354 my $entry = $nethash->{$cidr};
2355 my $line = $entry->{nomatch} ? '!' : '';
2356 $line .= $entry->{cidr};
2357 $line .= " # " . encode('utf8', $entry->{comment})
2358 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2359 $raw .= "$line\n";
2360 }
2361
2362 return $raw;
2363 };
2364
2365 sub save_vmfw_conf {
2366 my ($vmid, $vmfw_conf) = @_;
2367
2368 my $raw = '';
2369
2370 my $options = $vmfw_conf->{options};
2371 $raw .= &$format_options($options) if scalar(keys %$options);
2372
2373 my $rules = $vmfw_conf->{rules} || [];
2374 if (scalar(@$rules)) {
2375 $raw .= "[RULES]\n\n";
2376 $raw .= &$format_rules($rules, 1);
2377 $raw .= "\n";
2378 }
2379
2380 my $filename = "/etc/pve/firewall/$vmid.fw";
2381 PVE::Tools::file_set_contents($filename, $raw);
2382 }
2383
2384 sub read_vm_firewall_configs {
2385 my ($vmdata, $dir) = @_;
2386
2387 my $vmfw_configs = {};
2388
2389 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2390 my $vmfw_conf = load_vmfw_conf($vmid, $dir);
2391 next if !$vmfw_conf->{options}; # skip if file does not exists
2392 $vmfw_configs->{$vmid} = $vmfw_conf;
2393 }
2394
2395 return $vmfw_configs;
2396 }
2397
2398 sub get_option_log_level {
2399 my ($options, $k) = @_;
2400
2401 my $v = $options->{$k};
2402 $v = $default_log_level if !defined($v);
2403
2404 return undef if $v eq '' || $v eq 'nolog';
2405
2406 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2407
2408 return $v if ($v >= 0) && ($v <= 7);
2409
2410 warn "unknown log level ($k = '$v')\n";
2411
2412 return undef;
2413 }
2414
2415 sub generate_std_chains {
2416 my ($ruleset, $options) = @_;
2417
2418 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2419
2420 # same as shorewall smurflog.
2421 my $chain = 'PVEFW-smurflog';
2422 $pve_std_chains->{$chain} = [];
2423
2424 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2425 push @{$pve_std_chains->{$chain}}, "-j DROP";
2426
2427 # same as shorewall logflags action.
2428 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2429 $chain = 'PVEFW-logflags';
2430 $pve_std_chains->{$chain} = [];
2431
2432 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2433 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2434 push @{$pve_std_chains->{$chain}}, "-j DROP";
2435
2436 foreach my $chain (keys %$pve_std_chains) {
2437 ruleset_create_chain($ruleset, $chain);
2438 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2439 if (ref($rule)) {
2440 ruleset_generate_rule($ruleset, $chain, $rule);
2441 } else {
2442 ruleset_addrule($ruleset, $chain, $rule);
2443 }
2444 }
2445 }
2446 }
2447
2448 sub generate_ipset_chains {
2449 my ($ipset_ruleset, $fw_conf) = @_;
2450
2451 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2452 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
2453 }
2454 }
2455
2456 sub generate_ipset {
2457 my ($ipset_ruleset, $name, $options, $aliases) = @_;
2458
2459 my $hashsize = scalar(@$options);
2460 if ($hashsize <= 64) {
2461 $hashsize = 64;
2462 } else {
2463 $hashsize = round_powerof2($hashsize);
2464 }
2465
2466 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2467
2468 # remove duplicates
2469 my $nethash = {};
2470 foreach my $entry (@$options) {
2471 my $cidr = $entry->{cidr};
2472 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2473 my $alias = lc($cidr);
2474 if ($aliases->{$alias}) {
2475 $entry->{cidr} = $aliases->{$alias}->{cidr};
2476 $nethash->{$entry->{cidr}} = $entry;
2477 } else {
2478 warn "no such alias '$cidr'\n" if !$aliases->{$alias};
2479 }
2480 } else {
2481 $nethash->{$entry->{cidr}} = $entry;
2482 }
2483 }
2484
2485 foreach my $cidr (sort keys %$nethash) {
2486 my $entry = $nethash->{$cidr};
2487
2488 my $cmd = "add $name $cidr";
2489 if ($entry->{nomatch}) {
2490 if ($feature_ipset_nomatch) {
2491 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2492 } else {
2493 warn "ignore !$cidr - nomatch not supported by kernel\n";
2494 }
2495 } else {
2496 push @{$ipset_ruleset->{$name}}, $cmd;
2497 }
2498 }
2499 }
2500
2501 sub round_powerof2 {
2502 my ($int) = @_;
2503
2504 $int--;
2505 $int |= $int >> $_ foreach (1,2,4,8,16);
2506 return ++$int;
2507 }
2508
2509 sub load_clusterfw_conf {
2510 my ($filename) = @_;
2511
2512 $filename = $clusterfw_conf_filename if !defined($filename);
2513
2514 my $cluster_conf = {};
2515 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2516 $cluster_conf = parse_cluster_fw_rules($filename, $fh);
2517 }
2518
2519 return $cluster_conf;
2520 }
2521
2522 sub save_clusterfw_conf {
2523 my ($cluster_conf) = @_;
2524
2525 my $raw = '';
2526
2527 my $options = $cluster_conf->{options};
2528 $raw .= &$format_options($options) if scalar(keys %$options);
2529
2530 my $aliases = $cluster_conf->{aliases};
2531 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2532
2533 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2534 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2535 my $utf8comment = encode('utf8', $comment);
2536 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2537 } else {
2538 $raw .= "[IPSET $ipset]\n\n";
2539 }
2540 my $options = $cluster_conf->{ipset}->{$ipset};
2541 $raw .= &$format_ipset($options);
2542 $raw .= "\n";
2543 }
2544
2545 my $rules = $cluster_conf->{rules};
2546 if (scalar(@$rules)) {
2547 $raw .= "[RULES]\n\n";
2548 $raw .= &$format_rules($rules, 1);
2549 $raw .= "\n";
2550 }
2551
2552 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2553 my $rules = $cluster_conf->{groups}->{$group};
2554 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2555 my $utf8comment = encode('utf8', $comment);
2556 $raw .= "[group $group] # $utf8comment\n\n";
2557 } else {
2558 $raw .= "[group $group]\n\n";
2559 }
2560
2561 $raw .= &$format_rules($rules, 0);
2562 $raw .= "\n";
2563 }
2564
2565 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2566 }
2567
2568 sub load_hostfw_conf {
2569 my ($filename) = @_;
2570
2571 $filename = $hostfw_conf_filename if !defined($filename);
2572
2573 my $hostfw_conf = {};
2574 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2575 $hostfw_conf = parse_host_fw_rules($filename, $fh);
2576 }
2577 return $hostfw_conf;
2578 }
2579
2580 sub save_hostfw_conf {
2581 my ($hostfw_conf) = @_;
2582
2583 my $raw = '';
2584
2585 my $options = $hostfw_conf->{options};
2586 $raw .= &$format_options($options) if scalar(keys %$options);
2587
2588 my $rules = $hostfw_conf->{rules};
2589 if (scalar(@$rules)) {
2590 $raw .= "[RULES]\n\n";
2591 $raw .= &$format_rules($rules, 1);
2592 $raw .= "\n";
2593 }
2594
2595 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2596 }
2597
2598 sub compile {
2599 my ($cluster_conf, $hostfw_conf, $vmdata) = @_;
2600
2601 my $vmfw_configs;
2602
2603 if ($vmdata) { # test mode
2604 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2605 my $filename = "$testdir/cluster.fw";
2606 $cluster_conf = load_clusterfw_conf($filename);
2607
2608 $filename = "$testdir/host.fw";
2609 $hostfw_conf = load_hostfw_conf($filename);
2610
2611 $vmfw_configs = read_vm_firewall_configs($vmdata, $testdir);
2612 } else { # normal operation
2613 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2614
2615 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2616
2617 $vmdata = read_local_vm_config();
2618 $vmfw_configs = read_vm_firewall_configs($vmdata);
2619 }
2620
2621
2622 $cluster_conf->{ipset}->{venet0} = [];
2623
2624 my $ruleset = {};
2625
2626 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2627 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2628
2629 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2630
2631 my $hostfw_options = $hostfw_conf->{options} || {};
2632
2633 # fixme: what log level should we use here?
2634 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2635
2636 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2637
2638 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2639 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2640 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2641
2642 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2643 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2644
2645 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2646
2647 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2648 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2649
2650 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2651 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2652
2653 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2654
2655 generate_std_chains($ruleset, $hostfw_options);
2656
2657 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2658
2659 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2660
2661 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2662
2663 # generate firewall rules for QEMU VMs
2664 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2665 my $conf = $vmdata->{qemu}->{$vmid};
2666 my $vmfw_conf = $vmfw_configs->{$vmid};
2667 next if !$vmfw_conf;
2668 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2669
2670 foreach my $netid (keys %$conf) {
2671 next if $netid !~ m/^net(\d+)$/;
2672 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2673 next if !$net->{firewall};
2674 my $iface = "tap${vmid}i$1";
2675
2676 my $macaddr = $net->{macaddr};
2677 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2678 $vmfw_conf, $vmid, 'IN');
2679 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2680 $vmfw_conf, $vmid, 'OUT');
2681 }
2682 }
2683
2684 # generate firewall rules for OpenVZ containers
2685 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2686 my $conf = $vmdata->{openvz}->{$vmid};
2687
2688 my $vmfw_conf = $vmfw_configs->{$vmid};
2689 next if !$vmfw_conf;
2690 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2691
2692 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2693 my $ip = $conf->{ip_address}->{value};
2694 $ip =~ s/\s+/,/g;
2695 parse_address_list($ip); # make sure we have a valid $ip list
2696
2697 my @ips = split(',', $ip);
2698
2699 foreach my $singleip (@ips) {
2700 my $venet0ipset = {};
2701 $venet0ipset->{cidr} = $singleip;
2702 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2703 }
2704
2705 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN');
2706 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2707 }
2708
2709 if ($conf->{netif} && $conf->{netif}->{value}) {
2710 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2711 foreach my $netid (keys %$netif) {
2712 my $d = $netif->{$netid};
2713
2714 my $macaddr = $d->{mac};
2715 my $iface = $d->{host_ifname};
2716 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2717 $vmfw_conf, $vmid, 'IN');
2718 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2719 $vmfw_conf, $vmid, 'OUT');
2720 }
2721 }
2722 }
2723
2724 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2725 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2726 }
2727
2728 my $ipset_ruleset = {};
2729 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2730
2731 return ($ruleset, $ipset_ruleset);
2732 }
2733
2734 sub get_ruleset_status {
2735 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2736
2737 my $statushash = {};
2738
2739 foreach my $chain (sort keys %$ruleset) {
2740 my $sig = &$digest_fn($ruleset->{$chain});
2741
2742 $statushash->{$chain}->{sig} = $sig;
2743
2744 my $oldsig = $active_chains->{$chain};
2745 if (!defined($oldsig)) {
2746 $statushash->{$chain}->{action} = 'create';
2747 } else {
2748 if ($oldsig eq $sig) {
2749 $statushash->{$chain}->{action} = 'exists';
2750 } else {
2751 $statushash->{$chain}->{action} = 'update';
2752 }
2753 }
2754 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2755 foreach my $cmd (@{$ruleset->{$chain}}) {
2756 print "\t$cmd\n" if $verbose;
2757 }
2758 }
2759
2760 foreach my $chain (sort keys %$active_chains) {
2761 if (!defined($ruleset->{$chain})) {
2762 my $sig = $active_chains->{$chain};
2763 $statushash->{$chain}->{action} = 'delete';
2764 $statushash->{$chain}->{sig} = $sig;
2765 print "delete $chain ($sig)\n" if $verbose;
2766 }
2767 }
2768
2769 return $statushash;
2770 }
2771
2772 sub print_sig_rule {
2773 my ($chain, $sig) = @_;
2774
2775 # We just use this to store a SHA1 checksum used to detect changes
2776 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2777 }
2778
2779 sub get_ruleset_cmdlist {
2780 my ($ruleset, $verbose) = @_;
2781
2782 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2783
2784 my ($active_chains, $hooks) = iptables_get_chains();
2785 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2786
2787 # create missing chains first
2788 foreach my $chain (sort keys %$ruleset) {
2789 my $stat = $statushash->{$chain};
2790 die "internal error" if !$stat;
2791 next if $stat->{action} ne 'create';
2792
2793 $cmdlist .= ":$chain - [0:0]\n";
2794 }
2795
2796 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2797 if (!$hooks->{$h}) {
2798 $cmdlist .= "-A $h -j PVEFW-$h\n";
2799 }
2800 }
2801
2802 foreach my $chain (sort keys %$ruleset) {
2803 my $stat = $statushash->{$chain};
2804 die "internal error" if !$stat;
2805
2806 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2807 $cmdlist .= "-F $chain\n";
2808 foreach my $cmd (@{$ruleset->{$chain}}) {
2809 $cmdlist .= "$cmd\n";
2810 }
2811 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2812 } elsif ($stat->{action} eq 'delete') {
2813 die "internal error"; # this should not happen
2814 } elsif ($stat->{action} eq 'exists') {
2815 # do nothing
2816 } else {
2817 die "internal error - unknown status '$stat->{action}'";
2818 }
2819 }
2820
2821 foreach my $chain (keys %$statushash) {
2822 next if $statushash->{$chain}->{action} ne 'delete';
2823 $cmdlist .= "-F $chain\n";
2824 }
2825 foreach my $chain (keys %$statushash) {
2826 next if $statushash->{$chain}->{action} ne 'delete';
2827 next if $chain eq 'PVEFW-INPUT';
2828 next if $chain eq 'PVEFW-OUTPUT';
2829 next if $chain eq 'PVEFW-FORWARD';
2830 $cmdlist .= "-X $chain\n";
2831 }
2832
2833 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
2834
2835 $cmdlist .= "COMMIT\n";
2836
2837 return wantarray ? ($cmdlist, $changes) : $cmdlist;
2838 }
2839
2840 sub get_ipset_cmdlist {
2841 my ($ruleset, $verbose) = @_;
2842
2843 my $cmdlist = "";
2844
2845 my $delete_cmdlist = "";
2846
2847 my $active_chains = ipset_get_chains();
2848 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
2849
2850 # remove stale _swap chains
2851 foreach my $chain (keys %$active_chains) {
2852 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2853 $cmdlist .= "destroy $chain\n";
2854 }
2855 }
2856
2857 foreach my $chain (sort keys %$ruleset) {
2858 my $stat = $statushash->{$chain};
2859 die "internal error" if !$stat;
2860
2861 if ($stat->{action} eq 'create') {
2862 foreach my $cmd (@{$ruleset->{$chain}}) {
2863 $cmdlist .= "$cmd\n";
2864 }
2865 }
2866
2867 if ($stat->{action} eq 'update') {
2868 my $chain_swap = $chain."_swap";
2869
2870 foreach my $cmd (@{$ruleset->{$chain}}) {
2871 $cmd =~ s/$chain/$chain_swap/;
2872 $cmdlist .= "$cmd\n";
2873 }
2874 $cmdlist .= "swap $chain_swap $chain\n";
2875 $cmdlist .= "flush $chain_swap\n";
2876 $cmdlist .= "destroy $chain_swap\n";
2877 }
2878
2879 }
2880
2881 foreach my $chain (keys %$statushash) {
2882 next if $statushash->{$chain}->{action} ne 'delete';
2883
2884 $delete_cmdlist .= "flush $chain\n";
2885 $delete_cmdlist .= "destroy $chain\n";
2886 }
2887
2888 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
2889
2890 return ($cmdlist, $delete_cmdlist, $changes);
2891 }
2892
2893 sub apply_ruleset {
2894 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2895
2896 enable_bridge_firewall();
2897
2898 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2899 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
2900
2901 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2902
2903 if ($verbose) {
2904 if ($ipset_changes) {
2905 print "ipset changes:\n";
2906 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2907 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2908 }
2909
2910 if ($changes) {
2911 print "iptables changes:\n";
2912 print $cmdlist;
2913 }
2914 }
2915
2916 ipset_restore_cmdlist($ipset_create_cmdlist);
2917
2918 iptables_restore_cmdlist($cmdlist);
2919
2920 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2921
2922 # test: re-read status and check if everything is up to date
2923 my $active_chains = iptables_get_chains();
2924 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
2925
2926 my $errors;
2927 foreach my $chain (sort keys %$ruleset) {
2928 my $stat = $statushash->{$chain};
2929 if ($stat->{action} ne 'exists') {
2930 warn "unable to update chain '$chain'\n";
2931 $errors = 1;
2932 }
2933 }
2934
2935 die "unable to apply firewall changes\n" if $errors;
2936
2937 update_nf_conntrack_max($hostfw_conf);
2938
2939 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
2940
2941 }
2942
2943 sub update_nf_conntrack_max {
2944 my ($hostfw_conf) = @_;
2945
2946 my $max = 65536; # reasonable default
2947
2948 my $options = $hostfw_conf->{options} || {};
2949
2950 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2951 $max = $options->{nf_conntrack_max};
2952 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2953 }
2954
2955 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2956 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2957
2958 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2959
2960 if ($current != $max) {
2961 my $hashsize = int($max/4);
2962 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2963 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2964 }
2965 }
2966
2967 sub update_nf_conntrack_tcp_timeout_established {
2968 my ($hostfw_conf) = @_;
2969
2970 my $options = $hostfw_conf->{options} || {};
2971
2972 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
2973
2974 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2975 }
2976
2977 sub remove_pvefw_chains {
2978
2979 my ($chash, $hooks) = iptables_get_chains();
2980 my $cmdlist = "*filter\n";
2981
2982 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2983 if ($hooks->{$h}) {
2984 $cmdlist .= "-D $h -j PVEFW-$h\n";
2985 }
2986 }
2987
2988 foreach my $chain (keys %$chash) {
2989 $cmdlist .= "-F $chain\n";
2990 }
2991
2992 foreach my $chain (keys %$chash) {
2993 $cmdlist .= "-X $chain\n";
2994 }
2995 $cmdlist .= "COMMIT\n";
2996
2997 iptables_restore_cmdlist($cmdlist);
2998 }
2999
3000 sub init {
3001 my $cluster_conf = load_clusterfw_conf();
3002 my $cluster_options = $cluster_conf->{options};
3003 my $enable = $cluster_options->{enable};
3004
3005 return if !$enable;
3006
3007 # load required modules here
3008 }
3009
3010 sub update {
3011 my ($verbose) = @_;
3012
3013 my $code = sub {
3014
3015 my $cluster_conf = load_clusterfw_conf();
3016 my $cluster_options = $cluster_conf->{options};
3017
3018 my $enable = $cluster_options->{enable};
3019
3020 die "Firewall is disabled - cannot start\n" if !$enable;
3021
3022 if (!$enable) {
3023 PVE::Firewall::remove_pvefw_chains();
3024 print "Firewall disabled\n" if $verbose;
3025 return;
3026 }
3027
3028 my $hostfw_conf = load_hostfw_conf();
3029
3030 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
3031
3032 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
3033 };
3034
3035 run_locked($code);
3036 }
3037
3038 1;