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