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