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