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