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