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