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