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