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