implement log level options
[pve-firewall.git] / PVE / Firewall.pm
1 package PVE::Firewall;
2
3 use warnings;
4 use strict;
5 use Data::Dumper;
6 use Digest::SHA;
7 use PVE::Tools;
8 use PVE::QemuServer;
9 use File::Basename;
10 use File::Path;
11 use IO::File;
12 use Net::IP;
13 use PVE::Tools qw(run_command lock_file);
14
15 use Data::Dumper;
16
17 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
18 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
19
20 my $default_log_level = 'info';
21
22 my $log_level_hash = {
23 debug => 7,
24 info => 6,
25 notice => 5,
26 warning => 4,
27 err => 3,
28 crit => 2,
29 alert => 1,
30 emerg => 0,
31 };
32
33 # imported/converted from: /usr/share/shorewall/macro.*
34 my $pve_fw_macros = {
35 'Amanda' => [
36 { action => 'PARAM', proto => 'udp', dport => '10080' },
37 { action => 'PARAM', proto => 'tcp', dport => '10080' },
38 ],
39 'Auth' => [
40 { action => 'PARAM', proto => 'tcp', dport => '113' },
41 ],
42 'BGP' => [
43 { action => 'PARAM', proto => 'tcp', dport => '179' },
44 ],
45 'BitTorrent' => [
46 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
47 { action => 'PARAM', proto => 'udp', dport => '6881' },
48 ],
49 'BitTorrent32' => [
50 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
51 { action => 'PARAM', proto => 'udp', dport => '6881' },
52 ],
53 'CVS' => [
54 { action => 'PARAM', proto => 'tcp', dport => '2401' },
55 ],
56 'Citrix' => [
57 { action => 'PARAM', proto => 'tcp', dport => '1494' },
58 { action => 'PARAM', proto => 'udp', dport => '1604' },
59 { action => 'PARAM', proto => 'tcp', dport => '2598' },
60 ],
61 'DAAP' => [
62 { action => 'PARAM', proto => 'tcp', dport => '3689' },
63 { action => 'PARAM', proto => 'udp', dport => '3689' },
64 ],
65 'DCC' => [
66 { action => 'PARAM', proto => 'tcp', dport => '6277' },
67 ],
68 'DHCPfwd' => [
69 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
70 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '67:68', sport => '67:68' },
71 ],
72 'DNS' => [
73 { action => 'PARAM', proto => 'udp', dport => '53' },
74 { action => 'PARAM', proto => 'tcp', dport => '53' },
75 ],
76 'Distcc' => [
77 { action => 'PARAM', proto => 'tcp', dport => '3632' },
78 ],
79 'Edonkey' => [
80 { action => 'PARAM', proto => 'tcp', dport => '4662' },
81 { action => 'PARAM', proto => 'udp', dport => '4665' },
82 ],
83 'FTP' => [
84 { action => 'PARAM', proto => 'tcp', dport => '21' },
85 ],
86 'Finger' => [
87 { action => 'PARAM', proto => 'tcp', dport => '79' },
88 ],
89 'GNUnet' => [
90 { action => 'PARAM', proto => 'tcp', dport => '2086' },
91 { action => 'PARAM', proto => 'udp', dport => '2086' },
92 { action => 'PARAM', proto => 'tcp', dport => '1080' },
93 { action => 'PARAM', proto => 'udp', dport => '1080' },
94 ],
95 'GRE' => [
96 { action => 'PARAM', proto => '47' },
97 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
98 ],
99 'Git' => [
100 { action => 'PARAM', proto => 'tcp', dport => '9418' },
101 ],
102 'Gnutella' => [
103 { action => 'PARAM', proto => 'tcp', dport => '6346' },
104 { action => 'PARAM', proto => 'udp', dport => '6346' },
105 ],
106 'HKP' => [
107 { action => 'PARAM', proto => 'tcp', dport => '11371' },
108 ],
109 'HTTP' => [
110 { action => 'PARAM', proto => 'tcp', dport => '80' },
111 ],
112 'HTTPS' => [
113 { action => 'PARAM', proto => 'tcp', dport => '443' },
114 ],
115 'ICPV2' => [
116 { action => 'PARAM', proto => 'udp', dport => '3130' },
117 ],
118 'ICQ' => [
119 { action => 'PARAM', proto => 'tcp', dport => '5190' },
120 ],
121 'IMAP' => [
122 { action => 'PARAM', proto => 'tcp', dport => '143' },
123 ],
124 'IMAPS' => [
125 { action => 'PARAM', proto => 'tcp', dport => '993' },
126 ],
127 'IPIP' => [
128 { action => 'PARAM', proto => '94' },
129 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '94' },
130 ],
131 'IPP' => [
132 { action => 'PARAM', proto => 'tcp', dport => '631' },
133 ],
134 'IPPbrd' => [
135 { action => 'PARAM', proto => 'udp', dport => '631' },
136 ],
137 'IPPserver' => [
138 { action => 'PARAM', source => 'SOURCE', dest => 'DEST', proto => 'tcp', dport => '631' },
139 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '631' },
140 ],
141 'IPsec' => [
142 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
143 { action => 'PARAM', proto => '50' },
144 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
145 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
146 ],
147 'IPsecah' => [
148 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
149 { action => 'PARAM', proto => '51' },
150 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500', sport => '500' },
151 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '51' },
152 ],
153 'IPsecnat' => [
154 { action => 'PARAM', proto => 'udp', dport => '500' },
155 { action => 'PARAM', proto => 'udp', dport => '4500' },
156 { action => 'PARAM', proto => '50' },
157 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '500' },
158 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '4500' },
159 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '50' },
160 ],
161 'IRC' => [
162 { action => 'PARAM', proto => 'tcp', dport => '6667' },
163 ],
164 'JabberPlain' => [
165 { action => 'PARAM', proto => 'tcp', dport => '5222' },
166 ],
167 'JabberSecure' => [
168 { action => 'PARAM', proto => 'tcp', dport => '5223' },
169 ],
170 'Jabberd' => [
171 { action => 'PARAM', proto => 'tcp', dport => '5269' },
172 ],
173 'Jetdirect' => [
174 { action => 'PARAM', proto => 'tcp', dport => '9100' },
175 ],
176 'L2TP' => [
177 { action => 'PARAM', proto => 'udp', dport => '1701' },
178 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1701' },
179 ],
180 'LDAP' => [
181 { action => 'PARAM', proto => 'tcp', dport => '389' },
182 ],
183 'LDAPS' => [
184 { action => 'PARAM', proto => 'tcp', dport => '636' },
185 ],
186 'MSNP' => [
187 { action => 'PARAM', proto => 'tcp', dport => '1863' },
188 ],
189 'MSSQL' => [
190 { action => 'PARAM', proto => 'tcp', dport => '1433' },
191 ],
192 'Mail' => [
193 { action => 'PARAM', proto => 'tcp', dport => '25' },
194 { action => 'PARAM', proto => 'tcp', dport => '465' },
195 { action => 'PARAM', proto => 'tcp', dport => '587' },
196 ],
197 'Munin' => [
198 { action => 'PARAM', proto => 'tcp', dport => '4949' },
199 ],
200 'MySQL' => [
201 { action => 'PARAM', proto => 'tcp', dport => '3306' },
202 ],
203 'NNTP' => [
204 { action => 'PARAM', proto => 'tcp', dport => '119' },
205 ],
206 'NNTPS' => [
207 { action => 'PARAM', proto => 'tcp', dport => '563' },
208 ],
209 'NTP' => [
210 { action => 'PARAM', proto => 'udp', dport => '123' },
211 ],
212 'NTPbi' => [
213 { action => 'PARAM', proto => 'udp', dport => '123' },
214 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '123' },
215 ],
216 'NTPbrd' => [
217 { action => 'PARAM', proto => 'udp', dport => '123' },
218 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '123' },
219 ],
220 'OSPF' => [
221 { action => 'PARAM', proto => '89' },
222 ],
223 'OpenVPN' => [
224 { action => 'PARAM', proto => 'udp', dport => '1194' },
225 ],
226 'PCA' => [
227 { action => 'PARAM', proto => 'udp', dport => '5632' },
228 { action => 'PARAM', proto => 'tcp', dport => '5631' },
229 ],
230 'POP3' => [
231 { action => 'PARAM', proto => 'tcp', dport => '110' },
232 ],
233 'POP3S' => [
234 { action => 'PARAM', proto => 'tcp', dport => '995' },
235 ],
236 'PPtP' => [
237 { action => 'PARAM', proto => '47' },
238 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => '47' },
239 { action => 'PARAM', proto => 'tcp', dport => '1723' },
240 ],
241 'Ping' => [
242 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
243 ],
244 'PostgreSQL' => [
245 { action => 'PARAM', proto => 'tcp', dport => '5432' },
246 ],
247 'Printer' => [
248 { action => 'PARAM', proto => 'tcp', dport => '515' },
249 ],
250 'RDP' => [
251 { action => 'PARAM', proto => 'tcp', dport => '3389' },
252 ],
253 'RIPbi' => [
254 { action => 'PARAM', proto => 'udp', dport => '520' },
255 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '520' },
256 ],
257 'RNDC' => [
258 { action => 'PARAM', proto => 'tcp', dport => '953' },
259 ],
260 'Razor' => [
261 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
262 ],
263 'Rdate' => [
264 { action => 'PARAM', proto => 'tcp', dport => '37' },
265 ],
266 'Rsync' => [
267 { action => 'PARAM', proto => 'tcp', dport => '873' },
268 ],
269 'SANE' => [
270 { action => 'PARAM', proto => 'tcp', dport => '6566' },
271 ],
272 'SMB' => [
273 { action => 'PARAM', proto => 'udp', dport => '135,445' },
274 { action => 'PARAM', proto => 'udp', dport => '137:139' },
275 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
276 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
277 ],
278 'SMBBI' => [
279 { action => 'PARAM', proto => 'udp', dport => '135,445' },
280 { action => 'PARAM', proto => 'udp', dport => '137:139' },
281 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
282 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
283 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '135,445' },
284 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '137:139' },
285 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'udp', dport => '1024:65535', sport => '137' },
286 { action => 'PARAM', source => 'DEST', dest => 'SOURCE', proto => 'tcp', dport => '135,139,445' },
287 ],
288 'SMBswat' => [
289 { action => 'PARAM', proto => 'tcp', dport => '901' },
290 ],
291 'SMTP' => [
292 { action => 'PARAM', proto => 'tcp', dport => '25' },
293 ],
294 'SMTPS' => [
295 { action => 'PARAM', proto => 'tcp', dport => '465' },
296 ],
297 'SNMP' => [
298 { action => 'PARAM', proto => 'udp', dport => '161:162' },
299 { action => 'PARAM', proto => 'tcp', dport => '161' },
300 ],
301 'SPAMD' => [
302 { action => 'PARAM', proto => 'tcp', dport => '783' },
303 ],
304 'SSH' => [
305 { action => 'PARAM', proto => 'tcp', dport => '22' },
306 ],
307 'SVN' => [
308 { action => 'PARAM', proto => 'tcp', dport => '3690' },
309 ],
310 'SixXS' => [
311 { action => 'PARAM', proto => 'tcp', dport => '3874' },
312 { action => 'PARAM', proto => 'udp', dport => '3740' },
313 { action => 'PARAM', proto => '41' },
314 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
315 ],
316 'Squid' => [
317 { action => 'PARAM', proto => 'tcp', dport => '3128' },
318 ],
319 'Submission' => [
320 { action => 'PARAM', proto => 'tcp', dport => '587' },
321 ],
322 'Syslog' => [
323 { action => 'PARAM', proto => 'udp', dport => '514' },
324 { action => 'PARAM', proto => 'tcp', dport => '514' },
325 ],
326 'TFTP' => [
327 { action => 'PARAM', proto => 'udp', dport => '69' },
328 ],
329 'Telnet' => [
330 { action => 'PARAM', proto => 'tcp', dport => '23' },
331 ],
332 'Telnets' => [
333 { action => 'PARAM', proto => 'tcp', dport => '992' },
334 ],
335 'Time' => [
336 { action => 'PARAM', proto => 'tcp', dport => '37' },
337 ],
338 'Trcrt' => [
339 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
340 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
341 ],
342 'VNC' => [
343 { action => 'PARAM', proto => 'tcp', dport => '5900:5909' },
344 ],
345 'VNCL' => [
346 { action => 'PARAM', proto => 'tcp', dport => '5500' },
347 ],
348 'Web' => [
349 { action => 'PARAM', proto => 'tcp', dport => '80' },
350 { action => 'PARAM', proto => 'tcp', dport => '443' },
351 ],
352 'Webcache' => [
353 { action => 'PARAM', proto => 'tcp', dport => '8080' },
354 ],
355 'Webmin' => [
356 { action => 'PARAM', proto => 'tcp', dport => '10000' },
357 ],
358 'Whois' => [
359 { action => 'PARAM', proto => 'tcp', dport => '43' },
360 ],
361 };
362
363 my $pve_fw_parsed_macros;
364 my $pve_fw_preferred_macro_names = {};
365
366 my $pve_std_chains = {
367 'PVEFW-SET-ACCEPT-MARK' => [
368 "-j MARK --set-mark 1",
369 ],
370 'PVEFW-DropBroadcast' => [
371 # same as shorewall 'Broadcast'
372 # simply DROP BROADCAST/MULTICAST/ANYCAST
373 # we can use this to reduce logging
374 { action => 'DROP', dsttype => 'BROADCAST' },
375 { action => 'DROP', dsttype => 'MULTICAST' },
376 { action => 'DROP', dsttype => 'ANYCAST' },
377 { action => 'DROP', dest => '224.0.0.0/4' },
378 ],
379 'PVEFW-reject' => [
380 # same as shorewall 'reject'
381 { action => 'DROP', dsttype => 'BROADCAST' },
382 { action => 'DROP', source => '224.0.0.0/4' },
383 { action => 'DROP', proto => 'icmp' },
384 "-p tcp -j REJECT --reject-with tcp-reset",
385 "-p udp -j REJECT --reject-with icmp-port-unreachable",
386 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
387 "-j REJECT --reject-with icmp-host-prohibited",
388 ],
389 'PVEFW-Drop' => [
390 # same as shorewall 'Drop', which is equal to DROP,
391 # but REJECT/DROP some packages to reduce logging,
392 # and ACCEPT critical ICMP types
393 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
394 # we are not interested in BROADCAST/MULTICAST/ANYCAST
395 { action => 'PVEFW-DropBroadcast' },
396 # ACCEPT critical ICMP types
397 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
398 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
399 # Drop packets with INVALID state
400 "-m conntrack --ctstate INVALID -j DROP",
401 # Drop Microsoft SMB noise
402 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
403 { action => 'DROP', proto => 'udp', dport => '137:139'},
404 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
405 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
406 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
407 # Drop new/NotSyn traffic so that it doesn't get logged
408 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
409 # Drop DNS replies
410 { action => 'DROP', proto => 'udp', sport => 53 },
411 ],
412 'PVEFW-Reject' => [
413 # same as shorewall 'Reject', which is equal to Reject,
414 # but REJECT/DROP some packages to reduce logging,
415 # and ACCEPT critical ICMP types
416 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
417 # we are not interested in BROADCAST/MULTICAST/ANYCAST
418 { action => 'PVEFW-DropBroadcast' },
419 # ACCEPT critical ICMP types
420 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
421 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
422 # Drop packets with INVALID state
423 "-m conntrack --ctstate INVALID -j DROP",
424 # Drop Microsoft SMB noise
425 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
426 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
427 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
428 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
429 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
430 # Drop new/NotSyn traffic so that it doesn't get logged
431 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
432 # Drop DNS replies
433 { action => 'DROP', proto => 'udp', sport => 53 },
434 ],
435 'PVEFW-tcpflags' => [
436 # same as shorewall tcpflags action.
437 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
438 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
439 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
440 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
441 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
442 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
443 ],
444 'PVEFW-smurfs' => [
445 # same as shorewall smurfs action
446 # Filter packets for smurfs (packets with a broadcast address as the source).
447 "-s 0.0.0.0/32 -j RETURN",
448 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
449 "-s 224.0.0.0/4 -g PVEFW-smurflog",
450 ],
451 };
452
453 # iptables -p icmp -h
454 my $icmp_type_names = {
455 any => 1,
456 'echo-reply' => 1,
457 'destination-unreachable' => 1,
458 'network-unreachable' => 1,
459 'host-unreachable' => 1,
460 'protocol-unreachable' => 1,
461 'port-unreachable' => 1,
462 'fragmentation-needed' => 1,
463 'source-route-failed' => 1,
464 'network-unknown' => 1,
465 'host-unknown' => 1,
466 'network-prohibited' => 1,
467 'host-prohibited' => 1,
468 'TOS-network-unreachable' => 1,
469 'TOS-host-unreachable' => 1,
470 'communication-prohibited' => 1,
471 'host-precedence-violation' => 1,
472 'precedence-cutoff' => 1,
473 'source-quench' => 1,
474 'redirect' => 1,
475 'network-redirect' => 1,
476 'host-redirect' => 1,
477 'TOS-network-redirect' => 1,
478 'TOS-host-redirect' => 1,
479 'echo-request' => 1,
480 'router-advertisement' => 1,
481 'router-solicitation' => 1,
482 'time-exceeded' => 1,
483 'ttl-zero-during-transit' => 1,
484 'ttl-zero-during-reassembly' => 1,
485 'parameter-problem' => 1,
486 'ip-header-bad' => 1,
487 'required-option-missing' => 1,
488 'timestamp-request' => 1,
489 'timestamp-reply' => 1,
490 'address-mask-request' => 1,
491 'address-mask-reply' => 1,
492 };
493
494 sub get_firewall_macros {
495
496 return $pve_fw_parsed_macros if $pve_fw_parsed_macros;
497
498 $pve_fw_parsed_macros = {};
499
500 foreach my $k (keys %$pve_fw_macros) {
501 my $name = lc($k);
502
503 my $macro = $pve_fw_macros->{$k};
504 $pve_fw_preferred_macro_names->{$name} = $k;
505 $pve_fw_parsed_macros->{$name} = $macro;
506 }
507
508 return $pve_fw_parsed_macros;
509 }
510
511 my $etc_services;
512
513 sub get_etc_services {
514
515 return $etc_services if $etc_services;
516
517 my $filename = "/etc/services";
518
519 my $fh = IO::File->new($filename, O_RDONLY);
520 if (!$fh) {
521 warn "unable to read '$filename' - $!\n";
522 return {};
523 }
524
525 my $services = {};
526
527 while (my $line = <$fh>) {
528 chomp ($line);
529 next if $line =~m/^#/;
530 next if ($line =~m/^\s*$/);
531
532 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
533 $services->{byid}->{$2}->{name} = $1;
534 $services->{byid}->{$2}->{port} = $2;
535 $services->{byid}->{$2}->{$3} = 1;
536 $services->{byname}->{$1} = $services->{byid}->{$2};
537 }
538 }
539
540 close($fh);
541
542 $etc_services = $services;
543
544
545 return $etc_services;
546 }
547
548 my $etc_protocols;
549
550 sub get_etc_protocols {
551 return $etc_protocols if $etc_protocols;
552
553 my $filename = "/etc/protocols";
554
555 my $fh = IO::File->new($filename, O_RDONLY);
556 if (!$fh) {
557 warn "unable to read '$filename' - $!\n";
558 return {};
559 }
560
561 my $protocols = {};
562
563 while (my $line = <$fh>) {
564 chomp ($line);
565 next if $line =~m/^#/;
566 next if ($line =~m/^\s*$/);
567
568 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
569 $protocols->{byid}->{$2}->{name} = $1;
570 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
571 }
572 }
573
574 close($fh);
575
576 $etc_protocols = $protocols;
577
578 return $etc_protocols;
579 }
580
581 sub parse_address_list {
582 my ($str) = @_;
583
584 my $nbaor = 0;
585 foreach my $aor (split(/,/, $str)) {
586 if (!Net::IP->new($aor)) {
587 my $err = Net::IP::Error();
588 die "invalid IP address: $err\n";
589 }else{
590 $nbaor++;
591 }
592 }
593 return $nbaor;
594 }
595
596 sub parse_port_name_number_or_range {
597 my ($str) = @_;
598
599 my $services = PVE::Firewall::get_etc_services();
600 my $nbports = 0;
601 foreach my $item (split(/,/, $str)) {
602 my $portlist = "";
603 my $oldpon = undef;
604 $nbports++;
605 foreach my $pon (split(':', $item, 2)) {
606 $pon = $services->{byname}->{$pon}->{port} if $services->{byname}->{$pon}->{port};
607 if ($pon =~ m/^\d+$/){
608 die "invalid port '$pon'\n" if $pon < 0 && $pon > 65535;
609 die "port '$pon' must be bigger than port '$oldpon' \n" if $oldpon && ($pon < $oldpon);
610 $oldpon = $pon;
611 }else{
612 die "invalid port $services->{byname}->{$pon}\n" if !$services->{byname}->{$pon};
613 }
614 }
615 }
616
617 return ($nbports);
618 }
619
620 my $bridge_firewall_enabled = 0;
621
622 sub enable_bridge_firewall {
623
624 return if $bridge_firewall_enabled; # only once
625
626 system("echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables");
627 system("echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables");
628
629 $bridge_firewall_enabled = 1;
630 }
631
632 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
633
634 sub iptables {
635 my ($cmd) = @_;
636
637 run_command("/sbin/iptables $cmd", outfunc => sub {}, errfunc => sub {});
638 }
639
640 sub iptables_restore_cmdlist {
641 my ($cmdlist) = @_;
642
643 run_command("/sbin/iptables-restore -n", input => $cmdlist);
644 }
645
646 sub iptables_get_chains {
647
648 my $res = {};
649
650 # check what chains we want to track
651 my $is_pvefw_chain = sub {
652 my $name = shift;
653
654 return 1 if $name =~ m/^PVEFW-\S+$/;
655
656 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
657 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT)$/;
658 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
659
660 return undef;
661 };
662
663 my $table = '';
664
665 my $parser = sub {
666 my $line = shift;
667
668 return if $line =~ m/^#/;
669 return if $line =~ m/^\s*$/;
670
671 if ($line =~ m/^\*(\S+)$/) {
672 $table = $1;
673 return;
674 }
675
676 return if $table ne 'filter';
677
678 if ($line =~ m/^:(\S+)\s/) {
679 my $chain = $1;
680 return if !&$is_pvefw_chain($chain);
681 $res->{$chain} = "unknown";
682 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
683 my ($chain, $sig) = ($1, $2);
684 return if !&$is_pvefw_chain($chain);
685 $res->{$chain} = $sig;
686 } else {
687 # simply ignore the rest
688 return;
689 }
690 };
691
692 run_command("/sbin/iptables-save", outfunc => $parser);
693
694 return $res;
695 }
696
697 sub iptables_chain_exist {
698 my ($chain) = @_;
699
700 eval{
701 iptables("-n --list $chain");
702 };
703 return undef if $@;
704
705 return 1;
706 }
707
708 sub iptables_rule_exist {
709 my ($rule) = @_;
710
711 eval{
712 iptables("-C $rule");
713 };
714 return undef if $@;
715
716 return 1;
717 }
718
719 sub ruleset_generate_rule {
720 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
721
722 return if $rule->{disable};
723
724 my $cmd = '';
725
726 $cmd .= " -m iprange --src-range" if $rule->{nbsource} && $rule->{nbsource} > 1;
727 $cmd .= " -s $rule->{source}" if $rule->{source};
728 $cmd .= " -m iprange --dst-range" if $rule->{nbdest} && $rule->{nbdest} > 1;
729 $cmd .= " -d $rule->{dest}" if $rule->{dest};
730
731 if ($rule->{proto}) {
732 $cmd .= " -p $rule->{proto}";
733
734 my $multiport = 0;
735 $multiport++ if $rule->{nbdport} && ($rule->{nbdport} > 1);
736 $multiport++ if $rule->{nbsport} && ($rule->{nbsport} > 1);
737
738 $cmd .= " --match multiport" if $multiport;
739
740 die "multiport: option '--sports' cannot be used together with '--dports'\n"
741 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
742
743 if ($rule->{dport}) {
744 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
745 # Note: we use dport to store --icmp-type
746 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport}});
747 $cmd .= " -m icmp --icmp-type $rule->{dport}";
748 } else {
749 if ($rule->{nbdport} && $rule->{nbdport} > 1) {
750 if ($multiport == 2) {
751 $cmd .= " --ports $rule->{dport}";
752 } else {
753 $cmd .= " --dports $rule->{dport}";
754 }
755 } else {
756 $cmd .= " --dport $rule->{dport}";
757 }
758 }
759 }
760
761 if ($rule->{sport}) {
762 if ($rule->{nbsport} && $rule->{nbsport} > 1) {
763 $cmd .= " --sports $rule->{sport}" if $multiport != 2;
764 } else {
765 $cmd .= " --sport $rule->{sport}";
766 }
767 }
768 } elsif ($rule->{dport} || $rule->{sport}) {
769 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport};
770 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport};
771 }
772
773 $cmd .= " -m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
774
775 if (my $action = $rule->{action}) {
776 $action = $actions->{$action} if defined($actions->{$action});
777 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
778 $cmd .= $goto ? " -g $action" : " -j $action";
779 }
780
781 ruleset_addrule($ruleset, $chain, $cmd) if $cmd;
782 }
783
784 sub ruleset_create_chain {
785 my ($ruleset, $chain) = @_;
786
787 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
788
789 die "chain '$chain' already exists\n" if $ruleset->{$chain};
790
791 $ruleset->{$chain} = [];
792 }
793
794 sub ruleset_chain_exist {
795 my ($ruleset, $chain) = @_;
796
797 return $ruleset->{$chain} ? 1 : undef;
798 }
799
800 sub ruleset_addrule {
801 my ($ruleset, $chain, $rule) = @_;
802
803 die "no such chain '$chain'\n" if !$ruleset->{$chain};
804
805 push @{$ruleset->{$chain}}, "-A $chain $rule";
806 }
807
808 sub ruleset_insertrule {
809 my ($ruleset, $chain, $rule) = @_;
810
811 die "no such chain '$chain'\n" if !$ruleset->{$chain};
812
813 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
814 }
815
816 sub generate_bridge_chains {
817 my ($ruleset, $bridge) = @_;
818
819 if (!ruleset_chain_exist($ruleset, "PVEFW-FORWARD")){
820 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
821 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
822 }
823
824 if (!ruleset_chain_exist($ruleset, "$bridge-FW")) {
825 ruleset_create_chain($ruleset, "$bridge-FW");
826 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -m physdev --physdev-is-bridged -j $bridge-FW");
827 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -m physdev --physdev-is-bridged -j $bridge-FW");
828 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o $bridge -j DROP"); # disable interbridge routing
829 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i $bridge -j DROP"); # disable interbridge routing
830 }
831
832 if (!ruleset_chain_exist($ruleset, "$bridge-OUT")) {
833 ruleset_create_chain($ruleset, "$bridge-OUT");
834 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-bridged --physdev-is-in -j $bridge-OUT");
835 }
836
837 if (!ruleset_chain_exist($ruleset, "$bridge-IN")) {
838 ruleset_create_chain($ruleset, "$bridge-IN");
839 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-bridged --physdev-is-out -j $bridge-IN");
840 ruleset_addrule($ruleset, "$bridge-FW", "-m mark --mark 1 -j ACCEPT");
841 # accept traffic to unmanaged bridge ports
842 ruleset_addrule($ruleset, "$bridge-FW", "-m physdev --physdev-is-bridged --physdev-is-out -j ACCEPT ");
843 }
844 }
845
846 sub generate_tap_rules_direction {
847 my ($ruleset, $group_rules, $iface, $netid, $macaddr, $vmfw_conf, $bridge, $direction) = @_;
848
849 my $rules = $vmfw_conf->{lc($direction)};
850 my $options = $vmfw_conf->{options};
851
852 my $tapchain = "$iface-$direction";
853
854 ruleset_create_chain($ruleset, $tapchain);
855
856 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
857 ruleset_addrule($ruleset, $tapchain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
858 }
859
860 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
861 ruleset_addrule($ruleset, $tapchain, "-p udp -m udp --dport 67:68 -j ACCEPT");
862 }
863
864 if ($options->{tcpflags}) {
865 ruleset_addrule($ruleset, $tapchain, "-p tcp -j PVEFW-tcpflags");
866 }
867
868 ruleset_addrule($ruleset, $tapchain, "-m conntrack --ctstate INVALID -j DROP");
869 ruleset_addrule($ruleset, $tapchain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
870
871 if ($direction eq 'OUT' && defined($macaddr) &&
872 !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
873 ruleset_addrule($ruleset, $tapchain, "-m mac ! --mac-source $macaddr -j DROP");
874 }
875
876 if ($rules) {
877 foreach my $rule (@$rules) {
878 next if $rule->{iface} && $rule->{iface} ne $netid;
879 # we go to $bridge-IN if accept in out rules
880 if($rule->{action} =~ m/^(GROUP-(\S+))$/){
881 $rule->{action} .= "-$direction";
882 # generate empty group rule if don't exist
883 if(!ruleset_chain_exist($ruleset, $rule->{action})){
884 generate_group_rules($ruleset, $group_rules, $2);
885 }
886 ruleset_generate_rule($ruleset, $tapchain, $rule);
887 ruleset_addrule($ruleset, $tapchain, "-m mark --mark 1 -j RETURN")
888 if $direction eq 'OUT';
889 } else {
890 if ($direction eq 'OUT') {
891 ruleset_generate_rule($ruleset, $tapchain, $rule,
892 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" });
893 } else {
894 ruleset_generate_rule($ruleset, $tapchain, $rule, { REJECT => "PVEFW-reject" });
895 }
896 }
897 }
898 }
899
900 # implement policy
901 my $policy;
902
903 if ($direction eq 'OUT') {
904 $policy = $options->{'policy-out'} || 'ACCEPT'; # allow everything by default
905 } else {
906 $policy = $options->{'policy-in'} || 'DROP'; # allow everything by default
907 }
908
909 if ($policy eq 'ACCEPT') {
910 if ($direction eq 'OUT') {
911 ruleset_addrule($ruleset, $tapchain, "-g PVEFW-SET-ACCEPT-MARK");
912 } else {
913 ruleset_addrule($ruleset, $tapchain, "-j ACCEPT");
914 }
915 } elsif ($policy eq 'DROP') {
916 ruleset_addrule($ruleset, $tapchain, "-j PVEFW-Drop");
917 ruleset_addrule($ruleset, $tapchain, "-j LOG --log-prefix \"$tapchain-dropped: \" --log-level 4");
918 ruleset_addrule($ruleset, $tapchain, "-j DROP");
919 } elsif ($policy eq 'REJECT') {
920 ruleset_addrule($ruleset, $tapchain, "-j PVEFW-Reject");
921 ruleset_addrule($ruleset, $tapchain, "-j LOG --log-prefix \"$tapchain-reject: \" --log-level 4");
922 ruleset_addrule($ruleset, $tapchain, "-g PVEFW-reject");
923 } else {
924 # should not happen
925 die "internal error: unknown policy '$policy'";
926 }
927
928 # plug the tap chain to bridge chain
929 my $physdevdirection = $direction eq 'IN' ? "out" : "in";
930 my $rule = "-m physdev --physdev-$physdevdirection $iface --physdev-is-bridged -j $tapchain";
931 ruleset_insertrule($ruleset, "$bridge-$direction", $rule);
932
933 if ($direction eq 'OUT'){
934 # add tap->host rules
935 my $rule = "-m physdev --physdev-$physdevdirection $iface -j $tapchain";
936 ruleset_addrule($ruleset, "PVEFW-INPUT", $rule);
937 }
938 }
939
940 sub enablehostfw {
941 my ($ruleset, $rules, $group_rules) = @_;
942
943 # fixme: allow security groups
944
945 # host inbound firewall
946 my $chain = "PVEFW-HOST-IN";
947 ruleset_create_chain($ruleset, $chain);
948
949 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
950 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
951 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
952 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
953 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW -m multiport --dports 5404,5405 -j ACCEPT");
954 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
955
956 if ($rules->{in}) {
957 foreach my $rule (@{$rules->{in}}) {
958 # we use RETURN because we need to check also tap rules
959 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => 'RETURN', REJECT => "PVEFW-reject" });
960 }
961 }
962
963 ruleset_addrule($ruleset, $chain, "-j LOG --log-prefix \"kvmhost-IN dropped: \" --log-level 4");
964 ruleset_addrule($ruleset, $chain, "-j DROP");
965
966 # host outbound firewall
967 $chain = "PVEFW-HOST-OUT";
968 ruleset_create_chain($ruleset, $chain);
969
970 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
971 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT");
972 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
973 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST -j ACCEPT");
974 ruleset_addrule($ruleset, $chain, "-p udp -m conntrack --ctstate NEW -m multiport --dports 5404,5405 -j ACCEPT");
975 ruleset_addrule($ruleset, $chain, "-p udp -m udp --dport 9000 -j ACCEPT"); #corosync
976
977 if ($rules->{out}) {
978 foreach my $rule (@{$rules->{out}}) {
979 # we use RETURN because we need to check also tap rules
980 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => 'RETURN', REJECT => "PVEFW-reject" });
981 }
982 }
983
984 ruleset_addrule($ruleset, $chain, "-j LOG --log-prefix \"kvmhost-OUT dropped: \" --log-level 4");
985 ruleset_addrule($ruleset, $chain, "-j DROP");
986
987 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
988 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
989 }
990
991 sub generate_group_rules {
992 my ($ruleset, $group_rules, $group) = @_;
993
994 my $rules = $group_rules->{$group};
995
996 die "no such security group '$group'\n" if !$rules;
997
998 my $chain = "GROUP-${group}-IN";
999
1000 ruleset_create_chain($ruleset, $chain);
1001
1002 if ($rules->{in}) {
1003 foreach my $rule (@{$rules->{in}}) {
1004 ruleset_generate_rule($ruleset, $chain, $rule, { REJECT => "PVEFW-reject" });
1005 }
1006 }
1007
1008 $chain = "GROUP-${group}-OUT";
1009
1010 ruleset_create_chain($ruleset, $chain);
1011 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
1012
1013 if ($rules->{out}) {
1014 foreach my $rule (@{$rules->{out}}) {
1015 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1016 # check also other tap rules later
1017 ruleset_generate_rule($ruleset, $chain, $rule,
1018 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" });
1019 }
1020 }
1021 }
1022
1023 my $MAX_NETS = 32;
1024 my $valid_netdev_names = {};
1025 for (my $i = 0; $i < $MAX_NETS; $i++) {
1026 $valid_netdev_names->{"net$i"} = 1;
1027 }
1028
1029 sub parse_fw_rule {
1030 my ($line, $need_iface, $allow_groups) = @_;
1031
1032 my $macros = get_firewall_macros();
1033 my $protocols = get_etc_protocols();
1034
1035 my ($action, $iface, $source, $dest, $proto, $dport, $sport);
1036
1037 # we can add single line comments to the end of the rule
1038 my $comment = $1 if $line =~ s/#\s*(.*?)\s*$//;
1039
1040 # we can disable a rule when prefixed with '|'
1041 my $disable = 1 if $line =~ s/^\|//;
1042
1043 my @data = split(/\s+/, $line);
1044 my $expected_elements = $need_iface ? 7 : 6;
1045
1046 die "wrong number of rule elements\n" if scalar(@data) > $expected_elements;
1047
1048 if ($need_iface) {
1049 ($action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1050 } else {
1051 ($action, $source, $dest, $proto, $dport, $sport) = @data;
1052 }
1053
1054 die "incomplete rule\n" if !$action;
1055
1056 my $macro;
1057 my $macro_name;
1058
1059 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1060 # OK
1061 } elsif ($allow_groups && $action =~ m/^GROUP-(:?\S+)$/) {
1062 # OK
1063 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1064 ($macro_name, $action) = ($1, $2);
1065 my $lc_macro_name = lc($macro_name);
1066 my $preferred_name = $pve_fw_preferred_macro_names->{$lc_macro_name};
1067 $macro_name = $preferred_name if $preferred_name;
1068 $macro = $macros->{$lc_macro_name};
1069 die "unknown macro '$macro_name'\n" if !$macro;
1070 } else {
1071 die "unknown action '$action'\n";
1072 }
1073
1074 if ($need_iface) {
1075 $iface = undef if $iface && $iface eq '-';
1076 die "unknown interface '$iface'\n"
1077 if defined($iface) && !$valid_netdev_names->{$iface};
1078 }
1079
1080 $proto = undef if $proto && $proto eq '-';
1081 die "unknown protokol '$proto'\n" if $proto &&
1082 !(defined($protocols->{byname}->{$proto}) ||
1083 defined($protocols->{byid}->{$proto}));
1084
1085 $source = undef if $source && $source eq '-';
1086 $dest = undef if $dest && $dest eq '-';
1087
1088 $dport = undef if $dport && $dport eq '-';
1089 $sport = undef if $sport && $sport eq '-';
1090
1091 my $nbsource = undef;
1092 my $nbdest = undef;
1093
1094 $nbsource = parse_address_list($source) if $source;
1095 $nbdest = parse_address_list($dest) if $dest;
1096
1097 my $rules = [];
1098
1099 my $param = {
1100 disable => $disable,
1101 comment => $comment,
1102 action => $action,
1103 iface => $iface,
1104 source => $source,
1105 dest => $dest,
1106 nbsource => $nbsource,
1107 nbdest => $nbdest,
1108 proto => $proto,
1109 dport => $dport,
1110 sport => $sport,
1111 };
1112
1113 if ($macro) {
1114 foreach my $templ (@$macro) {
1115 my $rule = {};
1116 my $param_used = {};
1117 foreach my $k (keys %$templ) {
1118 my $v = $templ->{$k};
1119 if ($v eq 'PARAM') {
1120 $v = $param->{$k};
1121 $param_used->{$k} = 1;
1122 } elsif ($v eq 'DEST') {
1123 $v = $param->{dest};
1124 $param_used->{dest} = 1;
1125 } elsif ($v eq 'SOURCE') {
1126 $v = $param->{source};
1127 $param_used->{source} = 1;
1128 }
1129
1130 die "missing parameter '$k' in macro '$macro_name'\n" if !defined($v);
1131 $rule->{$k} = $v;
1132 }
1133 foreach my $k (keys %$param) {
1134 next if !defined($param->{$k});
1135 next if $param_used->{$k};
1136 if (defined($rule->{$k})) {
1137 die "parameter '$k' already define in macro (value = '$rule->{$k}')\n"
1138 if $rule->{$k} ne $param->{$k};
1139 } else {
1140 $rule->{$k} = $param->{$k};
1141 }
1142 }
1143 push @$rules, $rule;
1144 }
1145 } else {
1146 push @$rules, $param;
1147 }
1148
1149 foreach my $rule (@$rules) {
1150 $rule->{nbdport} = parse_port_name_number_or_range($rule->{dport})
1151 if defined($rule->{dport});
1152 $rule->{nbsport} = parse_port_name_number_or_range($rule->{sport})
1153 if defined($rule->{sport});
1154 }
1155
1156 return $rules;
1157 }
1158
1159 sub parse_vmfw_option {
1160 my ($line) = @_;
1161
1162 my ($opt, $value);
1163
1164 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
1165 $opt = lc($1);
1166 $value = int($2);
1167 } elsif ($line =~ m/^(policy-(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1168 $opt = lc($1);
1169 $value = uc($3);
1170 } else {
1171 chomp $line;
1172 die "can't parse option '$line'\n"
1173 }
1174
1175 return ($opt, $value);
1176 }
1177
1178 sub parse_hostfw_option {
1179 my ($line) = @_;
1180
1181 my ($opt, $value);
1182
1183 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1184
1185 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
1186 $opt = lc($1);
1187 $value = int($2);
1188 } elsif ($line =~ m/^(tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1189 $opt = lc($1);
1190 $value = $2 ? lc($3) : '';
1191 } elsif ($line =~ m/^(policy-(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1192 $opt = lc($1);
1193 $value = uc($3);
1194 } else {
1195 chomp $line;
1196 die "can't parse option '$line'\n"
1197 }
1198
1199 return ($opt, $value);
1200 }
1201
1202 sub parse_vm_fw_rules {
1203 my ($filename, $fh) = @_;
1204
1205 my $res = { in => [], out => [], options => {}};
1206
1207 my $section;
1208
1209 while (defined(my $line = <$fh>)) {
1210 next if $line =~ m/^#/;
1211 next if $line =~ m/^\s*$/;
1212
1213 my $linenr = $fh->input_line_number();
1214 my $prefix = "$filename (line $linenr)";
1215
1216 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1217 $section = lc($1);
1218 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1219 next;
1220 }
1221 if (!$section) {
1222 warn "$prefix: skip line - no section";
1223 next;
1224 }
1225
1226 next if !$res->{$section}; # skip undefined section
1227
1228 if ($section eq 'options') {
1229 eval {
1230 my ($opt, $value) = parse_vmfw_option($line);
1231 $res->{options}->{$opt} = $value;
1232 };
1233 warn "$prefix: $@" if $@;
1234 next;
1235 }
1236
1237 my $rules;
1238 eval { $rules = parse_fw_rule($line, 1, 1); };
1239 if (my $err = $@) {
1240 warn "$prefix: $err";
1241 next;
1242 }
1243
1244 push @{$res->{$section}}, @$rules;
1245 }
1246
1247 return $res;
1248 }
1249
1250 sub parse_host_fw_rules {
1251 my ($filename, $fh) = @_;
1252
1253 my $res = { in => [], out => [], options => {}};
1254
1255 my $section;
1256
1257 while (defined(my $line = <$fh>)) {
1258 next if $line =~ m/^#/;
1259 next if $line =~ m/^\s*$/;
1260
1261 my $linenr = $fh->input_line_number();
1262 my $prefix = "$filename (line $linenr)";
1263
1264 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1265 $section = lc($1);
1266 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1267 next;
1268 }
1269 if (!$section) {
1270 warn "$prefix: skip line - no section";
1271 next;
1272 }
1273
1274 next if !$res->{$section}; # skip undefined section
1275
1276 if ($section eq 'options') {
1277 eval {
1278 print "PARSE:$line\n";
1279 my ($opt, $value) = parse_hostfw_option($line);
1280 $res->{options}->{$opt} = $value;
1281 };
1282 warn "$prefix: $@" if $@;
1283 next;
1284 }
1285
1286 my $rules;
1287 eval { $rules = parse_fw_rule($line, 1, 1); };
1288 if (my $err = $@) {
1289 warn "$prefix: $err";
1290 next;
1291 }
1292
1293 push @{$res->{$section}}, @$rules;
1294 }
1295
1296 return $res;
1297 }
1298
1299 sub parse_group_fw_rules {
1300 my ($filename, $fh) = @_;
1301
1302 my $section;
1303 my $group;
1304
1305 my $res = { in => [], out => [] };
1306
1307 while (defined(my $line = <$fh>)) {
1308 next if $line =~ m/^#/;
1309 next if $line =~ m/^\s*$/;
1310
1311 my $linenr = $fh->input_line_number();
1312 my $prefix = "$filename (line $linenr)";
1313
1314 if ($line =~ m/^\[(in|out):(\S+)\]\s*$/i) {
1315 $section = lc($1);
1316 $group = lc($2);
1317 next;
1318 }
1319 if (!$section || !$group) {
1320 warn "$prefix: skip line - no section";
1321 next;
1322 }
1323
1324 my $rules;
1325 eval { $rules = parse_fw_rule($line, 0, 0); };
1326 if (my $err = $@) {
1327 warn "$prefix: $err";
1328 next;
1329 }
1330
1331 push @{$res->{$group}->{$section}}, @$rules;
1332 }
1333
1334 return $res;
1335 }
1336
1337 sub run_locked {
1338 my ($code, @param) = @_;
1339
1340 my $timeout = 10;
1341
1342 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
1343
1344 die $@ if $@;
1345
1346 return $res;
1347 }
1348
1349 sub read_local_vm_config {
1350
1351 my $openvz = {};
1352
1353 my $qemu = {};
1354
1355 my $list = PVE::QemuServer::config_list();
1356
1357 foreach my $vmid (keys %$list) {
1358 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
1359 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1360 $qemu->{$vmid} = $conf;
1361 }
1362 }
1363
1364 my $vmdata = { openvz => $openvz, qemu => $qemu };
1365
1366 return $vmdata;
1367 };
1368
1369 sub read_vm_firewall_rules {
1370 my ($vmdata) = @_;
1371 my $rules = {};
1372 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
1373 my $filename = "/etc/pve/firewall/$vmid.fw";
1374 my $fh = IO::File->new($filename, O_RDONLY);
1375 next if !$fh;
1376
1377 $rules->{$vmid} = parse_vm_fw_rules($filename, $fh);
1378 }
1379
1380 return $rules;
1381 }
1382
1383 sub get_option_log_level {
1384 my ($options, $k) = @_;
1385
1386 my $v = $options->{$k};
1387 return $v = $default_log_level if !defined($v);
1388
1389 return undef if $v eq '' || $v eq 'nolog';
1390
1391 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
1392
1393 return $v if ($v >= 0) && ($v <= 7);
1394
1395 warn "unknown log level ($k = '$v')\n";
1396
1397 return undef;
1398 }
1399
1400 sub generate_std_chains {
1401 my ($ruleset, $options) = @_;
1402
1403 my $loglevel = get_option_log_level($options, 'smurf_log_level');
1404
1405 # same as shorewall smurflog.
1406 if (defined($loglevel)) {
1407 $pve_std_chains-> {'PVEFW-smurflog'} = [
1408 "-j LOG --log-prefix \"smurfs-dropped\" --log-level $loglevel",
1409 "-j DROP",
1410 ];
1411 } else {
1412 $pve_std_chains-> {'PVEFW-smurflog'} = [ "-j DROP" ];
1413 }
1414
1415 # same as shorewall logflags action.
1416 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
1417 if (defined($loglevel)) {
1418 $pve_std_chains-> {'PVEFW-logflags'} = [
1419 "-j LOG --log-prefix \"logflags-dropped:\" --log-level $loglevel --log-ip-options",
1420 "-j DROP",
1421 ];
1422 } else {
1423 $pve_std_chains-> {'PVEFW-logflags'} = [ "-j DROP" ];
1424 }
1425
1426 foreach my $chain (keys %$pve_std_chains) {
1427 ruleset_create_chain($ruleset, $chain);
1428 foreach my $rule (@{$pve_std_chains->{$chain}}) {
1429 if (ref($rule)) {
1430 ruleset_generate_rule($ruleset, $chain, $rule);
1431 } else {
1432 ruleset_addrule($ruleset, $chain, $rule);
1433 }
1434 }
1435 }
1436 }
1437
1438 sub save_pvefw_status {
1439 my ($status) = @_;
1440
1441 die "unknown status '$status' - internal error"
1442 if $status !~ m/^(stopped|active)$/;
1443
1444 mkdir dirname($pve_fw_status_filename);
1445 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
1446 }
1447
1448 sub read_pvefw_status {
1449
1450 my $status = 'unknown';
1451
1452 return 'stopped' if ! -f $pve_fw_status_filename;
1453
1454 eval {
1455 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
1456 };
1457 warn $@ if $@;
1458
1459 return $status;
1460 }
1461
1462 sub compile {
1463 my $vmdata = read_local_vm_config();
1464 my $rules = read_vm_firewall_rules($vmdata);
1465
1466 my $group_rules = {};
1467 my $filename = "/etc/pve/firewall/groups.fw";
1468 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1469 $group_rules = parse_group_fw_rules($filename, $fh);
1470 }
1471
1472 #print Dumper($rules);
1473
1474 my $ruleset = {};
1475
1476 ruleset_create_chain($ruleset, "PVEFW-INPUT");
1477 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
1478 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
1479
1480 my $host_options = {};
1481 my $host_rules;
1482
1483 $filename = "/etc/pve/local/host.fw";
1484 if (my $fh = IO::File->new($filename, O_RDONLY)) {
1485 $host_rules = parse_host_fw_rules($filename, $fh);
1486 $host_options = $host_rules->{options};
1487 }
1488
1489 generate_std_chains($ruleset, $host_options);
1490
1491 my $hotsfw_enable = $host_rules && !(defined($host_options->{enable}) && ($host_options->{enable} == 0));
1492
1493 enablehostfw($ruleset, $host_rules, $group_rules) if $hotsfw_enable;
1494
1495 # generate firewall rules for QEMU VMs
1496 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1497 my $conf = $vmdata->{qemu}->{$vmid};
1498 my $vmfw_conf = $rules->{$vmid};
1499 next if !$vmfw_conf;
1500 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
1501
1502 foreach my $netid (keys %$conf) {
1503 next if $netid !~ m/^net(\d+)$/;
1504 my $net = PVE::QemuServer::parse_net($conf->{$netid});
1505 next if !$net;
1506 my $iface = "tap${vmid}i$1";
1507
1508 my $bridge = $net->{bridge};
1509 next if !$bridge; # fixme: ?
1510
1511 $bridge .= "v$net->{tag}" if $net->{tag};
1512
1513
1514 generate_bridge_chains($ruleset, $bridge);
1515
1516 my $macaddr = $net->{macaddr};
1517 generate_tap_rules_direction($ruleset, $group_rules, $iface, $netid, $macaddr, $vmfw_conf, $bridge, 'IN');
1518 generate_tap_rules_direction($ruleset, $group_rules, $iface, $netid, $macaddr, $vmfw_conf, $bridge, 'OUT');
1519 }
1520 }
1521
1522 if ($hotsfw_enable) {
1523 # allow traffic from lo (ourself)
1524 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i lo -j ACCEPT");
1525 }
1526
1527 return $ruleset;
1528 }
1529
1530 sub get_ruleset_status {
1531 my ($ruleset, $verbose) = @_;
1532
1533 my $active_chains = iptables_get_chains();
1534
1535 my $statushash = {};
1536
1537 foreach my $chain (sort keys %$ruleset) {
1538 my $digest = Digest::SHA->new('sha1');
1539 foreach my $cmd (@{$ruleset->{$chain}}) {
1540 $digest->add("$cmd\n");
1541 }
1542 my $sig = $digest->b64digest;
1543 $statushash->{$chain}->{sig} = $sig;
1544
1545 my $oldsig = $active_chains->{$chain};
1546 if (!defined($oldsig)) {
1547 $statushash->{$chain}->{action} = 'create';
1548 } else {
1549 if ($oldsig eq $sig) {
1550 $statushash->{$chain}->{action} = 'exists';
1551 } else {
1552 $statushash->{$chain}->{action} = 'update';
1553 }
1554 }
1555 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
1556 foreach my $cmd (@{$ruleset->{$chain}}) {
1557 print "\t$cmd\n" if $verbose;
1558 }
1559 }
1560
1561 foreach my $chain (sort keys %$active_chains) {
1562 if (!defined($ruleset->{$chain})) {
1563 my $sig = $active_chains->{$chain};
1564 $statushash->{$chain}->{action} = 'delete';
1565 $statushash->{$chain}->{sig} = $sig;
1566 print "delete $chain ($sig)\n" if $verbose;
1567 }
1568 }
1569
1570 return $statushash;
1571 }
1572
1573 sub print_ruleset {
1574 my ($ruleset) = @_;
1575
1576 get_ruleset_status($ruleset, 1);
1577 }
1578
1579 sub print_sig_rule {
1580 my ($chain, $sig) = @_;
1581
1582 # We just use this to store a SHA1 checksum used to detect changes
1583 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
1584 }
1585
1586 sub get_rulset_cmdlist {
1587 my ($ruleset, $verbose) = @_;
1588
1589 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
1590
1591 my $statushash = get_ruleset_status($ruleset, $verbose);
1592
1593 # create missing chains first
1594 foreach my $chain (sort keys %$ruleset) {
1595 my $stat = $statushash->{$chain};
1596 die "internal error" if !$stat;
1597 next if $stat->{action} ne 'create';
1598
1599 $cmdlist .= ":$chain - [0:0]\n";
1600 }
1601
1602 my $rule = "INPUT -j PVEFW-INPUT";
1603 if (!PVE::Firewall::iptables_rule_exist($rule)) {
1604 $cmdlist .= "-A $rule\n";
1605 }
1606 $rule = "OUTPUT -j PVEFW-OUTPUT";
1607 if (!PVE::Firewall::iptables_rule_exist($rule)) {
1608 $cmdlist .= "-A $rule\n";
1609 }
1610
1611 $rule = "FORWARD -j PVEFW-FORWARD";
1612 if (!PVE::Firewall::iptables_rule_exist($rule)) {
1613 $cmdlist .= "-A $rule\n";
1614 }
1615
1616 foreach my $chain (sort keys %$ruleset) {
1617 my $stat = $statushash->{$chain};
1618 die "internal error" if !$stat;
1619
1620 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
1621 $cmdlist .= "-F $chain\n";
1622 foreach my $cmd (@{$ruleset->{$chain}}) {
1623 $cmdlist .= "$cmd\n";
1624 }
1625 $cmdlist .= print_sig_rule($chain, $stat->{sig});
1626 } elsif ($stat->{action} eq 'delete') {
1627 die "internal error"; # this should not happen
1628 } elsif ($stat->{action} eq 'exists') {
1629 # do nothing
1630 } else {
1631 die "internal error - unknown status '$stat->{action}'";
1632 }
1633 }
1634
1635 foreach my $chain (keys %$statushash) {
1636 next if $statushash->{$chain}->{action} ne 'delete';
1637 $cmdlist .= "-F $chain\n";
1638 }
1639 foreach my $chain (keys %$statushash) {
1640 next if $statushash->{$chain}->{action} ne 'delete';
1641 next if $chain eq 'PVEFW-INPUT';
1642 next if $chain eq 'PVEFW-OUTPUT';
1643 next if $chain eq 'PVEFW-FORWARD';
1644 $cmdlist .= "-X $chain\n";
1645 }
1646
1647 $cmdlist .= "COMMIT\n";
1648
1649 return $cmdlist;
1650 }
1651
1652 sub apply_ruleset {
1653 my ($ruleset, $verbose) = @_;
1654
1655 enable_bridge_firewall();
1656
1657 my $cmdlist = get_rulset_cmdlist($ruleset, $verbose);
1658
1659 print $cmdlist if $verbose;
1660
1661 iptables_restore_cmdlist($cmdlist);
1662
1663 # test: re-read status and check if everything is up to date
1664 my $statushash = get_ruleset_status($ruleset);
1665
1666 my $errors;
1667 foreach my $chain (sort keys %$ruleset) {
1668 my $stat = $statushash->{$chain};
1669 if ($stat->{action} ne 'exists') {
1670 warn "unable to update chain '$chain'\n";
1671 $errors = 1;
1672 }
1673 }
1674
1675 die "unable to apply firewall changes\n" if $errors;
1676 }
1677
1678 sub update {
1679 my ($start, $verbose) = @_;
1680
1681 my $code = sub {
1682 my $status = read_pvefw_status();
1683
1684 my $ruleset = PVE::Firewall::compile();
1685
1686 if ($start || $status eq 'active') {
1687
1688 save_pvefw_status('active') if ($status ne 'active');
1689
1690 PVE::Firewall::apply_ruleset($ruleset, $verbose);
1691 } else {
1692 print "Firewall not active (status = $status)\n" if $verbose;
1693 }
1694 };
1695
1696 run_locked($code);
1697 }
1698
1699
1700 1;