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