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