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