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