]> git.proxmox.com Git - pve-firewall.git/blob - src/PVE/Firewall.pm
only allow tcpflafgs and nosmurfs in 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, "-d $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, $host_options, $macaddr, $direction) = @_;
1429
1430 ruleset_create_chain($ruleset, $chain);
1431 my $accept = generate_nfqueue($options);
1432
1433 if (!(defined($host_options->{nosmurfs}) && $host_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 ($host_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, $hostfw_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 $hostfw_options = $vmfw_conf->{options};
1551 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1552
1553 my $chain = "venet0-$vmid-$direction";
1554
1555 ruleset_create_vm_chain($ruleset, $chain, $options, $hostfw_options, undef, $direction);
1556
1557 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1558
1559 # implement policy
1560 my $policy;
1561
1562 if ($direction eq 'OUT') {
1563 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1564 } else {
1565 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1566 }
1567
1568 my $accept = generate_nfqueue($options);
1569 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1570 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1571
1572 # plug into FORWARD, INPUT and OUTPUT chain
1573 if ($direction eq 'OUT') {
1574 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD", {
1575 action => $chain,
1576 source => $ip,
1577 iface_in => 'venet0'});
1578
1579 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT", {
1580 action => $chain,
1581 source => $ip,
1582 iface_in => 'venet0'});
1583 } else {
1584 ruleset_generate_rule($ruleset, "PVEFW-FORWARD", {
1585 action => $chain,
1586 dest => $ip,
1587 iface_out => 'venet0'});
1588
1589 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT", {
1590 action => $chain,
1591 dest => $ip,
1592 iface_out => 'venet0'});
1593 }
1594 }
1595
1596 sub generate_tap_rules_direction {
1597 my ($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1598
1599 my $lc_direction = lc($direction);
1600
1601 my $rules = $vmfw_conf->{rules};
1602
1603 my $options = $vmfw_conf->{options};
1604 my $hostfw_options = $hostfw_conf->{options};
1605 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
1606
1607 my $tapchain = "$iface-$direction";
1608
1609 ruleset_create_vm_chain($ruleset, $tapchain, $options, $hostfw_options, $macaddr, $direction);
1610
1611 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1612
1613 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1614
1615 # implement policy
1616 my $policy;
1617
1618 if ($direction eq 'OUT') {
1619 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1620 } else {
1621 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1622 }
1623
1624 my $accept = generate_nfqueue($options);
1625 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
1626 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1627
1628 # plug the tap chain to bridge chain
1629 if ($direction eq 'IN') {
1630 ruleset_insertrule($ruleset, "$bridge-IN",
1631 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
1632 } else {
1633 ruleset_insertrule($ruleset, "$bridge-OUT",
1634 "-m physdev --physdev-in $iface -j $tapchain");
1635 }
1636 }
1637
1638 sub enable_host_firewall {
1639 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1640
1641 my $options = $hostfw_conf->{options};
1642 my $cluster_options = $cluster_conf->{options};
1643 my $rules = $hostfw_conf->{rules};
1644 my $cluster_rules = $cluster_conf->{rules};
1645
1646 # host inbound firewall
1647 my $chain = "PVEFW-HOST-IN";
1648 ruleset_create_chain($ruleset, $chain);
1649
1650 my $loglevel = get_option_log_level($options, "log_level_in");
1651
1652 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1653 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1654 }
1655
1656 if ($options->{tcpflags}) {
1657 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1658 }
1659
1660 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1661 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1662 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
1663 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1664 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1665 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1666
1667 # we use RETURN because we need to check also tap rules
1668 my $accept_action = 'RETURN';
1669
1670 # add host rules first, so that cluster wide rules can be overwritten
1671 foreach my $rule (@$rules, @$cluster_rules) {
1672 next if $rule->{type} ne 'in';
1673 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1674 }
1675
1676 # implement input policy
1677 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1678 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1679
1680 # host outbound firewall
1681 $chain = "PVEFW-HOST-OUT";
1682 ruleset_create_chain($ruleset, $chain);
1683
1684 $loglevel = get_option_log_level($options, "log_level_out");
1685
1686 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1687 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
1688 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
1689 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
1690 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW --dport 5404:5405 -j ACCEPT");
1691 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
1692
1693 # we use RETURN because we may want to check other thigs later
1694 $accept_action = 'RETURN';
1695
1696 # add host rules first, so that cluster wide rules can be overwritten
1697 foreach my $rule (@$rules, @$cluster_rules) {
1698 next if $rule->{type} ne 'out';
1699 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1700 }
1701
1702 # implement output policy
1703 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1704 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1705
1706 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
1707 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
1708 }
1709
1710 sub generate_group_rules {
1711 my ($ruleset, $cluster_conf, $group) = @_;
1712 die "no such security group '$group'\n" if !$cluster_conf->{groups}->{$group};
1713
1714 my $rules = $cluster_conf->{groups}->{$group};
1715
1716 my $chain = "GROUP-${group}-IN";
1717
1718 ruleset_create_chain($ruleset, $chain);
1719 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1720
1721 foreach my $rule (@$rules) {
1722 next if $rule->{type} ne 'in';
1723 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1724 }
1725
1726 $chain = "GROUP-${group}-OUT";
1727
1728 ruleset_create_chain($ruleset, $chain);
1729 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1730
1731 foreach my $rule (@$rules) {
1732 next if $rule->{type} ne 'out';
1733 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1734 # check also other tap rules later
1735 ruleset_generate_rule($ruleset, $chain, $rule,
1736 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" }, undef, $cluster_conf);
1737 }
1738 }
1739
1740 my $MAX_NETS = 32;
1741 my $valid_netdev_names = {};
1742 for (my $i = 0; $i < $MAX_NETS; $i++) {
1743 $valid_netdev_names->{"net$i"} = 1;
1744 }
1745
1746 sub parse_fw_rule {
1747 my ($line, $need_iface, $allow_groups) = @_;
1748
1749 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1750
1751 # we can add single line comments to the end of the rule
1752 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1753
1754 # we can disable a rule when prefixed with '|'
1755 my $enable = 1;
1756
1757 $enable = 0 if $line =~ s/^\|//;
1758
1759 my @data = split(/\s+/, $line);
1760 my $expected_elements = $need_iface ? 8 : 7;
1761
1762 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1763
1764 if ($need_iface) {
1765 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1766 } else {
1767 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1768 }
1769
1770 die "incomplete rule\n" if ! ($type && $action);
1771
1772 my $macro;
1773
1774 $type = lc($type);
1775
1776 if ($type eq 'in' || $type eq 'out') {
1777 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1778 # OK
1779 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1780 $action = $2;
1781 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1782 die "unknown macro '$1'\n" if !$preferred_name;
1783 $macro = $preferred_name;
1784 } else {
1785 die "unknown action '$action'\n";
1786 }
1787 } elsif ($type eq 'group') {
1788 die "wrong number of rule elements\n" if scalar(@data) != 3;
1789 die "groups disabled\n" if !$allow_groups;
1790
1791 die "invalid characters in group name\n" if $action !~ m/^${security_group_pattern}$/;
1792 } else {
1793 die "unknown rule type '$type'\n";
1794 }
1795
1796 if ($need_iface) {
1797 $iface = undef if $iface && $iface eq '-';
1798 }
1799
1800 $proto = undef if $proto && $proto eq '-';
1801 pve_fw_verify_protocol_spec($proto) if $proto;
1802
1803 $source = undef if $source && $source eq '-';
1804 $dest = undef if $dest && $dest eq '-';
1805
1806 $dport = undef if $dport && $dport eq '-';
1807 $sport = undef if $sport && $sport eq '-';
1808
1809 parse_port_name_number_or_range($dport) if defined($dport);
1810 parse_port_name_number_or_range($sport) if defined($sport);
1811
1812 parse_address_list($source) if $source;
1813 parse_address_list($dest) if $dest;
1814
1815 return {
1816 type => $type,
1817 enable => $enable,
1818 comment => $comment,
1819 action => $action,
1820 macro => $macro,
1821 iface => $iface,
1822 source => $source,
1823 dest => $dest,
1824 proto => $proto,
1825 dport => $dport,
1826 sport => $sport,
1827 };
1828 }
1829
1830 sub parse_vmfw_option {
1831 my ($line) = @_;
1832
1833 my ($opt, $value);
1834
1835 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1836
1837 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
1838 $opt = lc($1);
1839 $value = int($2);
1840 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1841 $opt = lc($1);
1842 $value = $2 ? lc($3) : '';
1843 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1844 $opt = lc($1);
1845 $value = uc($3);
1846 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1847 $opt = lc($1);
1848 $value = $2;
1849 } else {
1850 chomp $line;
1851 die "can't parse option '$line'\n"
1852 }
1853
1854 return ($opt, $value);
1855 }
1856
1857 sub parse_hostfw_option {
1858 my ($line) = @_;
1859
1860 my ($opt, $value);
1861
1862 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1863
1864 if ($line =~ m/^(enable|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1865 $opt = lc($1);
1866 $value = int($2);
1867 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1868 $opt = lc($1);
1869 $value = $2 ? lc($3) : '';
1870 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
1871 $opt = lc($1);
1872 $value = int($2);
1873 } else {
1874 chomp $line;
1875 die "can't parse option '$line'\n"
1876 }
1877
1878 return ($opt, $value);
1879 }
1880
1881 sub parse_clusterfw_option {
1882 my ($line) = @_;
1883
1884 my ($opt, $value);
1885
1886 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1887 $opt = lc($1);
1888 $value = int($2);
1889 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1890 $opt = lc($1);
1891 $value = uc($3);
1892 } else {
1893 chomp $line;
1894 die "can't parse option '$line'\n"
1895 }
1896
1897 return ($opt, $value);
1898 }
1899
1900 sub parse_vm_fw_rules {
1901 my ($filename, $fh) = @_;
1902
1903 my $res = { rules => [], options => {}};
1904
1905 my $section;
1906
1907 while (defined(my $line = <$fh>)) {
1908 next if $line =~ m/^#/;
1909 next if $line =~ m/^\s*$/;
1910
1911 my $linenr = $fh->input_line_number();
1912 my $prefix = "$filename (line $linenr)";
1913
1914 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1915 $section = lc($1);
1916 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1917 next;
1918 }
1919 if (!$section) {
1920 warn "$prefix: skip line - no section";
1921 next;
1922 }
1923
1924 next if !$res->{$section}; # skip undefined section
1925
1926 if ($section eq 'options') {
1927 eval {
1928 my ($opt, $value) = parse_vmfw_option($line);
1929 $res->{options}->{$opt} = $value;
1930 };
1931 warn "$prefix: $@" if $@;
1932 next;
1933 }
1934
1935 my $rule;
1936 eval { $rule = parse_fw_rule($line, 1, 1); };
1937 if (my $err = $@) {
1938 warn "$prefix: $err";
1939 next;
1940 }
1941
1942 push @{$res->{$section}}, $rule;
1943 }
1944
1945 return $res;
1946 }
1947
1948 sub parse_host_fw_rules {
1949 my ($filename, $fh) = @_;
1950
1951 my $res = { rules => [], options => {}};
1952
1953 my $section;
1954
1955 while (defined(my $line = <$fh>)) {
1956 next if $line =~ m/^#/;
1957 next if $line =~ m/^\s*$/;
1958
1959 my $linenr = $fh->input_line_number();
1960 my $prefix = "$filename (line $linenr)";
1961
1962 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1963 $section = lc($1);
1964 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1965 next;
1966 }
1967 if (!$section) {
1968 warn "$prefix: skip line - no section";
1969 next;
1970 }
1971
1972 next if !$res->{$section}; # skip undefined section
1973
1974 if ($section eq 'options') {
1975 eval {
1976 my ($opt, $value) = parse_hostfw_option($line);
1977 $res->{options}->{$opt} = $value;
1978 };
1979 warn "$prefix: $@" if $@;
1980 next;
1981 }
1982
1983 my $rule;
1984 eval { $rule = parse_fw_rule($line, 1, 1); };
1985 if (my $err = $@) {
1986 warn "$prefix: $err";
1987 next;
1988 }
1989
1990 push @{$res->{$section}}, $rule;
1991 }
1992
1993 return $res;
1994 }
1995
1996 sub parse_cluster_fw_rules {
1997 my ($filename, $fh) = @_;
1998
1999 my $section;
2000 my $group;
2001
2002 my $res = {
2003 rules => [],
2004 options => {},
2005 groups => {},
2006 group_comments => {},
2007 ipset => {} ,
2008 ipset_comments => {},
2009 };
2010
2011 while (defined(my $line = <$fh>)) {
2012 next if $line =~ m/^#/;
2013 next if $line =~ m/^\s*$/;
2014
2015 my $linenr = $fh->input_line_number();
2016 my $prefix = "$filename (line $linenr)";
2017
2018 if ($line =~ m/^\[options\]$/i) {
2019 $section = 'options';
2020 next;
2021 }
2022
2023 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2024 $section = 'groups';
2025 $group = lc($1);
2026 my $comment = $2;
2027 $res->{$section}->{$group} = [];
2028 $res->{group_comments}->{$group} = decode('utf8', $comment)
2029 if $comment;
2030 next;
2031 }
2032
2033 if ($line =~ m/^\[rules\]$/i) {
2034 $section = 'rules';
2035 next;
2036 }
2037
2038 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2039 $section = 'ipset';
2040 $group = lc($1);
2041 my $comment = $2;
2042 $res->{$section}->{$group} = [];
2043 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
2044 if $comment;
2045 next;
2046 }
2047
2048 if (!$section) {
2049 warn "$prefix: skip line - no section\n";
2050 next;
2051 }
2052
2053 if ($section eq 'options') {
2054 eval {
2055 my ($opt, $value) = parse_clusterfw_option($line);
2056 $res->{options}->{$opt} = $value;
2057 };
2058 warn "$prefix: $@" if $@;
2059 } elsif ($section eq 'rules') {
2060 my $rule;
2061 eval { $rule = parse_fw_rule($line, 1, 1); };
2062 if (my $err = $@) {
2063 warn "$prefix: $err";
2064 next;
2065 }
2066 push @{$res->{$section}}, $rule;
2067 } elsif ($section eq 'groups') {
2068 my $rule;
2069 eval { $rule = parse_fw_rule($line, 0, 0); };
2070 if (my $err = $@) {
2071 warn "$prefix: $err";
2072 next;
2073 }
2074 push @{$res->{$section}->{$group}}, $rule;
2075 } elsif ($section eq 'ipset') {
2076 # we can add single line comments to the end of the rule
2077 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2078
2079 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2080 my $nomatch = $1;
2081 my $cidr = $2;
2082
2083 $cidr =~ s|/32$||;
2084
2085 eval { pve_verify_ipv4_or_cidr($cidr); };
2086 if (my $err = $@) {
2087 warn "$prefix: $cidr - $err";
2088 next;
2089 }
2090
2091 my $entry = { cidr => $cidr };
2092 $entry->{nomatch} = 1 if $nomatch;
2093 $entry->{comment} = $comment if $comment;
2094
2095 push @{$res->{$section}->{$group}}, $entry;
2096 }
2097 }
2098
2099 return $res;
2100 }
2101
2102 sub run_locked {
2103 my ($code, @param) = @_;
2104
2105 my $timeout = 10;
2106
2107 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2108
2109 die $@ if $@;
2110
2111 return $res;
2112 }
2113
2114 sub read_local_vm_config {
2115
2116 my $openvz = {};
2117 my $qemu = {};
2118
2119 my $vmdata = { openvz => $openvz, qemu => $qemu };
2120
2121 my $vmlist = PVE::Cluster::get_vmlist();
2122 return $vmdata if !$vmlist || !$vmlist->{ids};
2123 my $ids = $vmlist->{ids};
2124
2125 foreach my $vmid (keys %$ids) {
2126 next if !$vmid; # skip VE0
2127 my $d = $ids->{$vmid};
2128 next if !$d->{node} || $d->{node} ne $nodename;
2129 next if !$d->{type};
2130 if ($d->{type} eq 'openvz') {
2131 if ($have_pve_manager) {
2132 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2133 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2134 $openvz->{$vmid} = $conf;
2135 }
2136 }
2137 } elsif ($d->{type} eq 'qemu') {
2138 if ($have_qemu_server) {
2139 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2140 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2141 $qemu->{$vmid} = $conf;
2142 }
2143 }
2144 }
2145 }
2146
2147 return $vmdata;
2148 };
2149
2150 sub load_vmfw_conf {
2151 my ($vmid) = @_;
2152
2153 my $vmfw_conf = {};
2154
2155 my $filename = "/etc/pve/firewall/$vmid.fw";
2156 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2157 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2158 }
2159
2160 return $vmfw_conf;
2161 }
2162
2163 my $format_rules = sub {
2164 my ($rules, $need_iface) = @_;
2165
2166 my $raw = '';
2167
2168 foreach my $rule (@$rules) {
2169 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
2170 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2171 $raw .= uc($rule->{type});
2172 if ($rule->{macro}) {
2173 $raw .= " $rule->{macro}($rule->{action})";
2174 } else {
2175 $raw .= " " . $rule->{action};
2176 }
2177 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2178
2179 if ($rule->{type} ne 'group') {
2180 $raw .= " " . ($rule->{source} || '-');
2181 $raw .= " " . ($rule->{dest} || '-');
2182 $raw .= " " . ($rule->{proto} || '-');
2183 $raw .= " " . ($rule->{dport} || '-');
2184 $raw .= " " . ($rule->{sport} || '-');
2185 }
2186
2187 $raw .= " # " . encode('utf8', $rule->{comment})
2188 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2189 $raw .= "\n";
2190 } else {
2191 die "unknown rule type '$rule->{type}'";
2192 }
2193 }
2194
2195 return $raw;
2196 };
2197
2198 my $format_options = sub {
2199 my ($options) = @_;
2200
2201 my $raw = '';
2202
2203 $raw .= "[OPTIONS]\n\n";
2204 foreach my $opt (keys %$options) {
2205 $raw .= "$opt: $options->{$opt}\n";
2206 }
2207 $raw .= "\n";
2208
2209 return $raw;
2210 };
2211
2212 my $format_ipset = sub {
2213 my ($options) = @_;
2214
2215 my $raw = '';
2216
2217 my $nethash = {};
2218 foreach my $entry (@$options) {
2219 $nethash->{$entry->{cidr}} = $entry;
2220 }
2221
2222 foreach my $cidr (sort keys %$nethash) {
2223 my $entry = $nethash->{$cidr};
2224 my $line = $entry->{nomatch} ? '!' : '';
2225 $line .= $entry->{cidr};
2226 $line .= " # " . encode('utf8', $entry->{comment})
2227 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2228 $raw .= "$line\n";
2229 }
2230
2231 return $raw;
2232 };
2233
2234 sub save_vmfw_conf {
2235 my ($vmid, $vmfw_conf) = @_;
2236
2237 my $raw = '';
2238
2239 my $options = $vmfw_conf->{options};
2240 $raw .= &$format_options($options) if scalar(keys %$options);
2241
2242 my $rules = $vmfw_conf->{rules};
2243 if (scalar(@$rules)) {
2244 $raw .= "[RULES]\n\n";
2245 $raw .= &$format_rules($rules, 1);
2246 $raw .= "\n";
2247 }
2248
2249 my $filename = "/etc/pve/firewall/$vmid.fw";
2250 PVE::Tools::file_set_contents($filename, $raw);
2251 }
2252
2253 sub read_vm_firewall_configs {
2254 my ($vmdata) = @_;
2255 my $vmfw_configs = {};
2256
2257 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2258 my $vmfw_conf = load_vmfw_conf($vmid);
2259 next if !$vmfw_conf->{options}; # skip if file does not exists
2260 $vmfw_configs->{$vmid} = $vmfw_conf;
2261 }
2262
2263 return $vmfw_configs;
2264 }
2265
2266 sub get_option_log_level {
2267 my ($options, $k) = @_;
2268
2269 my $v = $options->{$k};
2270 $v = $default_log_level if !defined($v);
2271
2272 return undef if $v eq '' || $v eq 'nolog';
2273
2274 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2275
2276 return $v if ($v >= 0) && ($v <= 7);
2277
2278 warn "unknown log level ($k = '$v')\n";
2279
2280 return undef;
2281 }
2282
2283 sub generate_std_chains {
2284 my ($ruleset, $options) = @_;
2285
2286 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2287
2288 # same as shorewall smurflog.
2289 my $chain = 'PVEFW-smurflog';
2290 $pve_std_chains->{$chain} = [];
2291
2292 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2293 push @{$pve_std_chains->{$chain}}, "-j DROP";
2294
2295 # same as shorewall logflags action.
2296 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
2297 $chain = 'PVEFW-logflags';
2298 $pve_std_chains->{$chain} = [];
2299
2300 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2301 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2302 push @{$pve_std_chains->{$chain}}, "-j DROP";
2303
2304 foreach my $chain (keys %$pve_std_chains) {
2305 ruleset_create_chain($ruleset, $chain);
2306 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2307 if (ref($rule)) {
2308 ruleset_generate_rule($ruleset, $chain, $rule);
2309 } else {
2310 ruleset_addrule($ruleset, $chain, $rule);
2311 }
2312 }
2313 }
2314 }
2315
2316 sub generate_ipset_chains {
2317 my ($ipset_ruleset, $fw_conf) = @_;
2318
2319 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2320 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2321 }
2322 }
2323
2324 sub generate_ipset {
2325 my ($ipset_ruleset, $name, $options) = @_;
2326
2327 my $hashsize = scalar(@$options);
2328 if ($hashsize <= 64) {
2329 $hashsize = 64;
2330 } else {
2331 $hashsize = round_powerof2($hashsize);
2332 }
2333
2334 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2335
2336 # remove duplicates
2337 my $nethash = {};
2338 foreach my $entry (@$options) {
2339 $nethash->{$entry->{cidr}} = $entry;
2340 }
2341
2342 foreach my $cidr (sort keys %$nethash) {
2343 my $entry = $nethash->{$cidr};
2344
2345 my $cmd = "add $name $cidr";
2346 if ($entry->{nomatch}) {
2347 if ($feature_ipset_nomatch) {
2348 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2349 } else {
2350 warn "ignore !$cidr - nomatch not supported by kernel\n";
2351 }
2352 } else {
2353 push @{$ipset_ruleset->{$name}}, $cmd;
2354 }
2355 }
2356 }
2357
2358 sub round_powerof2 {
2359 my ($int) = @_;
2360
2361 $int--;
2362 $int |= $int >> $_ foreach (1,2,4,8,16);
2363 return ++$int;
2364 }
2365
2366 sub save_pvefw_status {
2367 my ($status) = @_;
2368
2369 die "unknown status '$status' - internal error"
2370 if $status !~ m/^(stopped|active)$/;
2371
2372 mkdir dirname($pve_fw_status_filename);
2373 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2374 }
2375
2376 sub read_pvefw_status {
2377
2378 my $status = 'unknown';
2379
2380 return 'stopped' if ! -f $pve_fw_status_filename;
2381
2382 eval {
2383 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2384 };
2385 warn $@ if $@;
2386
2387 return $status;
2388 }
2389
2390 # fixme: move to pve-common PVE::ProcFSTools
2391 sub read_proc_net_route {
2392 my $filename = "/proc/net/route";
2393
2394 my $res = {};
2395
2396 my $fh = IO::File->new ($filename, "r");
2397 return $res if !$fh;
2398
2399 my $int_to_quad = sub {
2400 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2401 };
2402
2403 while (defined(my $line = <$fh>)) {
2404 next if $line =~/^Iface\s+Destination/; # skip head
2405 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2406 push @{$res->{$iface}}, {
2407 dest => &$int_to_quad(hex($dest)),
2408 gateway => &$int_to_quad(hex($gateway)),
2409 mask => &$int_to_quad(hex($mask)),
2410 metric => $metric,
2411 mtu => $mtu,
2412 };
2413 }
2414
2415 return $res;
2416 }
2417
2418 sub load_clusterfw_conf {
2419
2420 my $cluster_conf = {};
2421 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2422 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2423 }
2424
2425 return $cluster_conf;
2426 }
2427
2428 sub save_clusterfw_conf {
2429 my ($cluster_conf) = @_;
2430
2431 my $raw = '';
2432
2433 my $options = $cluster_conf->{options};
2434 $raw .= &$format_options($options) if scalar(keys %$options);
2435
2436 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2437 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2438 my $utf8comment = encode('utf8', $comment);
2439 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2440 } else {
2441 $raw .= "[IPSET $ipset]\n\n";
2442 }
2443 my $options = $cluster_conf->{ipset}->{$ipset};
2444 $raw .= &$format_ipset($options);
2445 $raw .= "\n";
2446 }
2447
2448 my $rules = $cluster_conf->{rules};
2449 if (scalar(@$rules)) {
2450 $raw .= "[RULES]\n\n";
2451 $raw .= &$format_rules($rules, 1);
2452 $raw .= "\n";
2453 }
2454
2455 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2456 my $rules = $cluster_conf->{groups}->{$group};
2457 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2458 my $utf8comment = encode('utf8', $comment);
2459 $raw .= "[group $group] # $utf8comment\n\n";
2460 } else {
2461 $raw .= "[group $group]\n\n";
2462 }
2463
2464 $raw .= &$format_rules($rules, 0);
2465 $raw .= "\n";
2466 }
2467
2468 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2469 }
2470
2471 sub load_hostfw_conf {
2472
2473 my $hostfw_conf = {};
2474 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2475 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2476 }
2477 return $hostfw_conf;
2478 }
2479
2480 sub save_hostfw_conf {
2481 my ($hostfw_conf) = @_;
2482
2483 my $raw = '';
2484
2485 my $options = $hostfw_conf->{options};
2486 $raw .= &$format_options($options) if scalar(keys %$options);
2487
2488 my $rules = $hostfw_conf->{rules};
2489 if (scalar(@$rules)) {
2490 $raw .= "[RULES]\n\n";
2491 $raw .= &$format_rules($rules, 1);
2492 $raw .= "\n";
2493 }
2494
2495 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2496 }
2497
2498 sub compile {
2499 my ($cluster_conf, $hostfw_conf) = @_;
2500
2501 $cluster_conf = load_clusterfw_conf() if !$cluster_conf;
2502 $hostfw_conf = load_hostfw_conf() if !$hostfw_conf;
2503
2504 my $vmdata = read_local_vm_config();
2505 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2506
2507 my $routing_table = read_proc_net_route();
2508
2509 my $ipset_ruleset = {};
2510 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2511
2512 my $ruleset = {};
2513
2514 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2515 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2516
2517 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2518
2519 my $hostfw_options = $hostfw_conf->{options} || {};
2520
2521 generate_std_chains($ruleset, $hostfw_options);
2522
2523 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2524
2525 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2526
2527 # generate firewall rules for QEMU VMs
2528 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2529 my $conf = $vmdata->{qemu}->{$vmid};
2530 my $vmfw_conf = $vmfw_configs->{$vmid};
2531 next if !$vmfw_conf;
2532 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2533
2534 foreach my $netid (keys %$conf) {
2535 next if $netid !~ m/^net(\d+)$/;
2536 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2537 next if !$net;
2538 my $iface = "tap${vmid}i$1";
2539
2540 my $bridge = $net->{bridge};
2541 next if !$bridge; # fixme: ?
2542
2543 $bridge .= "v$net->{tag}" if $net->{tag};
2544
2545 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2546
2547 my $macaddr = $net->{macaddr};
2548 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2549 $vmfw_conf, $vmid, $bridge, 'IN');
2550 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2551 $vmfw_conf, $vmid, $bridge, 'OUT');
2552 }
2553 }
2554
2555 # generate firewall rules for OpenVZ containers
2556 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2557 my $conf = $vmdata->{openvz}->{$vmid};
2558
2559 my $vmfw_conf = $vmfw_configs->{$vmid};
2560 next if !$vmfw_conf;
2561 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2562
2563 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2564 my $ip = $conf->{ip_address}->{value};
2565 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'IN');
2566 generate_venet_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $vmfw_conf, $vmid, $ip, 'OUT');
2567 }
2568
2569 if ($conf->{netif} && $conf->{netif}->{value}) {
2570 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2571 foreach my $netid (keys %$netif) {
2572 my $d = $netif->{$netid};
2573 my $bridge = $d->{bridge};
2574 if (!$bridge) {
2575 warn "no bridge device for CT $vmid iface '$netid'\n";
2576 next; # fixme?
2577 }
2578
2579 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2580
2581 my $macaddr = $d->{mac};
2582 my $iface = $d->{host_ifname};
2583 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2584 $vmfw_conf, $vmid, $bridge, 'IN');
2585 generate_tap_rules_direction($ruleset, $cluster_conf, $hostfw_conf, $iface, $netid, $macaddr,
2586 $vmfw_conf, $vmid, $bridge, 'OUT');
2587 }
2588 }
2589 }
2590
2591 if($hostfw_options->{optimize}){
2592
2593 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2594 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2595 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2596 }
2597
2598 # fixme: what log level should we use here?
2599 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2600
2601 # fixme: should we really block inter-bridge traffic?
2602
2603 # always allow traffic from containers?
2604 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2605
2606 # disable interbridge routing
2607 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2608 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2609 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2610 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2611 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2612 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2613
2614 return ($ruleset, $ipset_ruleset);
2615 }
2616
2617 sub get_ruleset_status {
2618 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2619
2620 my $statushash = {};
2621
2622 foreach my $chain (sort keys %$ruleset) {
2623 my $sig = &$digest_fn($ruleset->{$chain});
2624
2625 $statushash->{$chain}->{sig} = $sig;
2626
2627 my $oldsig = $active_chains->{$chain};
2628 if (!defined($oldsig)) {
2629 $statushash->{$chain}->{action} = 'create';
2630 } else {
2631 if ($oldsig eq $sig) {
2632 $statushash->{$chain}->{action} = 'exists';
2633 } else {
2634 $statushash->{$chain}->{action} = 'update';
2635 }
2636 }
2637 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2638 foreach my $cmd (@{$ruleset->{$chain}}) {
2639 print "\t$cmd\n" if $verbose;
2640 }
2641 }
2642
2643 foreach my $chain (sort keys %$active_chains) {
2644 if (!defined($ruleset->{$chain})) {
2645 my $sig = $active_chains->{$chain};
2646 $statushash->{$chain}->{action} = 'delete';
2647 $statushash->{$chain}->{sig} = $sig;
2648 print "delete $chain ($sig)\n" if $verbose;
2649 }
2650 }
2651
2652 return $statushash;
2653 }
2654
2655 sub print_sig_rule {
2656 my ($chain, $sig) = @_;
2657
2658 # We just use this to store a SHA1 checksum used to detect changes
2659 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2660 }
2661
2662 sub get_ruleset_cmdlist {
2663 my ($ruleset, $verbose) = @_;
2664
2665 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2666
2667 my ($active_chains, $hooks) = iptables_get_chains();
2668 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2669
2670 # create missing chains first
2671 foreach my $chain (sort keys %$ruleset) {
2672 my $stat = $statushash->{$chain};
2673 die "internal error" if !$stat;
2674 next if $stat->{action} ne 'create';
2675
2676 $cmdlist .= ":$chain - [0:0]\n";
2677 }
2678
2679 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2680 if (!$hooks->{$h}) {
2681 $cmdlist .= "-A $h -j PVEFW-$h\n";
2682 }
2683 }
2684
2685 foreach my $chain (sort keys %$ruleset) {
2686 my $stat = $statushash->{$chain};
2687 die "internal error" if !$stat;
2688
2689 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
2690 $cmdlist .= "-F $chain\n";
2691 foreach my $cmd (@{$ruleset->{$chain}}) {
2692 $cmdlist .= "$cmd\n";
2693 }
2694 $cmdlist .= print_sig_rule($chain, $stat->{sig});
2695 } elsif ($stat->{action} eq 'delete') {
2696 die "internal error"; # this should not happen
2697 } elsif ($stat->{action} eq 'exists') {
2698 # do nothing
2699 } else {
2700 die "internal error - unknown status '$stat->{action}'";
2701 }
2702 }
2703
2704 foreach my $chain (keys %$statushash) {
2705 next if $statushash->{$chain}->{action} ne 'delete';
2706 $cmdlist .= "-F $chain\n";
2707 }
2708 foreach my $chain (keys %$statushash) {
2709 next if $statushash->{$chain}->{action} ne 'delete';
2710 next if $chain eq 'PVEFW-INPUT';
2711 next if $chain eq 'PVEFW-OUTPUT';
2712 next if $chain eq 'PVEFW-FORWARD';
2713 $cmdlist .= "-X $chain\n";
2714 }
2715
2716 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
2717
2718 $cmdlist .= "COMMIT\n";
2719
2720 return wantarray ? ($cmdlist, $changes) : $cmdlist;
2721 }
2722
2723 sub get_ipset_cmdlist {
2724 my ($ruleset, $verbose) = @_;
2725
2726 my $cmdlist = "";
2727
2728 my $delete_cmdlist = "";
2729
2730 my $active_chains = ipset_get_chains();
2731 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
2732
2733 # remove stale _swap chains
2734 foreach my $chain (keys %$active_chains) {
2735 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2736 $cmdlist .= "destroy $chain\n";
2737 }
2738 }
2739
2740 foreach my $chain (sort keys %$ruleset) {
2741 my $stat = $statushash->{$chain};
2742 die "internal error" if !$stat;
2743
2744 if ($stat->{action} eq 'create') {
2745 foreach my $cmd (@{$ruleset->{$chain}}) {
2746 $cmdlist .= "$cmd\n";
2747 }
2748 }
2749
2750 if ($stat->{action} eq 'update') {
2751 my $chain_swap = $chain."_swap";
2752
2753 foreach my $cmd (@{$ruleset->{$chain}}) {
2754 $cmd =~ s/$chain/$chain_swap/;
2755 $cmdlist .= "$cmd\n";
2756 }
2757 $cmdlist .= "swap $chain_swap $chain\n";
2758 $cmdlist .= "flush $chain_swap\n";
2759 $cmdlist .= "destroy $chain_swap\n";
2760 }
2761
2762 }
2763
2764 foreach my $chain (keys %$statushash) {
2765 next if $statushash->{$chain}->{action} ne 'delete';
2766
2767 $delete_cmdlist .= "flush $chain\n";
2768 $delete_cmdlist .= "destroy $chain\n";
2769 }
2770
2771 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
2772
2773 return ($cmdlist, $delete_cmdlist, $changes);
2774 }
2775
2776 sub apply_ruleset {
2777 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2778
2779 enable_bridge_firewall();
2780
2781 update_nf_conntrack_max($hostfw_conf);
2782
2783 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
2784
2785 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2786 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
2787
2788 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
2789
2790 if ($verbose) {
2791 if ($ipset_changes) {
2792 print "ipset changes:\n";
2793 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2794 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2795 }
2796
2797 if ($changes) {
2798 print "iptables changes:\n";
2799 print $cmdlist;
2800 }
2801 }
2802
2803 ipset_restore_cmdlist($ipset_create_cmdlist);
2804
2805 iptables_restore_cmdlist($cmdlist);
2806
2807 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2808
2809 # test: re-read status and check if everything is up to date
2810 my $active_chains = iptables_get_chains();
2811 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
2812
2813 my $errors;
2814 foreach my $chain (sort keys %$ruleset) {
2815 my $stat = $statushash->{$chain};
2816 if ($stat->{action} ne 'exists') {
2817 warn "unable to update chain '$chain'\n";
2818 $errors = 1;
2819 }
2820 }
2821
2822 die "unable to apply firewall changes\n" if $errors;
2823 }
2824
2825 sub update_nf_conntrack_max {
2826 my ($hostfw_conf) = @_;
2827
2828 my $max = 65536; # reasonable default
2829
2830 my $options = $hostfw_conf->{options} || {};
2831
2832 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
2833 $max = $options->{nf_conntrack_max};
2834 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2835 }
2836
2837 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2838 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2839
2840 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
2841
2842 if ($current != $max) {
2843 my $hashsize = int($max/4);
2844 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
2845 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
2846 }
2847 }
2848
2849 sub update_nf_conntrack_tcp_timeout_established {
2850 my ($hostfw_conf) = @_;
2851
2852 my $options = $hostfw_conf->{options} || {};
2853
2854 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
2855
2856 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
2857 }
2858
2859 sub remove_pvefw_chains {
2860
2861 my ($chash, $hooks) = iptables_get_chains();
2862 my $cmdlist = "*filter\n";
2863
2864 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2865 if ($hooks->{$h}) {
2866 $cmdlist .= "-D $h -j PVEFW-$h\n";
2867 }
2868 }
2869
2870 foreach my $chain (keys %$chash) {
2871 $cmdlist .= "-F $chain\n";
2872 }
2873
2874 foreach my $chain (keys %$chash) {
2875 $cmdlist .= "-X $chain\n";
2876 }
2877 $cmdlist .= "COMMIT\n";
2878
2879 iptables_restore_cmdlist($cmdlist);
2880 }
2881
2882 sub update {
2883 my ($start, $verbose) = @_;
2884
2885 my $code = sub {
2886
2887 my $cluster_conf = load_clusterfw_conf();
2888 my $cluster_options = $cluster_conf->{options};
2889
2890 my $enable = $cluster_options->{enable};
2891
2892 my $status = read_pvefw_status();
2893
2894 die "Firewall is disabled - cannot start\n" if !$enable && $start;
2895
2896 if (!$enable) {
2897 PVE::Firewall::remove_pvefw_chains();
2898 print "Firewall disabled\n" if $verbose;
2899 return;
2900 }
2901
2902 my $hostfw_conf = load_hostfw_conf();
2903
2904 my ($ruleset, $ipset_ruleset) = compile($cluster_conf, $hostfw_conf);
2905
2906 if ($start || $status eq 'active') {
2907
2908 save_pvefw_status('active') if ($status ne 'active');
2909
2910 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2911 } else {
2912 print "Firewall not active (status = $status)\n" if $verbose;
2913 }
2914 };
2915
2916 run_locked($code);
2917 }
2918
2919
2920 1;