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