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