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