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