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