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