]> git.proxmox.com Git - pve-firewall.git/blame - src/PVE/Firewall.pm
add DHCPv6 macro
[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;
6d959e3f 8use Socket qw(AF_INET6 inet_ntop inet_pton);
c8301d63 9use PVE::INotify;
7ca36671 10use PVE::Exception qw(raise raise_param_exc);
e74a87f5 11use PVE::JSONSchema qw(register_standard_option get_standard_option);
c8301d63 12use PVE::Cluster;
5f0a912c 13use PVE::ProcFSTools;
70e524eb 14use PVE::Tools qw($IPV4RE $IPV6RE);
6b9f68a2 15use File::Basename;
5e1267a5
DM
16use File::Path;
17use IO::File;
ecbea048 18use Net::IP;
1a301a8d 19use PVE::Tools qw(run_command lock_file dir_glob_foreach);
30c1ae52 20use Encode;
ecbea048 21
63c91681 22my $hostfw_conf_filename = "/etc/pve/local/host.fw";
21053409
DM
23my $pvefw_conf_dir = "/etc/pve/firewall";
24my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
fca39c2c 25
fdefeeab 26# dynamically include PVE::QemuServer and PVE::LXC
d9fee004
DM
27# to avoid dependency problems
28my $have_qemu_server;
29eval {
30 require PVE::QemuServer;
31 $have_qemu_server = 1;
32};
33
3b4882dc
AG
34my $have_lxc;
35eval {
36 require PVE::LXC;
37 $have_lxc = 1;
38};
39
40
259db1e6
DM
41my $pve_fw_status_dir = "/var/lib/pve-firewall";
42
43mkdir $pve_fw_status_dir; # make sure this exists
44
351052d1
DM
45my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
46my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
f9792937 47our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
351052d1
DM
48
49my $max_alias_name_length = 64;
50my $max_ipset_name_length = 64;
51my $max_group_name_length = 20;
52
ae029a88
DM
53PVE::JSONSchema::register_format('IPorCIDR', \&pve_verify_ip_or_cidr);
54sub pve_verify_ip_or_cidr {
009ee3ac
DM
55 my ($cidr, $noerr) = @_;
56
70e524eb 57 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
e34d0e58 58 return $cidr if Net::IP->new($cidr);
7c619bbb
DM
59 return undef if $noerr;
60 die Net::IP::Error() . "\n";
61 }
62 return undef if $noerr;
63 die "value does not look like a valid IP address or CIDR network\n";
64}
65
ae029a88
DM
66PVE::JSONSchema::register_format('IPorCIDRorAlias', \&pve_verify_ip_or_cidr_or_alias);
67sub pve_verify_ip_or_cidr_or_alias {
7c619bbb
DM
68 my ($cidr, $noerr) = @_;
69
70 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
71
ae029a88 72 return pve_verify_ip_or_cidr($cidr, $noerr);
009ee3ac
DM
73}
74
e74a87f5
DM
75PVE::JSONSchema::register_standard_option('ipset-name', {
76 description => "IP set name.",
77 type => 'string',
351052d1 78 pattern => $ipset_name_pattern,
387d0ffc 79 minLength => 2,
351052d1 80 maxLength => $max_ipset_name_length,
387d0ffc
DM
81});
82
81d574a7
DM
83PVE::JSONSchema::register_standard_option('pve-fw-alias', {
84 description => "Alias name.",
85 type => 'string',
351052d1 86 pattern => $ip_alias_pattern,
81d574a7 87 minLength => 2,
351052d1 88 maxLength => $max_alias_name_length,
81d574a7
DM
89});
90
6302c41f
DM
91PVE::JSONSchema::register_standard_option('pve-fw-loglevel' => {
92 description => "Log level.",
e34d0e58 93 type => 'string',
6302c41f
DM
94 enum => ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
95 optional => 1,
96});
97
387d0ffc
DM
98PVE::JSONSchema::register_standard_option('pve-security-group-name', {
99 description => "Security Group name.",
100 type => 'string',
44be8ceb 101 pattern => $security_group_name_pattern,
387d0ffc 102 minLength => 2,
351052d1 103 maxLength => $max_group_name_length,
e74a87f5 104});
009ee3ac 105
cbb5d6f3
DM
106my $feature_ipset_nomatch = 0;
107eval {
108 my (undef, undef, $release) = POSIX::uname();
109 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
110 my ($major, $minor) = ($1, $2);
111 $feature_ipset_nomatch = 1 if ($major > 3) ||
112 ($major == 3 && $minor >= 7);
113 }
114
115};
116
c8301d63
DM
117my $nodename = PVE::INotify::nodename();
118
06320eb0
DM
119my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
120
56f313f7 121my $default_log_level = 'nolog'; # avoid logs by default
2d404ffc
DM
122
123my $log_level_hash = {
124 debug => 7,
125 info => 6,
126 notice => 5,
127 warning => 4,
128 err => 3,
129 crit => 2,
130 alert => 1,
131 emerg => 0,
132};
133
35d1d6da
DM
134# we need to overwrite some macros for ipv6
135my $pve_ipv6fw_macros = {
136 'Ping' => [
137 { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
138 ],
b3d75afb
WB
139 'NeighborDiscovery' => [
140 "IPv6 neighbor solicitation, neighbor and router advertisement",
141 { action => 'PARAM', proto => 'icmpv6', dport => 'router-advertisement' },
142 { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-solicitation' },
143 { action => 'PARAM', proto => 'icmpv6', dport => 'neighbor-advertisement' },
144 ],
a42e9763
WB
145 'DHCPv6' => [
146 { action => 'PARAM', proto => 'udp', dport => '546:547', sport => '546:547' },
147 ],
35d1d6da
DM
148 'Trcrt' => [
149 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
150 { action => 'PARAM', proto => 'icmpv6', dport => 'echo-request' },
151 ],
152 };
153
857f62c8 154# imported/converted from: /usr/share/shorewall/macro.*
961b4928 155my $pve_fw_macros = {
857f62c8 156 'Amanda' => [
ebd54ae9 157 "Amanda Backup",
857f62c8
DM
158 { action => 'PARAM', proto => 'udp', dport => '10080' },
159 { action => 'PARAM', proto => 'tcp', dport => '10080' },
160 ],
161 'Auth' => [
ebd54ae9 162 "Auth (identd) traffic",
857f62c8
DM
163 { action => 'PARAM', proto => 'tcp', dport => '113' },
164 ],
165 'BGP' => [
ebd54ae9 166 "Border Gateway Protocol traffic",
857f62c8
DM
167 { action => 'PARAM', proto => 'tcp', dport => '179' },
168 ],
169 'BitTorrent' => [
ebd54ae9 170 "BitTorrent traffic for BitTorrent 3.1 and earlier",
961b4928 171 { action => 'PARAM', proto => 'tcp', dport => '6881:6889' },
857f62c8
DM
172 { action => 'PARAM', proto => 'udp', dport => '6881' },
173 ],
174 'BitTorrent32' => [
ebd54ae9 175 "BitTorrent traffic for BitTorrent 3.2 and later",
857f62c8
DM
176 { action => 'PARAM', proto => 'tcp', dport => '6881:6999' },
177 { action => 'PARAM', proto => 'udp', dport => '6881' },
178 ],
06ba9c44
AG
179 'Ceph' => [
180 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
181 { action => 'PARAM', proto => 'tcp', dport => '6789' },
182 { action => 'PARAM', proto => 'tcp', dport => '6800:7300' },
183 ],
857f62c8 184 'CVS' => [
ebd54ae9 185 "Concurrent Versions System pserver traffic",
857f62c8
DM
186 { action => 'PARAM', proto => 'tcp', dport => '2401' },
187 ],
188 'Citrix' => [
ebd54ae9 189 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
857f62c8
DM
190 { action => 'PARAM', proto => 'tcp', dport => '1494' },
191 { action => 'PARAM', proto => 'udp', dport => '1604' },
192 { action => 'PARAM', proto => 'tcp', dport => '2598' },
193 ],
194 'DAAP' => [
ebd54ae9 195 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
857f62c8
DM
196 { action => 'PARAM', proto => 'tcp', dport => '3689' },
197 { action => 'PARAM', proto => 'udp', dport => '3689' },
198 ],
199 'DCC' => [
ebd54ae9 200 "Distributed Checksum Clearinghouse spam filtering mechanism",
857f62c8
DM
201 { action => 'PARAM', proto => 'tcp', dport => '6277' },
202 ],
203 'DHCPfwd' => [
d2c3266d 204 "Forwarded DHCP traffic",
857f62c8 205 { action => 'PARAM', proto => 'udp', dport => '67:68', sport => '67:68' },
857f62c8
DM
206 ],
207 'DNS' => [
ebd54ae9 208 "Domain Name System traffic (upd and tcp)",
857f62c8
DM
209 { action => 'PARAM', proto => 'udp', dport => '53' },
210 { action => 'PARAM', proto => 'tcp', dport => '53' },
211 ],
212 'Distcc' => [
ebd54ae9 213 "Distributed Compiler service",
857f62c8
DM
214 { action => 'PARAM', proto => 'tcp', dport => '3632' },
215 ],
857f62c8 216 'FTP' => [
ebd54ae9 217 "File Transfer Protocol",
857f62c8
DM
218 { action => 'PARAM', proto => 'tcp', dport => '21' },
219 ],
220 'Finger' => [
ebd54ae9 221 "Finger protocol (RFC 742)",
857f62c8
DM
222 { action => 'PARAM', proto => 'tcp', dport => '79' },
223 ],
224 'GNUnet' => [
ebd54ae9 225 "GNUnet secure peer-to-peer networking traffic",
857f62c8
DM
226 { action => 'PARAM', proto => 'tcp', dport => '2086' },
227 { action => 'PARAM', proto => 'udp', dport => '2086' },
228 { action => 'PARAM', proto => 'tcp', dport => '1080' },
229 { action => 'PARAM', proto => 'udp', dport => '1080' },
230 ],
231 'GRE' => [
d2c3266d 232 "Generic Routing Encapsulation tunneling protocol",
857f62c8 233 { action => 'PARAM', proto => '47' },
857f62c8
DM
234 ],
235 'Git' => [
ebd54ae9 236 "Git distributed revision control traffic",
857f62c8
DM
237 { action => 'PARAM', proto => 'tcp', dport => '9418' },
238 ],
857f62c8 239 'HKP' => [
ebd54ae9 240 "OpenPGP HTTP keyserver protocol traffic",
857f62c8
DM
241 { action => 'PARAM', proto => 'tcp', dport => '11371' },
242 ],
243 'HTTP' => [
ebd54ae9 244 "Hypertext Transfer Protocol (WWW)",
961b4928
DM
245 { action => 'PARAM', proto => 'tcp', dport => '80' },
246 ],
857f62c8 247 'HTTPS' => [
ebd54ae9 248 "Hypertext Transfer Protocol (WWW) over SSL",
857f62c8
DM
249 { action => 'PARAM', proto => 'tcp', dport => '443' },
250 ],
251 'ICPV2' => [
ebd54ae9 252 "Internet Cache Protocol V2 (Squid) traffic",
857f62c8
DM
253 { action => 'PARAM', proto => 'udp', dport => '3130' },
254 ],
255 'ICQ' => [
ebd54ae9 256 "AOL Instant Messenger traffic",
857f62c8
DM
257 { action => 'PARAM', proto => 'tcp', dport => '5190' },
258 ],
259 'IMAP' => [
ebd54ae9 260 "Internet Message Access Protocol",
857f62c8
DM
261 { action => 'PARAM', proto => 'tcp', dport => '143' },
262 ],
263 'IMAPS' => [
ebd54ae9 264 "Internet Message Access Protocol over SSL",
857f62c8
DM
265 { action => 'PARAM', proto => 'tcp', dport => '993' },
266 ],
267 'IPIP' => [
d2c3266d 268 "IPIP capsulation traffic",
857f62c8 269 { action => 'PARAM', proto => '94' },
857f62c8 270 ],
857f62c8 271 'IPsec' => [
d2c3266d 272 "IPsec traffic",
857f62c8
DM
273 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
274 { action => 'PARAM', proto => '50' },
857f62c8
DM
275 ],
276 'IPsecah' => [
d2c3266d 277 "IPsec authentication (AH) traffic",
857f62c8
DM
278 { action => 'PARAM', proto => 'udp', dport => '500', sport => '500' },
279 { action => 'PARAM', proto => '51' },
857f62c8
DM
280 ],
281 'IPsecnat' => [
d2c3266d 282 "IPsec traffic and Nat-Traversal",
857f62c8
DM
283 { action => 'PARAM', proto => 'udp', dport => '500' },
284 { action => 'PARAM', proto => 'udp', dport => '4500' },
285 { action => 'PARAM', proto => '50' },
857f62c8
DM
286 ],
287 'IRC' => [
ebd54ae9 288 "Internet Relay Chat traffic",
857f62c8
DM
289 { action => 'PARAM', proto => 'tcp', dport => '6667' },
290 ],
857f62c8 291 'Jetdirect' => [
ebd54ae9 292 "HP Jetdirect printing",
857f62c8
DM
293 { action => 'PARAM', proto => 'tcp', dport => '9100' },
294 ],
295 'L2TP' => [
ebd54ae9 296 "Layer 2 Tunneling Protocol traffic",
857f62c8 297 { action => 'PARAM', proto => 'udp', dport => '1701' },
857f62c8
DM
298 ],
299 'LDAP' => [
ebd54ae9 300 "Lightweight Directory Access Protocol traffic",
857f62c8
DM
301 { action => 'PARAM', proto => 'tcp', dport => '389' },
302 ],
303 'LDAPS' => [
ebd54ae9 304 "Secure Lightweight Directory Access Protocol traffic",
857f62c8
DM
305 { action => 'PARAM', proto => 'tcp', dport => '636' },
306 ],
307 'MSNP' => [
ebd54ae9 308 "Microsoft Notification Protocol",
857f62c8
DM
309 { action => 'PARAM', proto => 'tcp', dport => '1863' },
310 ],
311 'MSSQL' => [
ebd54ae9 312 "Microsoft SQL Server",
857f62c8
DM
313 { action => 'PARAM', proto => 'tcp', dport => '1433' },
314 ],
315 'Mail' => [
ebd54ae9 316 "Mail traffic (SMTP, SMTPS, Submission)",
857f62c8
DM
317 { action => 'PARAM', proto => 'tcp', dport => '25' },
318 { action => 'PARAM', proto => 'tcp', dport => '465' },
319 { action => 'PARAM', proto => 'tcp', dport => '587' },
320 ],
321 'Munin' => [
ebd54ae9 322 "Munin networked resource monitoring traffic",
857f62c8
DM
323 { action => 'PARAM', proto => 'tcp', dport => '4949' },
324 ],
325 'MySQL' => [
ebd54ae9 326 "MySQL server",
857f62c8
DM
327 { action => 'PARAM', proto => 'tcp', dport => '3306' },
328 ],
329 'NNTP' => [
ebd54ae9 330 "NNTP traffic (Usenet).",
857f62c8
DM
331 { action => 'PARAM', proto => 'tcp', dport => '119' },
332 ],
333 'NNTPS' => [
ebd54ae9 334 "Encrypted NNTP traffic (Usenet)",
857f62c8
DM
335 { action => 'PARAM', proto => 'tcp', dport => '563' },
336 ],
337 'NTP' => [
ebd54ae9 338 "Network Time Protocol (ntpd)",
857f62c8
DM
339 { action => 'PARAM', proto => 'udp', dport => '123' },
340 ],
857f62c8 341 'OSPF' => [
ebd54ae9 342 "OSPF multicast traffic",
857f62c8
DM
343 { action => 'PARAM', proto => '89' },
344 ],
345 'OpenVPN' => [
ebd54ae9 346 "OpenVPN traffic",
857f62c8
DM
347 { action => 'PARAM', proto => 'udp', dport => '1194' },
348 ],
349 'PCA' => [
ebd54ae9 350 "Symantec PCAnywere (tm)",
857f62c8
DM
351 { action => 'PARAM', proto => 'udp', dport => '5632' },
352 { action => 'PARAM', proto => 'tcp', dport => '5631' },
353 ],
354 'POP3' => [
ebd54ae9 355 "POP3 traffic",
857f62c8
DM
356 { action => 'PARAM', proto => 'tcp', dport => '110' },
357 ],
358 'POP3S' => [
ebd54ae9 359 "Encrypted POP3 traffic",
857f62c8
DM
360 { action => 'PARAM', proto => 'tcp', dport => '995' },
361 ],
362 'PPtP' => [
ebd54ae9 363 "Point-to-Point Tunneling Protocol",
857f62c8 364 { action => 'PARAM', proto => '47' },
857f62c8
DM
365 { action => 'PARAM', proto => 'tcp', dport => '1723' },
366 ],
367 'Ping' => [
ebd54ae9 368 "ICMP echo request",
269d4f13 369 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
857f62c8
DM
370 ],
371 'PostgreSQL' => [
ebd54ae9 372 "PostgreSQL server",
857f62c8
DM
373 { action => 'PARAM', proto => 'tcp', dport => '5432' },
374 ],
375 'Printer' => [
ebd54ae9 376 "Line Printer protocol printing",
857f62c8
DM
377 { action => 'PARAM', proto => 'tcp', dport => '515' },
378 ],
379 'RDP' => [
ebd54ae9 380 "Microsoft Remote Desktop Protocol traffic",
857f62c8
DM
381 { action => 'PARAM', proto => 'tcp', dport => '3389' },
382 ],
d2c3266d 383 'RIP' => [
ebd54ae9 384 "Routing Information Protocol (bidirectional)",
857f62c8 385 { action => 'PARAM', proto => 'udp', dport => '520' },
857f62c8
DM
386 ],
387 'RNDC' => [
ebd54ae9 388 "BIND remote management protocol",
857f62c8
DM
389 { action => 'PARAM', proto => 'tcp', dport => '953' },
390 ],
391 'Razor' => [
ebd54ae9 392 "Razor Antispam System",
857f62c8
DM
393 { action => 'ACCEPT', proto => 'tcp', dport => '2703' },
394 ],
395 'Rdate' => [
ebd54ae9 396 "Remote time retrieval (rdate)",
857f62c8
DM
397 { action => 'PARAM', proto => 'tcp', dport => '37' },
398 ],
399 'Rsync' => [
ebd54ae9 400 "Rsync server",
857f62c8
DM
401 { action => 'PARAM', proto => 'tcp', dport => '873' },
402 ],
403 'SANE' => [
ebd54ae9 404 "SANE network scanning",
857f62c8
DM
405 { action => 'PARAM', proto => 'tcp', dport => '6566' },
406 ],
407 'SMB' => [
ebd54ae9 408 "Microsoft SMB traffic",
857f62c8
DM
409 { action => 'PARAM', proto => 'udp', dport => '135,445' },
410 { action => 'PARAM', proto => 'udp', dport => '137:139' },
411 { action => 'PARAM', proto => 'udp', dport => '1024:65535', sport => '137' },
412 { action => 'PARAM', proto => 'tcp', dport => '135,139,445' },
413 ],
857f62c8 414 'SMBswat' => [
ebd54ae9 415 "Samba Web Administration Tool",
857f62c8
DM
416 { action => 'PARAM', proto => 'tcp', dport => '901' },
417 ],
418 'SMTP' => [
ebd54ae9 419 "Simple Mail Transfer Protocol",
857f62c8
DM
420 { action => 'PARAM', proto => 'tcp', dport => '25' },
421 ],
422 'SMTPS' => [
ebd54ae9 423 "Encrypted Simple Mail Transfer Protocol",
857f62c8
DM
424 { action => 'PARAM', proto => 'tcp', dport => '465' },
425 ],
426 'SNMP' => [
ebd54ae9 427 "Simple Network Management Protocol",
857f62c8
DM
428 { action => 'PARAM', proto => 'udp', dport => '161:162' },
429 { action => 'PARAM', proto => 'tcp', dport => '161' },
430 ],
431 'SPAMD' => [
ebd54ae9 432 "Spam Assassin SPAMD traffic",
857f62c8
DM
433 { action => 'PARAM', proto => 'tcp', dport => '783' },
434 ],
435 'SSH' => [
ebd54ae9 436 "Secure shell traffic",
857f62c8
DM
437 { action => 'PARAM', proto => 'tcp', dport => '22' },
438 ],
439 'SVN' => [
ebd54ae9 440 "Subversion server (svnserve)",
857f62c8
DM
441 { action => 'PARAM', proto => 'tcp', dport => '3690' },
442 ],
443 'SixXS' => [
ebd54ae9 444 "SixXS IPv6 Deployment and Tunnel Broker",
857f62c8
DM
445 { action => 'PARAM', proto => 'tcp', dport => '3874' },
446 { action => 'PARAM', proto => 'udp', dport => '3740' },
447 { action => 'PARAM', proto => '41' },
448 { action => 'PARAM', proto => 'udp', dport => '5072,8374' },
449 ],
450 'Squid' => [
ebd54ae9 451 "Squid web proxy traffic",
857f62c8
DM
452 { action => 'PARAM', proto => 'tcp', dport => '3128' },
453 ],
454 'Submission' => [
ebd54ae9 455 "Mail message submission traffic",
857f62c8
DM
456 { action => 'PARAM', proto => 'tcp', dport => '587' },
457 ],
458 'Syslog' => [
ebd54ae9 459 "Syslog protocol (RFC 5424) traffic",
857f62c8
DM
460 { action => 'PARAM', proto => 'udp', dport => '514' },
461 { action => 'PARAM', proto => 'tcp', dport => '514' },
462 ],
463 'TFTP' => [
ebd54ae9 464 "Trivial File Transfer Protocol traffic",
857f62c8
DM
465 { action => 'PARAM', proto => 'udp', dport => '69' },
466 ],
467 'Telnet' => [
ebd54ae9 468 "Telnet traffic",
857f62c8
DM
469 { action => 'PARAM', proto => 'tcp', dport => '23' },
470 ],
471 'Telnets' => [
ebd54ae9 472 "Telnet over SSL",
857f62c8
DM
473 { action => 'PARAM', proto => 'tcp', dport => '992' },
474 ],
475 'Time' => [
ebd54ae9 476 "RFC 868 Time protocol",
857f62c8
DM
477 { action => 'PARAM', proto => 'tcp', dport => '37' },
478 ],
479 'Trcrt' => [
ebd54ae9 480 "Traceroute (for up to 30 hops) traffic",
857f62c8 481 { action => 'PARAM', proto => 'udp', dport => '33434:33524' },
269d4f13 482 { action => 'PARAM', proto => 'icmp', dport => 'echo-request' },
857f62c8
DM
483 ],
484 'VNC' => [
93be4333
DM
485 "VNC traffic for VNC display's 0 - 99",
486 { action => 'PARAM', proto => 'tcp', dport => '5900:5999' },
857f62c8
DM
487 ],
488 'VNCL' => [
ebd54ae9 489 "VNC traffic from Vncservers to Vncviewers in listen mode",
857f62c8
DM
490 { action => 'PARAM', proto => 'tcp', dport => '5500' },
491 ],
492 'Web' => [
ebd54ae9 493 "WWW traffic (HTTP and HTTPS)",
857f62c8 494 { action => 'PARAM', proto => 'tcp', dport => '80' },
961b4928
DM
495 { action => 'PARAM', proto => 'tcp', dport => '443' },
496 ],
857f62c8 497 'Webcache' => [
ebd54ae9 498 "Web Cache/Proxy traffic (port 8080)",
857f62c8
DM
499 { action => 'PARAM', proto => 'tcp', dport => '8080' },
500 ],
501 'Webmin' => [
ebd54ae9 502 "Webmin traffic",
857f62c8
DM
503 { action => 'PARAM', proto => 'tcp', dport => '10000' },
504 ],
505 'Whois' => [
ebd54ae9 506 "Whois (nicname, RFC 3912) traffic",
857f62c8
DM
507 { action => 'PARAM', proto => 'tcp', dport => '43' },
508 ],
961b4928
DM
509};
510
511my $pve_fw_parsed_macros;
ebd54ae9 512my $pve_fw_macro_descr;
21a18e53 513my $pve_fw_macro_ipversion = {};
961b4928 514my $pve_fw_preferred_macro_names = {};
3a616aa0 515
5547adf7
AD
516my $pve_std_chains = {};
517$pve_std_chains->{4} = {
d8f2505e
DM
518 'PVEFW-SET-ACCEPT-MARK' => [
519 "-j MARK --set-mark 1",
520 ],
79929d9c
DM
521 'PVEFW-DropBroadcast' => [
522 # same as shorewall 'Broadcast'
523 # simply DROP BROADCAST/MULTICAST/ANYCAST
524 # we can use this to reduce logging
525 { action => 'DROP', dsttype => 'BROADCAST' },
526 { action => 'DROP', dsttype => 'MULTICAST' },
527 { action => 'DROP', dsttype => 'ANYCAST' },
cbb5d6f3 528 { action => 'DROP', dest => '224.0.0.0/4' },
79929d9c
DM
529 ],
530 'PVEFW-reject' => [
531 # same as shorewall 'reject'
532 { action => 'DROP', dsttype => 'BROADCAST' },
cbb5d6f3 533 { action => 'DROP', source => '224.0.0.0/4' },
79929d9c
DM
534 { action => 'DROP', proto => 'icmp' },
535 "-p tcp -j REJECT --reject-with tcp-reset",
536 "-p udp -j REJECT --reject-with icmp-port-unreachable",
537 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
538 "-j REJECT --reject-with icmp-host-prohibited",
539 ],
540 'PVEFW-Drop' => [
cbb5d6f3 541 # same as shorewall 'Drop', which is equal to DROP,
79929d9c
DM
542 # but REJECT/DROP some packages to reduce logging,
543 # and ACCEPT critical ICMP types
544 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
545 # we are not interested in BROADCAST/MULTICAST/ANYCAST
546 { action => 'PVEFW-DropBroadcast' },
547 # ACCEPT critical ICMP types
548 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
549 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
550 # Drop packets with INVALID state
551 "-m conntrack --ctstate INVALID -j DROP",
552 # Drop Microsoft SMB noise
553 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
554 { action => 'DROP', proto => 'udp', dport => '137:139'},
555 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
556 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
557 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
558 # Drop new/NotSyn traffic so that it doesn't get logged
559 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
560 # Drop DNS replies
561 { action => 'DROP', proto => 'udp', sport => 53 },
562 ],
563 'PVEFW-Reject' => [
cbb5d6f3 564 # same as shorewall 'Reject', which is equal to Reject,
79929d9c
DM
565 # but REJECT/DROP some packages to reduce logging,
566 # and ACCEPT critical ICMP types
567 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
568 # we are not interested in BROADCAST/MULTICAST/ANYCAST
569 { action => 'PVEFW-DropBroadcast' },
570 # ACCEPT critical ICMP types
571 { action => 'ACCEPT', proto => 'icmp', dport => 'fragmentation-needed' },
572 { action => 'ACCEPT', proto => 'icmp', dport => 'time-exceeded' },
573 # Drop packets with INVALID state
574 "-m conntrack --ctstate INVALID -j DROP",
575 # Drop Microsoft SMB noise
576 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
577 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
578 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
579 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
580 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
581 # Drop new/NotSyn traffic so that it doesn't get logged
582 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
583 # Drop DNS replies
584 { action => 'DROP', proto => 'udp', sport => 53 },
585 ],
d86659ef
DM
586 'PVEFW-tcpflags' => [
587 # same as shorewall tcpflags action.
588 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
589 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
590 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
591 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
592 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
593 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
594 ],
bee633ab
DM
595 'PVEFW-smurfs' => [
596 # same as shorewall smurfs action
597 # Filter packets for smurfs (packets with a broadcast address as the source).
32cbd582 598 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
bee633ab
DM
599 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
600 "-s 224.0.0.0/4 -g PVEFW-smurflog",
601 ],
d8f2505e
DM
602};
603
47a79ff2
AD
604$pve_std_chains->{6} = {
605 'PVEFW-SET-ACCEPT-MARK' => [
606 "-j MARK --set-mark 1",
607 ],
608 'PVEFW-DropBroadcast' => [
609 # same as shorewall 'Broadcast'
610 # simply DROP BROADCAST/MULTICAST/ANYCAST
611 # we can use this to reduce logging
612 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
649cd835
DM
613 # ipv6 addrtype does not work with kernel 2.6.32
614 #{ action => 'DROP', dsttype => 'MULTICAST' },
615 #{ action => 'DROP', dsttype => 'ANYCAST' },
616 { action => 'DROP', dest => 'ff00::/8' },
47a79ff2
AD
617 #{ action => 'DROP', dest => '224.0.0.0/4' },
618 ],
619 'PVEFW-reject' => [
620 # same as shorewall 'reject'
621 #{ action => 'DROP', dsttype => 'BROADCAST' },
622 #{ action => 'DROP', source => '224.0.0.0/4' },
649cd835 623 { action => 'DROP', proto => 'icmpv6' },
47a79ff2
AD
624 "-p tcp -j REJECT --reject-with tcp-reset",
625 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
626 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
627 #"-j REJECT --reject-with icmp-host-prohibited",
628 ],
629 'PVEFW-Drop' => [
630 # same as shorewall 'Drop', which is equal to DROP,
631 # but REJECT/DROP some packages to reduce logging,
632 # and ACCEPT critical ICMP types
649cd835 633 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
47a79ff2
AD
634 # we are not interested in BROADCAST/MULTICAST/ANYCAST
635 { action => 'PVEFW-DropBroadcast' },
636 # ACCEPT critical ICMP types
637 { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' },
638 { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' },
639 { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' },
640
641 # Drop packets with INVALID state
642 "-m conntrack --ctstate INVALID -j DROP",
643 # Drop Microsoft SMB noise
649cd835
DM
644 { action => 'DROP', proto => 'udp', dport => '135,445', nbdport => 2 },
645 { action => 'DROP', proto => 'udp', dport => '137:139'},
646 { action => 'DROP', proto => 'udp', dport => '1024:65535', sport => 137 },
647 { action => 'DROP', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
648 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
47a79ff2
AD
649 # Drop new/NotSyn traffic so that it doesn't get logged
650 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
651 # Drop DNS replies
649cd835 652 { action => 'DROP', proto => 'udp', sport => 53 },
47a79ff2
AD
653 ],
654 'PVEFW-Reject' => [
655 # same as shorewall 'Reject', which is equal to Reject,
656 # but REJECT/DROP some packages to reduce logging,
657 # and ACCEPT critical ICMP types
658 { action => 'PVEFW-reject', proto => 'tcp', dport => '43' }, # REJECT 'auth'
659 # we are not interested in BROADCAST/MULTICAST/ANYCAST
660 { action => 'PVEFW-DropBroadcast' },
661 # ACCEPT critical ICMP types
662 { action => 'ACCEPT', proto => 'icmpv6', dport => 'destination-unreachable' },
663 { action => 'ACCEPT', proto => 'icmpv6', dport => 'time-exceeded' },
664 { action => 'ACCEPT', proto => 'icmpv6', dport => 'packet-too-big' },
665
666 # Drop packets with INVALID state
667 "-m conntrack --ctstate INVALID -j DROP",
668 # Drop Microsoft SMB noise
669 { action => 'PVEFW-reject', proto => 'udp', dport => '135,445', nbdport => 2 },
670 { action => 'PVEFW-reject', proto => 'udp', dport => '137:139'},
671 { action => 'PVEFW-reject', proto => 'udp', dport => '1024:65535', sport => 137 },
672 { action => 'PVEFW-reject', proto => 'tcp', dport => '135,139,445', nbdport => 3 },
673 { action => 'DROP', proto => 'udp', dport => 1900 }, # UPnP
674 # Drop new/NotSyn traffic so that it doesn't get logged
675 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
676 # Drop DNS replies
677 { action => 'DROP', proto => 'udp', sport => 53 },
678 ],
679 'PVEFW-tcpflags' => [
680 # same as shorewall tcpflags action.
681 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
682 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
683 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
684 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
685 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
686 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
687 ],
47a79ff2
AD
688};
689
4b586518
DM
690# iptables -p icmp -h
691my $icmp_type_names = {
692 any => 1,
693 'echo-reply' => 1,
694 'destination-unreachable' => 1,
695 'network-unreachable' => 1,
696 'host-unreachable' => 1,
697 'protocol-unreachable' => 1,
698 'port-unreachable' => 1,
699 'fragmentation-needed' => 1,
700 'source-route-failed' => 1,
701 'network-unknown' => 1,
702 'host-unknown' => 1,
703 'network-prohibited' => 1,
704 'host-prohibited' => 1,
705 'TOS-network-unreachable' => 1,
706 'TOS-host-unreachable' => 1,
707 'communication-prohibited' => 1,
708 'host-precedence-violation' => 1,
709 'precedence-cutoff' => 1,
710 'source-quench' => 1,
711 'redirect' => 1,
712 'network-redirect' => 1,
713 'host-redirect' => 1,
714 'TOS-network-redirect' => 1,
715 'TOS-host-redirect' => 1,
716 'echo-request' => 1,
717 'router-advertisement' => 1,
718 'router-solicitation' => 1,
719 'time-exceeded' => 1,
720 'ttl-zero-during-transit' => 1,
721 'ttl-zero-during-reassembly' => 1,
722 'parameter-problem' => 1,
723 'ip-header-bad' => 1,
724 'required-option-missing' => 1,
725 'timestamp-request' => 1,
726 'timestamp-reply' => 1,
727 'address-mask-request' => 1,
728 'address-mask-reply' => 1,
729};
730
041b9277
DM
731# ip6tables -p icmpv6 -h
732
733my $icmpv6_type_names = {
734 'any' => 1,
735 'destination-unreachable' => 1,
736 'no-route' => 1,
737 'communication-prohibited' => 1,
738 'address-unreachable' => 1,
739 'port-unreachable' => 1,
740 'packet-too-big' => 1,
741 'time-exceeded' => 1,
742 'ttl-zero-during-transit' => 1,
743 'ttl-zero-during-reassembly' => 1,
744 'parameter-problem' => 1,
745 'bad-header' => 1,
746 'unknown-header-type' => 1,
747 'unknown-option' => 1,
748 'echo-request' => 1,
749 'echo-reply' => 1,
750 'router-solicitation' => 1,
751 'router-advertisement' => 1,
593604cc 752 'neighbor-solicitation' => 1,
041b9277 753 'neighbour-solicitation' => 1,
593604cc 754 'neighbor-advertisement' => 1,
041b9277
DM
755 'neighbour-advertisement' => 1,
756 'redirect' => 1,
757};
758
54cd19a8 759sub init_firewall_macros {
6158271d 760
961b4928 761 $pve_fw_parsed_macros = {};
9aab3127 762
21a18e53
WB
763 my $parse = sub {
764 my ($k, $macro) = @_;
e5076eee 765 my $lc_name = lc($k);
21a18e53
WB
766 $pve_fw_macro_ipversion->{$k} = 0;
767 while (!ref($macro->[0])) {
768 my $desc = shift @$macro;
769 if ($desc eq 'ipv4only') {
770 $pve_fw_macro_ipversion->{$k} = 4;
771 } elsif ($desc eq 'ipv6only') {
772 $pve_fw_macro_ipversion->{$k} = 6;
773 } else {
774 $pve_fw_macro_descr->{$k} = $desc;
775 }
ebd54ae9 776 }
e5076eee
DM
777 $pve_fw_preferred_macro_names->{$lc_name} = $k;
778 $pve_fw_parsed_macros->{$k} = $macro;
21a18e53
WB
779 };
780
781 foreach my $k (keys %$pve_fw_macros) {
782 &$parse($k, $pve_fw_macros->{$k});
783 }
784
785 foreach my $k (keys %$pve_ipv6fw_macros) {
786 next if $pve_fw_parsed_macros->{$k};
787 &$parse($k, $pve_ipv6fw_macros->{$k});
788 $pve_fw_macro_ipversion->{$k} = 6;
961b4928 789 }
9aab3127
DM
790}
791
54cd19a8
DM
792init_firewall_macros();
793
ebd54ae9
DM
794sub get_macros {
795 return wantarray ? ($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
796}
797
fcba0beb
DM
798my $etc_services;
799
800sub get_etc_services {
801
802 return $etc_services if $etc_services;
803
804 my $filename = "/etc/services";
805
806 my $fh = IO::File->new($filename, O_RDONLY);
807 if (!$fh) {
808 warn "unable to read '$filename' - $!\n";
809 return {};
810 }
811
812 my $services = {};
813
814 while (my $line = <$fh>) {
815 chomp ($line);
816 next if $line =~m/^#/;
817 next if ($line =~m/^\s*$/);
818
819 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
820 $services->{byid}->{$2}->{name} = $1;
35b66e9d 821 $services->{byid}->{$2}->{port} = $2;
fcba0beb
DM
822 $services->{byid}->{$2}->{$3} = 1;
823 $services->{byname}->{$1} = $services->{byid}->{$2};
824 }
825 }
826
827 close($fh);
828
6158271d
DM
829 $etc_services = $services;
830
3a616aa0 831
fcba0beb
DM
832 return $etc_services;
833}
834
835my $etc_protocols;
836
837sub get_etc_protocols {
838 return $etc_protocols if $etc_protocols;
839
840 my $filename = "/etc/protocols";
841
842 my $fh = IO::File->new($filename, O_RDONLY);
843 if (!$fh) {
844 warn "unable to read '$filename' - $!\n";
845 return {};
846 }
847
848 my $protocols = {};
849
850 while (my $line = <$fh>) {
851 chomp ($line);
852 next if $line =~m/^#/;
853 next if ($line =~m/^\s*$/);
854
855 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
856 $protocols->{byid}->{$2}->{name} = $1;
857 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
858 }
859 }
860
861 close($fh);
862
041b9277
DM
863 # add special case for ICMP v6
864 $protocols->{byid}->{icmpv6}->{name} = "icmpv6";
865 $protocols->{byname}->{icmpv6} = $protocols->{byid}->{icmpv6};
866
fcba0beb
DM
867 $etc_protocols = $protocols;
868
869 return $etc_protocols;
870}
871
525778d7 872my $ipv4_mask_hash_localnet = {
93be4333
DM
873 '255.255.0.0' => 16,
874 '255.255.128.0' => 17,
875 '255.255.192.0' => 18,
876 '255.255.224.0' => 19,
877 '255.255.240.0' => 20,
878 '255.255.248.0' => 21,
879 '255.255.252.0' => 22,
880 '255.255.254.0' => 23,
881 '255.255.255.0' => 24,
882 '255.255.255.128' => 25,
883 '255.255.255.192' => 26,
884 '255.255.255.224' => 27,
885 '255.255.255.240' => 28,
886 '255.255.255.248' => 29,
887 '255.255.255.252' => 30,
888};
889
525778d7 890my $__local_network;
93be4333 891
525778d7 892sub local_network {
ac633d30 893 my ($new_value) = @_;
93be4333 894
525778d7 895 $__local_network = $new_value if defined($new_value);
ac633d30 896
525778d7 897 return $__local_network if defined($__local_network);
93be4333
DM
898
899 eval {
900 my $nodename = PVE::INotify::nodename();
901
902 my $ip = PVE::Cluster::remote_node_ip($nodename);
903
904 my $testip = Net::IP->new($ip);
bfc488f6 905
5dc356af
WB
906 my $isv6 = $testip->version == 6;
907 my $routes = $isv6 ? PVE::ProcFSTools::read_proc_net_ipv6_route()
908 : PVE::ProcFSTools::read_proc_net_route();
93be4333 909 foreach my $entry (@$routes) {
5dc356af
WB
910 my $mask;
911 if ($isv6) {
912 $mask = $entry->{prefix};
913 } else {
914 $mask = $ipv4_mask_hash_localnet->{$entry->{mask}};
915 next if !defined($mask);
916 }
93be4333
DM
917 my $cidr = "$entry->{dest}/$mask";
918 my $testnet = Net::IP->new($cidr);
5dc356af 919 if ($testnet->overlaps($testip) == $Net::IP::IP_B_IN_A_OVERLAP) {
525778d7 920 $__local_network = $cidr;
93be4333
DM
921 return;
922 }
923 }
924 };
925 warn $@ if $@;
926
525778d7 927 return $__local_network;
93be4333
DM
928}
929
6d959e3f
DM
930# ipset names are limited to 31 characters,
931# and we use '-v4' or '-v6' to indicate IP versions,
932# and we use '_swap' suffix for atomic update,
933# for example PVEFW-${VMID}-${ipset_name}_swap
30150dca 934
88c26d5e 935my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
708ba714
DM
936
937sub compute_ipset_chain_name {
88c26d5e 938 my ($vmid, $ipset_name, $ipversion) = @_;
708ba714
DM
939
940 $vmid = 0 if !defined($vmid);
941
88c26d5e 942 my $id = "$vmid-${ipset_name}-v$ipversion";
708ba714 943
88c26d5e 944 if (length($id) > $max_iptables_ipset_name_length) {
708ba714
DM
945 $id = PVE::Tools::fnv31a_hex($id);
946 }
947
948 return "PVEFW-$id";
949}
950
b692f42c
DM
951sub compute_ipfilter_ipset_name {
952 my ($iface) = @_;
953
954 return "ipfilter-$iface";
955}
956
ecbea048
DM
957sub parse_address_list {
958 my ($str) = @_;
959
e2c62733
DM
960 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
961 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
962 return;
963 }
964
965 if ($str =~ m/^${ip_alias_pattern}$/) {
966 die "alias name too long\n" if length($str) > $max_alias_name_length;
967 return;
968 }
d72beb8e 969
3162af6b
DM
970 my $count = 0;
971 my $iprange = 0;
a589b6ac 972 my $ipversion;
7697c041 973
3162af6b
DM
974 foreach my $elem (split(/,/, $str)) {
975 $count++;
c344e509
DM
976 my $ip = Net::IP->new($elem);
977 if (!$ip) {
ecbea048
DM
978 my $err = Net::IP::Error();
979 die "invalid IP address: $err\n";
980 }
3162af6b 981 $iprange = 1 if $elem =~ m/-/;
a589b6ac 982
c344e509 983 my $new_ipversion = Net::IP::ip_is_ipv6($ip->ip()) ? 6 : 4;
a589b6ac
DM
984
985 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
006490cb 986 if $ipversion && ($new_ipversion != $ipversion);
a589b6ac
DM
987
988 $ipversion = $new_ipversion;
ecbea048 989 }
e34d0e58 990
5163367b 991 die "you can't use a range in a list\n" if $iprange && $count > 1;
a589b6ac 992
7697c041 993 return $ipversion;
ecbea048 994}
dddd9413 995
fcba0beb
DM
996sub parse_port_name_number_or_range {
997 my ($str) = @_;
998
999 my $services = PVE::Firewall::get_etc_services();
7ca36671 1000 my $count = 0;
041b7e8e
DM
1001 my $icmp_port = 0;
1002
fcba0beb 1003 foreach my $item (split(/,/, $str)) {
7ca36671
DM
1004 $count++;
1005 if ($item =~ m/^(\d+):(\d+)$/) {
1006 my ($port1, $port2) = ($1, $2);
1007 die "invalid port '$port1'\n" if $port1 > 65535;
1008 die "invalid port '$port2'\n" if $port2 > 65535;
1009 } elsif ($item =~ m/^(\d+)$/) {
1010 my $port = $1;
1011 die "invalid port '$port'\n" if $port > 65535;
1012 } else {
041b7e8e
DM
1013 if ($icmp_type_names->{$item}) {
1014 $icmp_port = 1;
041b9277
DM
1015 } elsif ($icmpv6_type_names->{$item}) {
1016 $icmp_port = 1;
041b7e8e 1017 } else {
e34d0e58 1018 die "invalid port '$item'\n" if !$services->{byname}->{$item};
041b7e8e 1019 }
fcba0beb
DM
1020 }
1021 }
1022
041b7e8e
DM
1023 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1024
7ca36671 1025 return $count;
fcba0beb
DM
1026}
1027
54cd19a8
DM
1028PVE::JSONSchema::register_format('pve-fw-port-spec', \&pve_fw_verify_port_spec);
1029sub pve_fw_verify_port_spec {
1030 my ($portstr) = @_;
1031
7ca36671 1032 parse_port_name_number_or_range($portstr);
54cd19a8
DM
1033
1034 return $portstr;
1035}
1036
d31689ee
DM
1037PVE::JSONSchema::register_format('pve-fw-addr-spec', \&pve_fw_verify_addr_spec);
1038sub pve_fw_verify_addr_spec {
54cd19a8
DM
1039 my ($list) = @_;
1040
1041 parse_address_list($list);
1042
1043 return $list;
1044}
1045
1046PVE::JSONSchema::register_format('pve-fw-protocol-spec', \&pve_fw_verify_protocol_spec);
1047sub pve_fw_verify_protocol_spec {
1048 my ($proto) = @_;
1049
1050 my $protocols = get_etc_protocols();
1051
1052 die "unknown protocol '$proto'\n" if $proto &&
1053 !(defined($protocols->{byname}->{$proto}) ||
1054 defined($protocols->{byid}->{$proto}));
1055
1056 return $proto;
1057}
1058
1059
d1c53b3e 1060# helper function for API
d1c53b3e 1061
5d38d64f
DM
1062sub copy_opject_with_digest {
1063 my ($object) = @_;
1064
1065 my $sha = Digest::SHA->new('sha1');
1066
1067 my $res = {};
1068 foreach my $k (sort keys %$object) {
1069 my $v = $object->{$k};
0365eb68 1070 next if !defined($v);
5d38d64f
DM
1071 $res->{$k} = $v;
1072 $sha->add($k, ':', $v, "\n");
1073 }
1074
55e686c7 1075 my $digest = $sha->hexdigest;
5d38d64f
DM
1076
1077 $res->{digest} = $digest;
1078
1079 return wantarray ? ($res, $digest) : $res;
1080}
1081
1082sub copy_list_with_digest {
1083 my ($list) = @_;
1084
1085 my $sha = Digest::SHA->new('sha1');
1086
1087 my $res = [];
1088 foreach my $entry (@$list) {
1089 my $data = {};
1090 foreach my $k (sort keys %$entry) {
1091 my $v = $entry->{$k};
0365eb68 1092 next if !defined($v);
5d38d64f 1093 $data->{$k} = $v;
6d9246e7
DM
1094 # Note: digest ignores refs ($rule->{errors})
1095 $sha->add($k, ':', $v, "\n") if !ref($v); ;
5d38d64f
DM
1096 }
1097 push @$res, $data;
1098 }
1099
55e686c7 1100 my $digest = $sha->hexdigest;
5d38d64f
DM
1101
1102 foreach my $entry (@$res) {
1103 $entry->{digest} = $digest;
1104 }
1105
1106 return wantarray ? ($res, $digest) : $res;
1107}
1108
9c7e0858
DM
1109my $rule_properties = {
1110 pos => {
1111 description => "Update rule at position <pos>.",
1112 type => 'integer',
1113 minimum => 0,
1114 optional => 1,
1115 },
c71e785f 1116 digest => get_standard_option('pve-config-digest'),
9c7e0858
DM
1117 type => {
1118 type => 'string',
1119 optional => 1,
1120 enum => ['in', 'out', 'group'],
1121 },
1122 action => {
c14dacdf 1123 description => "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
9c7e0858
DM
1124 type => 'string',
1125 optional => 1,
44be8ceb 1126 pattern => $security_group_name_pattern,
c14dacdf
DM
1127 maxLength => 20,
1128 minLength => 2,
9c7e0858 1129 },
e5076eee
DM
1130 macro => {
1131 type => 'string',
1132 optional => 1,
54cd19a8 1133 maxLength => 128,
e5076eee 1134 },
54cd19a8 1135 iface => get_standard_option('pve-iface', { optional => 1 }),
9c7e0858 1136 source => {
d31689ee 1137 type => 'string', format => 'pve-fw-addr-spec',
9c7e0858
DM
1138 optional => 1,
1139 },
1140 dest => {
d31689ee 1141 type => 'string', format => 'pve-fw-addr-spec',
9c7e0858
DM
1142 optional => 1,
1143 },
1144 proto => {
54cd19a8 1145 type => 'string', format => 'pve-fw-protocol-spec',
9c7e0858
DM
1146 optional => 1,
1147 },
1148 enable => {
72d055fc
AG
1149 type => 'integer',
1150 minimum => 0,
9c7e0858
DM
1151 optional => 1,
1152 },
1153 sport => {
54cd19a8 1154 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
1155 optional => 1,
1156 },
1157 dport => {
54cd19a8 1158 type => 'string', format => 'pve-fw-port-spec',
9c7e0858
DM
1159 optional => 1,
1160 },
1161 comment => {
1162 type => 'string',
1163 optional => 1,
1164 },
1165};
1166
1167sub add_rule_properties {
1168 my ($properties) = @_;
1169
1170 foreach my $k (keys %$rule_properties) {
3655b01f
DM
1171 my $h = $rule_properties->{$k};
1172 # copy data, so that we can modify later without side effects
1173 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
9c7e0858 1174 }
cbb5d6f3 1175
9c7e0858
DM
1176 return $properties;
1177}
1178
5b7974df
DM
1179sub delete_rule_properties {
1180 my ($rule, $delete_str) = @_;
e34d0e58 1181
5b7974df
DM
1182 foreach my $opt (PVE::Tools::split_list($delete_str)) {
1183 raise_param_exc({ 'delete' => "no such property ('$opt')"})
1184 if !defined($rule_properties->{$opt});
1185 raise_param_exc({ 'delete' => "unable to delete required property '$opt'"})
1186 if $opt eq 'type' || $opt eq 'action';
1187 delete $rule->{$opt};
1188 }
1189
1190 return $rule;
1191}
1192
9a2745a0 1193my $apply_macro = sub {
35d1d6da 1194 my ($macro_name, $param, $verify, $ipversion) = @_;
9a2745a0
DM
1195
1196 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1197 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1198
35d1d6da
DM
1199 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1200 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1201 }
1202
21a18e53 1203 # skip macros which are specific to another ipversion
ff5d050e
AG
1204 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1205 return if $ipversion != $required;
1206 }
21a18e53 1207
9a2745a0
DM
1208 my $rules = [];
1209
1210 foreach my $templ (@$macro_rules) {
1211 my $rule = {};
1212 my $param_used = {};
1213 foreach my $k (keys %$templ) {
1214 my $v = $templ->{$k};
1215 if ($v eq 'PARAM') {
1216 $v = $param->{$k};
1217 $param_used->{$k} = 1;
1218 } elsif ($v eq 'DEST') {
1219 $v = $param->{dest};
1220 $param_used->{dest} = 1;
1221 } elsif ($v eq 'SOURCE') {
1222 $v = $param->{source};
1223 $param_used->{source} = 1;
1224 }
1225
1226 if (!defined($v)) {
1227 my $msg = "missing parameter '$k' in macro '$macro_name'";
e34d0e58 1228 raise_param_exc({ macro => $msg }) if $verify;
9a2745a0
DM
1229 die "$msg\n";
1230 }
1231 $rule->{$k} = $v;
1232 }
1233 foreach my $k (keys %$param) {
1234 next if $k eq 'macro';
1235 next if !defined($param->{$k});
1236 next if $param_used->{$k};
1237 if (defined($rule->{$k})) {
1238 if ($rule->{$k} ne $param->{$k}) {
1239 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
e34d0e58 1240 raise_param_exc({ $k => $msg }) if $verify;
9a2745a0
DM
1241 die "$msg\n";
1242 }
1243 } else {
1244 $rule->{$k} = $param->{$k};
1245 }
1246 }
1247 push @$rules, $rule;
1248 }
1249
1250 return $rules;
1251};
1252
b6b8e6ad
DM
1253my $rule_env_iface_lookup = {
1254 'ct' => 1,
1255 'vm' => 1,
1256 'group' => 0,
1257 'cluster' => 1,
1258 'host' => 1,
1259};
1260
7ca36671 1261sub verify_rule {
a523e057 1262 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
b6b8e6ad
DM
1263
1264 my $allow_groups = $rule_env eq 'group' ? 0 : 1;
bfc488f6 1265
b6b8e6ad
DM
1266 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1267 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
7ca36671 1268
a523e057
DM
1269 my $errors = $rule->{errors} || {};
1270
6d9246e7 1271 my $error_count = 0;
7ca36671 1272
6d9246e7
DM
1273 my $add_error = sub {
1274 my ($param, $msg) = @_;
d4cda423 1275 chomp $msg;
6d9246e7
DM
1276 raise_param_exc({ $param => $msg }) if !$noerr;
1277 $error_count++;
1278 $errors->{$param} = $msg if !$errors->{$param};
1279 };
1280
eea9d2a1
DM
1281 my $ipversion;
1282 my $set_ip_version = sub {
1283 my $vers = shift;
1284 if ($vers) {
1285 die "detected mixed ipv4/ipv6 adresses in rule\n"
1286 if $ipversion && ($vers != $ipversion);
1287 $ipversion = $vers;
1288 }
1289 };
1290
a523e057 1291 my $check_ipset_or_alias_property = sub {
ae029a88 1292 my ($name, $expected_ipversion) = @_;
a523e057
DM
1293
1294 if (my $value = $rule->{$name}) {
1295 if ($value =~ m/^\+/) {
4dfe04e6 1296 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
bfc488f6 1297 &$add_error($name, "no such ipset '$1'")
a523e057 1298 if !($cluster_conf->{ipset}->{$1} || ($fw_conf && $fw_conf->{ipset}->{$1}));
bfc488f6 1299
a523e057 1300 } else {
351052d1 1301 &$add_error($name, "invalid ipset name '$value'");
a523e057
DM
1302 }
1303 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1304 my $alias = lc($value);
bfc488f6 1305 &$add_error($name, "no such alias '$value'")
70e524eb 1306 if !($cluster_conf->{aliases}->{$alias} || ($fw_conf && $fw_conf->{aliases}->{$alias}));
04f5088f 1307 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
70e524eb
AD
1308 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1309
eea9d2a1 1310 &$set_ip_version($e->{ipversion});
a523e057
DM
1311 }
1312 }
1313 };
1314
6d9246e7
DM
1315 my $type = $rule->{type};
1316 my $action = $rule->{action};
bfc488f6 1317
6d9246e7
DM
1318 &$add_error('type', "missing property") if !$type;
1319 &$add_error('action', "missing property") if !$action;
1320
1321 if ($type) {
1322 if ($type eq 'in' || $type eq 'out') {
1323 &$add_error('action', "unknown action '$action'")
1324 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1325 } elsif ($type eq 'group') {
1326 &$add_error('type', "security groups not allowed")
1327 if !$allow_groups;
1328 &$add_error('action', "invalid characters in security group name")
1329 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1330 } else {
1331 &$add_error('type', "unknown rule type '$type'");
1332 }
7ca36671 1333 }
e34d0e58 1334
dba740a9 1335 if ($rule->{iface}) {
bfc488f6 1336 &$add_error('type', "parameter -i not allowed for this rule type")
b6b8e6ad 1337 if !$allow_iface;
dba740a9 1338 eval { PVE::JSONSchema::pve_verify_iface($rule->{iface}); };
6d9246e7 1339 &$add_error('iface', $@) if $@;
fdefeeab 1340 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
b6b8e6ad
DM
1341 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1342 if $rule->{iface} !~ m/^net(\d+)$/;
b6b8e6ad
DM
1343 }
1344 }
7ca36671
DM
1345
1346 if ($rule->{macro}) {
6d9246e7
DM
1347 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1348 $rule->{macro} = $preferred_name;
1349 } else {
1350 &$add_error('macro', "unknown macro '$rule->{macro}'");
1351 }
1352 }
1353
1354 if ($rule->{proto}) {
1355 eval { pve_fw_verify_protocol_spec($rule->{proto}); };
1356 &$add_error('proto', $@) if $@;
041b9277
DM
1357 &$set_ip_version(4) if $rule->{proto} eq 'icmp';
1358 &$set_ip_version(6) if $rule->{proto} eq 'icmpv6';
6d9246e7 1359 }
7ca36671
DM
1360
1361 if ($rule->{dport}) {
1362 eval { parse_port_name_number_or_range($rule->{dport}); };
6d9246e7
DM
1363 &$add_error('dport', $@) if $@;
1364 &$add_error('proto', "missing property - 'dport' requires this property")
914f9a50 1365 if !$rule->{proto};
6d9246e7 1366 }
7ca36671
DM
1367
1368 if ($rule->{sport}) {
1369 eval { parse_port_name_number_or_range($rule->{sport}); };
6d9246e7
DM
1370 &$add_error('sport', $@) if $@;
1371 &$add_error('proto', "missing property - 'sport' requires this property")
914f9a50 1372 if !$rule->{proto};
7ca36671
DM
1373 }
1374
1375 if ($rule->{source}) {
041b9277
DM
1376 eval {
1377 my $source_ipversion = parse_address_list($rule->{source});
1378 &$set_ip_version($source_ipversion);
1379 };
6d9246e7 1380 &$add_error('source', $@) if $@;
ae029a88 1381 &$check_ipset_or_alias_property('source', $ipversion);
7ca36671
DM
1382 }
1383
1384 if ($rule->{dest}) {
9e2205e5
DM
1385 eval {
1386 my $dest_ipversion = parse_address_list($rule->{dest});
041b9277 1387 &$set_ip_version($dest_ipversion);
9e2205e5 1388 };
6d9246e7 1389 &$add_error('dest', $@) if $@;
ae029a88 1390 &$check_ipset_or_alias_property('dest', $ipversion);
7ca36671
DM
1391 }
1392
35d1d6da
DM
1393 $rule->{ipversion} = $ipversion if $ipversion;
1394
a523e057 1395 if ($rule->{macro} && !$error_count) {
35d1d6da 1396 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
6d9246e7
DM
1397 if (my $err = $@) {
1398 if (ref($err) eq "PVE::Exception" && $err->{errors}) {
1399 my $eh = $err->{errors};
1400 foreach my $p (keys %$eh) {
1401 &$add_error($p, $eh->{$p});
1402 }
1403 } else {
1404 &$add_error('macro', "$err");
1405 }
1406 }
9a2745a0
DM
1407 }
1408
6d9246e7
DM
1409 $rule->{errors} = $errors if $error_count;
1410
7ca36671
DM
1411 return $rule;
1412}
1413
9c7e0858
DM
1414sub copy_rule_data {
1415 my ($rule, $param) = @_;
1416
1417 foreach my $k (keys %$rule_properties) {
1418 if (defined(my $v = $param->{$k})) {
1419 if ($v eq '' || $v eq '-') {
1420 delete $rule->{$k};
1421 } else {
1422 $rule->{$k} = $v;
1423 }
9c7e0858
DM
1424 }
1425 }
7ca36671 1426
9c7e0858
DM
1427 return $rule;
1428}
1429
9f6845cf
DM
1430sub rules_modify_permissions {
1431 my ($rule_env) = @_;
1432
1433 if ($rule_env eq 'host') {
1434 return {
1435 check => ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1436 };
1437 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1438 return {
1439 check => ['perm', '/', [ 'Sys.Modify' ]],
1440 };
3b4882dc 1441 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
9f6845cf
DM
1442 return {
1443 check => ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1444 }
1445 }
1446
1447 return undef;
1448}
1449
1450sub rules_audit_permissions {
1451 my ($rule_env) = @_;
1452
1453 if ($rule_env eq 'host') {
1454 return {
1455 check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1456 };
1457 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1458 return {
1459 check => ['perm', '/', [ 'Sys.Audit' ]],
1460 };
3b4882dc 1461 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
9f6845cf
DM
1462 return {
1463 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1464 }
1465 }
1466
1467 return undef;
1468}
1469
9c7e0858 1470# core functions
780bcc0f
DM
1471my $bridge_firewall_enabled = 0;
1472
1473sub enable_bridge_firewall {
1474
1475 return if $bridge_firewall_enabled; # only once
1476
5f0a912c
DM
1477 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1478 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
780bcc0f 1479
6a8a75db
DM
1480 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1481 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/ipv4/tcp_syncookies", "1");
1482
780bcc0f
DM
1483 $bridge_firewall_enabled = 1;
1484}
1485
8cebfa6f 1486my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413 1487
b16e818e
DM
1488sub iptables_restore_cmdlist {
1489 my ($cmdlist) = @_;
3a616aa0 1490
59f9b456 1491 run_command("/sbin/iptables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
3a616aa0
AD
1492}
1493
17da5c0f
AD
1494sub ip6tables_restore_cmdlist {
1495 my ($cmdlist) = @_;
1496
59f9b456 1497 run_command("/sbin/ip6tables-restore -n", input => $cmdlist, errmsg => "iptables_restore_cmdlist");
17da5c0f
AD
1498}
1499
34cdedfa
AD
1500sub ipset_restore_cmdlist {
1501 my ($cmdlist) = @_;
1502
ff5363da 1503 run_command("/sbin/ipset restore", input => $cmdlist, errmsg => "ipset_restore_cmdlist");
34cdedfa
AD
1504}
1505
de2a57cd 1506sub iptables_get_chains {
17da5c0f
AD
1507 my ($iptablescmd) = @_;
1508
1509 $iptablescmd = "iptables" if !$iptablescmd;
de2a57cd
DM
1510
1511 my $res = {};
1512
1513 # check what chains we want to track
1514 my $is_pvefw_chain = sub {
1515 my $name = shift;
1516
dec84fcd
DM
1517 return 1 if $name =~ m/^PVEFW-\S+$/;
1518
a3ded5cd 1519 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
954f24b1 1520
a3ded5cd 1521 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
954f24b1 1522
a3ded5cd 1523 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
a89dfcc6 1524 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
de2a57cd
DM
1525
1526 return undef;
1527 };
1528
1529 my $table = '';
1530
c4a2e5ae
DM
1531 my $hooks = {};
1532
de2a57cd
DM
1533 my $parser = sub {
1534 my $line = shift;
1535
1536 return if $line =~ m/^#/;
1537 return if $line =~ m/^\s*$/;
1538
1539 if ($line =~ m/^\*(\S+)$/) {
1540 $table = $1;
1541 return;
1542 }
1543
1544 return if $table ne 'filter';
1545
1546 if ($line =~ m/^:(\S+)\s/) {
1547 my $chain = $1;
1548 return if !&$is_pvefw_chain($chain);
3fa83edf 1549 $res->{$chain} = "unknown";
09d5f68e 1550 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
3fa83edf 1551 my ($chain, $sig) = ($1, $2);
de2a57cd 1552 return if !&$is_pvefw_chain($chain);
3fa83edf 1553 $res->{$chain} = $sig;
c4a2e5ae
DM
1554 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1555 $hooks->{$1} = 1;
de2a57cd
DM
1556 } else {
1557 # simply ignore the rest
1558 return;
1559 }
1560 };
1561
17da5c0f 1562 run_command("/sbin/$iptablescmd-save", outfunc => $parser);
de2a57cd 1563
c4a2e5ae 1564 return wantarray ? ($res, $hooks) : $res;
de2a57cd
DM
1565}
1566
9bf7d929
DM
1567sub iptables_chain_digest {
1568 my ($rules) = @_;
1569 my $digest = Digest::SHA->new('sha1');
1570 foreach my $rule (@$rules) { # order is important
1571 $digest->add($rule);
1572 }
1573 return $digest->b64digest;
1574}
1575
3f95d14a
DM
1576sub ipset_chain_digest {
1577 my ($rules) = @_;
4bd0a9c4 1578
3f95d14a
DM
1579 my $digest = Digest::SHA->new('sha1');
1580 foreach my $rule (sort @$rules) { # note: sorted
1581 $digest->add($rule);
1582 }
1583 return $digest->b64digest;
1584}
1585
34cdedfa
AD
1586sub ipset_get_chains {
1587
1588 my $res = {};
1589 my $chains = {};
1590
1591 my $parser = sub {
1592 my $line = shift;
1593
1594 return if $line =~ m/^#/;
1595 return if $line =~ m/^\s*$/;
4b96e877 1596 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
81a0bf43
DM
1597 my $chain = $1;
1598 $line =~ s/\s+$//; # delete trailing white space
1599 push @{$chains->{$chain}}, $line;
34cdedfa
AD
1600 } else {
1601 # simply ignore the rest
1602 return;
1603 }
1604 };
1605
ff5363da 1606 run_command("/sbin/ipset save", outfunc => $parser);
34cdedfa 1607
3f95d14a
DM
1608 # compute digest for each chain
1609 foreach my $chain (keys %$chains) {
1610 $res->{$chain} = ipset_chain_digest($chains->{$chain});
34cdedfa
AD
1611 }
1612
1613 return $res;
1614}
1615
eba0fb64 1616sub ruleset_generate_cmdstr {
88c26d5e 1617 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
3a616aa0 1618
00bb4391 1619 return if defined($rule->{enable}) && !$rule->{enable};
6d9246e7 1620 return if $rule->{errors};
11bac5c2 1621
e5076eee
DM
1622 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1623
1624 my $nbdport = defined($rule->{dport}) ? parse_port_name_number_or_range($rule->{dport}) : 0;
1625 my $nbsport = defined($rule->{sport}) ? parse_port_name_number_or_range($rule->{sport}) : 0;
e5076eee 1626
41524a58 1627 my @cmd = ();
3a616aa0 1628
eba0fb64
DM
1629 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in};
1630 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out};
1631
ba791b1f
AD
1632 my $source = $rule->{source};
1633 my $dest = $rule->{dest};
1634
cbb5d6f3 1635 if ($source) {
44be8ceb 1636 if ($source =~ m/^\+/) {
4dfe04e6 1637 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1638 my $name = $1;
1639 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
88c26d5e 1640 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
708ba714 1641 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb 1642 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
88c26d5e 1643 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
708ba714 1644 push @cmd, "-m set --match-set ${ipset_chain} src";
e523d2bb
DM
1645 } else {
1646 die "no such ipset '$name'\n";
1647 }
44be8ceb
DM
1648 } else {
1649 die "invalid security group name '$source'\n";
1650 }
1651 } elsif ($source =~ m/^${ip_alias_pattern}$/){
81d574a7 1652 my $alias = lc($source);
04f5088f 1653 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
e523d2bb
DM
1654 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1655 die "no such alias '$source'\n" if !$e;
81d574a7 1656 push @cmd, "-s $e->{cidr}";
ac8242cc 1657 } elsif ($source =~ m/\-/){
ba791b1f 1658 push @cmd, "-m iprange --src-range $source";
cbb5d6f3 1659 } else {
ba791b1f
AD
1660 push @cmd, "-s $source";
1661 }
1662 }
1663
cbb5d6f3 1664 if ($dest) {
44be8ceb 1665 if ($dest =~ m/^\+/) {
4dfe04e6 1666 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
e523d2bb
DM
1667 my $name = $1;
1668 if ($fw_conf && $fw_conf->{ipset}->{$name}) {
88c26d5e 1669 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $name, $ipversion);
ac4580a0 1670 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb 1671 } elsif ($cluster_conf && $cluster_conf->{ipset}->{$name}) {
88c26d5e 1672 my $ipset_chain = compute_ipset_chain_name(0, $name, $ipversion);
708ba714 1673 push @cmd, "-m set --match-set ${ipset_chain} dst";
e523d2bb
DM
1674 } else {
1675 die "no such ipset '$name'\n";
1676 }
44be8ceb
DM
1677 } else {
1678 die "invalid security group name '$dest'\n";
1679 }
1680 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
51b40846 1681 my $alias = lc($dest);
04f5088f 1682 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
e523d2bb
DM
1683 $e = $cluster_conf->{aliases}->{$alias} if !$e && $cluster_conf;
1684 die "no such alias '$dest'\n" if !$e;
81d574a7 1685 push @cmd, "-d $e->{cidr}";
cbb5d6f3 1686 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
ba791b1f 1687 push @cmd, "-m iprange --dst-range $dest";
cbb5d6f3 1688 } else {
d6d2a385 1689 push @cmd, "-d $dest";
ba791b1f
AD
1690 }
1691 }
4b586518 1692
181390b0 1693 if ($rule->{proto}) {
41524a58 1694 push @cmd, "-p $rule->{proto}";
e3a1d391 1695
181390b0 1696 my $multiport = 0;
e5076eee
DM
1697 $multiport++ if $nbdport > 1;
1698 $multiport++ if $nbsport > 1;
e3a1d391 1699
41524a58 1700 push @cmd, "--match multiport" if $multiport;
4b586518 1701
cbb5d6f3 1702 die "multiport: option '--sports' cannot be used together with '--dports'\n"
181390b0
DM
1703 if ($multiport == 2) && ($rule->{dport} ne $rule->{sport});
1704
1705 if ($rule->{dport}) {
1706 if ($rule->{proto} && $rule->{proto} eq 'icmp') {
1707 # Note: we use dport to store --icmp-type
9bd7a4b3
WB
1708 die "unknown icmp-type '$rule->{dport}'\n"
1709 if $rule->{dport} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport}});
41524a58 1710 push @cmd, "-m icmp --icmp-type $rule->{dport}";
041b9277
DM
1711 } elsif ($rule->{proto} && $rule->{proto} eq 'icmpv6') {
1712 # Note: we use dport to store --icmpv6-type
9bd7a4b3
WB
1713 die "unknown icmpv6-type '$rule->{dport}'\n"
1714 if $rule->{dport} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport}});
041b9277 1715 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
181390b0 1716 } else {
e5076eee 1717 if ($nbdport > 1) {
181390b0 1718 if ($multiport == 2) {
41524a58 1719 push @cmd, "--ports $rule->{dport}";
181390b0 1720 } else {
41524a58 1721 push @cmd, "--dports $rule->{dport}";
181390b0 1722 }
e3a1d391 1723 } else {
41524a58 1724 push @cmd, "--dport $rule->{dport}";
e3a1d391 1725 }
4b586518
DM
1726 }
1727 }
4b586518 1728
181390b0 1729 if ($rule->{sport}) {
e5076eee 1730 if ($nbsport > 1) {
41524a58 1731 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
181390b0 1732 } else {
41524a58 1733 push @cmd, "--sport $rule->{sport}";
181390b0 1734 }
4b586518 1735 }
181390b0 1736 } elsif ($rule->{dport} || $rule->{sport}) {
93d96f83
DM
1737 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport};
1738 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport};
4b586518
DM
1739 }
1740
41524a58 1741 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype};
4e6112f9
DM
1742
1743 if (my $action = $rule->{action}) {
cbb5d6f3 1744 $action = $actions->{$action} if defined($actions->{$action});
4e6112f9 1745 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
41524a58 1746 push @cmd, $goto ? "-g $action" : "-j $action";
181390b0 1747 }
3a616aa0 1748
eba0fb64
DM
1749 return scalar(@cmd) ? join(' ', @cmd) : undef;
1750}
1751
1752sub ruleset_generate_rule {
88c26d5e 1753 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
eba0fb64 1754
e5076eee
DM
1755 my $rules;
1756
1757 if ($rule->{macro}) {
35d1d6da 1758 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
e5076eee
DM
1759 } else {
1760 $rules = [ $rule ];
1761 }
1762
d4091b82
DM
1763 # update all or nothing
1764
1765 my @cmds = ();
cbb5d6f3 1766 foreach my $tmp (@$rules) {
88c26d5e 1767 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
d4091b82 1768 push @cmds, $cmdstr;
e5076eee 1769 }
41524a58 1770 }
d4091b82
DM
1771
1772 foreach my $cmdstr (@cmds) {
1773 ruleset_addrule($ruleset, $chain, $cmdstr);
1774 }
3fa83edf 1775}
0f168d7b 1776
eba0fb64 1777sub ruleset_generate_rule_insert {
88c26d5e 1778 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
eba0fb64 1779
e5076eee
DM
1780 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1781
88c26d5e 1782 if (my $cmdstr = ruleset_generate_cmdstr($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
eba0fb64
DM
1783 ruleset_insertrule($ruleset, $chain, $cmdstr);
1784 }
1785}
3fa83edf
DM
1786
1787sub ruleset_create_chain {
1788 my ($ruleset, $chain) = @_;
3a616aa0 1789
d050c724 1790 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
782c4cde 1791 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
d050c724 1792
3fa83edf
DM
1793 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1794
1795 $ruleset->{$chain} = [];
3a616aa0
AD
1796}
1797
3fa83edf
DM
1798sub ruleset_chain_exist {
1799 my ($ruleset, $chain) = @_;
3a616aa0 1800
3fa83edf
DM
1801 return $ruleset->{$chain} ? 1 : undef;
1802}
3a616aa0 1803
3fa83edf
DM
1804sub ruleset_addrule {
1805 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1806
3fa83edf 1807 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1808
3fa83edf
DM
1809 push @{$ruleset->{$chain}}, "-A $chain $rule";
1810}
3a616aa0 1811
3fa83edf
DM
1812sub ruleset_insertrule {
1813 my ($ruleset, $chain, $rule) = @_;
3a616aa0 1814
3fa83edf 1815 die "no such chain '$chain'\n" if !$ruleset->{$chain};
3a616aa0 1816
3fa83edf
DM
1817 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1818}
3a616aa0 1819
782c4cde
DM
1820sub get_log_rule_base {
1821 my ($chain, $vmid, $msg, $loglevel) = @_;
cbb5d6f3 1822
782c4cde
DM
1823 die "internal error - no log level" if !defined($loglevel);
1824
1825 $vmid = 0 if !defined($vmid);
1826
cbb5d6f3 1827 # Note: we use special format for prefix to pass further
782c4cde
DM
1828 # info to log daemon (VMID, LOGVELEL and CHAIN)
1829
1830 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1831}
1832
1833sub ruleset_addlog {
1834 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1835
1836 return if !defined($loglevel);
1837
1838 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1839
1840 $logrule = "$rule $logrule" if defined($rule);
1841
88733a74 1842 ruleset_addrule($ruleset, $chain, $logrule);
782c4cde
DM
1843}
1844
ead850e8 1845sub ruleset_add_chain_policy {
88c26d5e 1846 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
ead850e8
DM
1847
1848 if ($policy eq 'ACCEPT') {
1849
88c26d5e 1850 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
ead850e8
DM
1851 { ACCEPT => $accept_action});
1852
1853 } elsif ($policy eq 'DROP') {
1854
1855 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop");
1856
782c4cde 1857 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1858
1859 ruleset_addrule($ruleset, $chain, "-j DROP");
1860 } elsif ($policy eq 'REJECT') {
1861 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject");
1862
782c4cde 1863 ruleset_addlog($ruleset, $chain, $vmid, "policy $policy: ", $loglevel);
ead850e8
DM
1864
1865 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject");
1866 } else {
1867 # should not happen
1868 die "internal error: unknown policy '$policy'";
1869 }
1870}
1871
e2943485
DM
1872sub ruleset_chain_add_conn_filters {
1873 my ($ruleset, $chain, $accept) = @_;
1874
1875 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID -j DROP");
1876 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
1877}
1878
1879sub ruleset_chain_add_input_filters {
88c26d5e 1880 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2428e394
AD
1881
1882 if ($cluster_conf->{ipset}->{blacklist}){
b5831a0d
AD
1883 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist")) {
1884 ruleset_create_chain($ruleset, "PVEFW-blacklist");
1885 ruleset_addlog($ruleset, "PVEFW-blacklist", 0, "DROP: ", $loglevel) if $loglevel;
1886 ruleset_addrule($ruleset, "PVEFW-blacklist", "-j DROP");
1887 }
88c26d5e 1888 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
708ba714 1889 ruleset_addrule($ruleset, $chain, "-m set --match-set ${ipset_chain} src -j PVEFW-blacklist");
2428e394 1890 }
e2943485
DM
1891
1892 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
5b5c42b1
DM
1893 if ($ipversion == 4) {
1894 ruleset_addrule($ruleset, $chain, "-m conntrack --ctstate INVALID,NEW -j PVEFW-smurfs");
1895 }
e2943485
DM
1896 }
1897
1898 if ($options->{tcpflags}) {
1899 ruleset_addrule($ruleset, $chain, "-p tcp -j PVEFW-tcpflags");
1900 }
1901}
1902
9e15114a 1903sub ruleset_create_vm_chain {
88c26d5e 1904 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
3a616aa0 1905
9e15114a 1906 ruleset_create_chain($ruleset, $chain);
b47ecc88 1907 my $accept = generate_nfqueue($options);
3a616aa0 1908
ce15d90b 1909 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
dcafc5fb
WB
1910 if ($ipversion == 4) {
1911 if ($direction eq 'OUT') {
1912 ruleset_generate_rule($ruleset, $chain, $ipversion,
1913 { action => 'PVEFW-SET-ACCEPT-MARK',
1914 proto => 'udp', sport => 68, dport => 67 });
1915 } else {
1916 ruleset_generate_rule($ruleset, $chain, $ipversion,
1917 { action => 'ACCEPT',
1918 proto => 'udp', sport => 67, dport => 68 });
1919 }
1920 } elsif ($ipversion == 6) {
1921 if ($direction eq 'OUT') {
1922 ruleset_generate_rule($ruleset, $chain, $ipversion,
1923 { action => 'PVEFW-SET-ACCEPT-MARK',
1924 proto => 'udp', sport => 546, dport => 547 });
1925 } else {
1926 ruleset_generate_rule($ruleset, $chain, $ipversion,
1927 { action => 'ACCEPT',
1928 proto => 'udp', sport => 547, dport => 546 });
1929 }
76a2d1e7 1930 }
dcafc5fb 1931
ce15d90b
DM
1932 }
1933
b21aca2c
DM
1934 if ($direction eq 'OUT') {
1935 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
9e15114a 1936 ruleset_addrule($ruleset, $chain, "-m mac ! --mac-source $macaddr -j DROP");
b21aca2c 1937 }
808d711d
DM
1938 if ($ipfilter_ipset) {
1939 ruleset_addrule($ruleset, $chain, "-m set ! --match-set $ipfilter_ipset src -j DROP");
1940 }
9e15114a 1941 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
c29f55c9 1942 }
9e15114a
DM
1943}
1944
4bc6b5ac 1945sub ruleset_add_group_rule {
aedde2c2 1946 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
4bc6b5ac
DM
1947
1948 my $group = $rule->{action};
1949 my $group_chain = "GROUP-$group-$direction";
1950 if(!ruleset_chain_exist($ruleset, $group_chain)){
aedde2c2 1951 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
4bc6b5ac 1952 }
bfc488f6 1953
f8b12fff
DM
1954 if ($direction eq 'OUT' && $rule->{iface_out}) {
1955 ruleset_addrule($ruleset, $chain, "-o $rule->{iface_out} -j $group_chain");
1956 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1957 ruleset_addrule($ruleset, $chain, "-i $rule->{iface_in} -j $group_chain");
4bc6b5ac
DM
1958 } else {
1959 ruleset_addrule($ruleset, $chain, "-j $group_chain");
1960 }
1961
1962 ruleset_addrule($ruleset, $chain, "-m mark --mark 1 -j $action");
1963}
1964
9e15114a 1965sub ruleset_generate_vm_rules {
84870b1a 1966 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
9e15114a
DM
1967
1968 my $lc_direction = lc($direction);
c29f55c9 1969
6b8ca015
DM
1970 my $in_accept = generate_nfqueue($options);
1971
92e976b3
DM
1972 foreach my $rule (@$rules) {
1973 next if $rule->{iface} && $rule->{iface} ne $netid;
b7ab6989 1974 next if !$rule->{enable} || $rule->{errors};
006490cb 1975 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
84870b1a 1976
92e976b3 1977 if ($rule->{type} eq 'group') {
4bc6b5ac 1978 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
aedde2c2 1979 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
92e976b3
DM
1980 } else {
1981 next if $rule->{type} ne $lc_direction;
921dfb33
DM
1982 eval {
1983 if ($direction eq 'OUT') {
88c26d5e 1984 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
e34d0e58 1985 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
e523d2bb 1986 undef, $cluster_conf, $vmfw_conf);
921dfb33 1987 } else {
88c26d5e 1988 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
e34d0e58 1989 { ACCEPT => $in_accept , REJECT => "PVEFW-reject" },
e523d2bb 1990 undef, $cluster_conf, $vmfw_conf);
921dfb33
DM
1991 }
1992 };
1993 warn $@ if $@;
4e6112f9 1994 }
3a616aa0 1995 }
9e15114a
DM
1996}
1997
b47ecc88
AD
1998sub generate_nfqueue {
1999 my ($options) = @_;
2000
73089769
DM
2001 if ($options->{ips}) {
2002 my $action = "NFQUEUE";
2003 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2004 if (defined($3) && defined($1)) {
b47ecc88 2005 $action .= " --queue-balance $1:$3";
73089769 2006 } elsif (defined($1)) {
b47ecc88
AD
2007 $action .= " --queue-num $1";
2008 }
2009 }
8dc92812 2010 $action .= " --queue-bypass" if $feature_ipset_nomatch; #need kernel 3.10
73089769
DM
2011 return $action;
2012 } else {
2013 return "ACCEPT";
b47ecc88 2014 }
b47ecc88
AD
2015}
2016
da6fc60b 2017sub ruleset_generate_vm_ipsrules {
a01c32c7 2018 my ($ruleset, $options, $direction, $iface) = @_;
da6fc60b
AD
2019
2020 if ($options->{ips} && $direction eq 'IN') {
2021 my $nfqueue = generate_nfqueue($options);
2022
a01c32c7 2023 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS")) {
da6fc60b
AD
2024 ruleset_create_chain($ruleset, "PVEFW-IPS");
2025 }
2026
a01c32c7 2027 ruleset_addrule($ruleset, "PVEFW-IPS", "-m physdev --physdev-out $iface --physdev-is-bridged -j $nfqueue");
da6fc60b
AD
2028 }
2029}
2030
9e15114a 2031sub generate_tap_rules_direction {
84870b1a 2032 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
9e15114a
DM
2033
2034 my $lc_direction = lc($direction);
2035
2036 my $rules = $vmfw_conf->{rules};
2037
2038 my $options = $vmfw_conf->{options};
2039 my $loglevel = get_option_log_level($options, "log_level_${lc_direction}");
2040
2041 my $tapchain = "$iface-$direction";
2042
b692f42c 2043 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
88c26d5e 2044 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
b692f42c 2045 if $vmfw_conf->{ipset}->{$ipfilter_name};
808d711d 2046
a34cfdd0 2047 # create chain with mac and ip filter
88c26d5e 2048 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
9e15114a 2049
a34cfdd0 2050 if ($options->{enable}) {
84870b1a 2051 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
3a616aa0 2052
a34cfdd0 2053 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
da6fc60b 2054
a34cfdd0
DM
2055 # implement policy
2056 my $policy;
ccae0b50 2057
a34cfdd0
DM
2058 if ($direction eq 'OUT') {
2059 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2060 } else {
72f63fde 2061 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
a34cfdd0 2062 }
ccae0b50 2063
a34cfdd0
DM
2064 my $accept = generate_nfqueue($options);
2065 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : $accept;
88c26d5e 2066 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
a34cfdd0
DM
2067 } else {
2068 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK" : 'ACCEPT';
88c26d5e 2069 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
a34cfdd0 2070 }
3a616aa0 2071
3fa83edf 2072 # plug the tap chain to bridge chain
3cc81077 2073 if ($direction eq 'IN') {
a01c32c7
DM
2074 ruleset_addrule($ruleset, "PVEFW-FWBR-IN",
2075 "-m physdev --physdev-is-bridged --physdev-out $iface -j $tapchain");
3cc81077 2076 } else {
a01c32c7
DM
2077 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT",
2078 "-m physdev --physdev-is-bridged --physdev-in $iface -j $tapchain");
3cc81077 2079 }
3a616aa0
AD
2080}
2081
d18c1e2b 2082sub enable_host_firewall {
aedde2c2 2083 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
0bd5f137 2084
92e976b3 2085 my $options = $hostfw_conf->{options};
63324b09 2086 my $cluster_options = $cluster_conf->{options};
92e976b3 2087 my $rules = $hostfw_conf->{rules};
35f0c37e 2088 my $cluster_rules = $cluster_conf->{rules};
178a63be 2089
3fa83edf 2090 # host inbound firewall
dec84fcd
DM
2091 my $chain = "PVEFW-HOST-IN";
2092 ruleset_create_chain($ruleset, $chain);
0bd5f137 2093
178a63be
DM
2094 my $loglevel = get_option_log_level($options, "log_level_in");
2095
e2943485 2096 ruleset_addrule($ruleset, $chain, "-i lo -j ACCEPT");
4ac863a6 2097
e2943485 2098 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
88c26d5e 2099 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
fb424a00 2100
23e888f8
DM
2101 # we use RETURN because we need to check also tap rules
2102 my $accept_action = 'RETURN';
2103
cc8dc02f
DM
2104 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2105
35f0c37e
DM
2106 # add host rules first, so that cluster wide rules can be overwritten
2107 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 2108 next if !$rule->{enable} || $rule->{errors};
35d1d6da 2109 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
bfc488f6 2110
f8b12fff 2111 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
5383df39 2112
1a9978ed
DM
2113 eval {
2114 if ($rule->{type} eq 'group') {
aedde2c2 2115 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
1a9978ed 2116 } elsif ($rule->{type} eq 'in') {
88c26d5e
DM
2117 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2118 { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2119 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2120 }
2121 };
2122 warn $@ if $@;
f8b12fff 2123 delete $rule->{iface_in};
0bd5f137 2124 }
eb399cef
DM
2125
2126 # allow standard traffic for management ipset (includes cluster network)
88c26d5e 2127 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management", $ipversion);
708ba714 2128 my $mngmntsrc = "-m set --match-set ${mngmnt_ipset_chain} src";
eb399cef 2129 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 8006 -j $accept_action"); # PVE API
bfc488f6 2130 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
eb399cef
DM
2131 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
2132 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 2133
afcd29b3
DM
2134 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2135 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
3bc79f87 2136
eb399cef 2137 # corosync
35d1d6da 2138 if ($localnet && ($ipversion == $localnet_ver)) {
c5191f57 2139 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7
DM
2140 ruleset_addrule($ruleset, $chain, "-s $localnet -d $localnet $corosync_rule");
2141 ruleset_addrule($ruleset, $chain, "-s $localnet -m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87 2142 }
0bd5f137 2143
23e888f8 2144 # implement input policy
63324b09 2145 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
88c26d5e 2146 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
0bd5f137 2147
3fa83edf 2148 # host outbound firewall
aadd745e 2149 $chain = "PVEFW-HOST-OUT";
dec84fcd
DM
2150 ruleset_create_chain($ruleset, $chain);
2151
178a63be
DM
2152 $loglevel = get_option_log_level($options, "log_level_out");
2153
dec84fcd 2154 ruleset_addrule($ruleset, $chain, "-o lo -j ACCEPT");
e2943485
DM
2155
2156 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2157
23e888f8
DM
2158 # we use RETURN because we may want to check other thigs later
2159 $accept_action = 'RETURN';
2160
cc8dc02f
DM
2161 ruleset_addrule($ruleset, $chain, "-p igmp -j $accept_action"); # important for multicast
2162
35f0c37e
DM
2163 # add host rules first, so that cluster wide rules can be overwritten
2164 foreach my $rule (@$rules, @$cluster_rules) {
5383df39 2165 next if !$rule->{enable} || $rule->{errors};
35d1d6da 2166 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
5383df39 2167
f8b12fff 2168 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1a9978ed
DM
2169 eval {
2170 if ($rule->{type} eq 'group') {
aedde2c2 2171 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
1a9978ed 2172 } elsif ($rule->{type} eq 'out') {
88c26d5e
DM
2173 ruleset_generate_rule($ruleset, $chain, $ipversion,
2174 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject" },
e523d2bb 2175 undef, $cluster_conf, $hostfw_conf);
1a9978ed
DM
2176 }
2177 };
2178 warn $@ if $@;
f8b12fff 2179 delete $rule->{iface_out};
0bd5f137
AD
2180 }
2181
3bc79f87 2182 # allow standard traffic on cluster network
35d1d6da 2183 if ($localnet && ($ipversion == $localnet_ver)) {
525778d7
DM
2184 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 8006 -j $accept_action"); # PVE API
2185 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 22 -j $accept_action"); # SSH
bfc488f6 2186 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 5900:5999 -j $accept_action"); # PVE VNC Console
525778d7 2187 ruleset_addrule($ruleset, $chain, "-d $localnet -p tcp --dport 3128 -j $accept_action"); # SPICE Proxy
bfc488f6 2188
c5191f57 2189 my $corosync_rule = "-p udp --dport 5404:5405 -j $accept_action";
525778d7 2190 ruleset_addrule($ruleset, $chain, "-d $localnet $corosync_rule");
f573ae2c 2191 ruleset_addrule($ruleset, $chain, "-m addrtype --dst-type MULTICAST $corosync_rule");
3bc79f87
DM
2192 }
2193
23e888f8 2194 # implement output policy
63324b09 2195 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
88c26d5e 2196 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
6158271d 2197
dec84fcd
DM
2198 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-j PVEFW-HOST-OUT");
2199 ruleset_addrule($ruleset, "PVEFW-INPUT", "-j PVEFW-HOST-IN");
9d31b418
AD
2200}
2201
2202sub generate_group_rules {
aedde2c2 2203 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
9d31b418 2204
c6f5cc88 2205 my $rules = $cluster_conf->{groups}->{$group};
6158271d 2206
b4deedab
DM
2207 if (!$rules) {
2208 warn "no such security group '$group'\n";
2209 $rules = []; # create empty chain
2210 }
2211
3fa83edf 2212 my $chain = "GROUP-${group}-IN";
9d31b418 2213
3fa83edf 2214 ruleset_create_chain($ruleset, $chain);
b47ecc88 2215 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 2216
92e976b3
DM
2217 foreach my $rule (@$rules) {
2218 next if $rule->{type} ne 'in';
aedde2c2 2219 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
88c26d5e
DM
2220 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2221 { ACCEPT => "PVEFW-SET-ACCEPT-MARK", REJECT => "PVEFW-reject" },
2222 undef, $cluster_conf);
9d31b418
AD
2223 }
2224
3fa83edf 2225 $chain = "GROUP-${group}-OUT";
9d31b418 2226
3fa83edf 2227 ruleset_create_chain($ruleset, $chain);
4e6112f9 2228 ruleset_addrule($ruleset, $chain, "-j MARK --set-mark 0"); # clear mark
9d31b418 2229
92e976b3
DM
2230 foreach my $rule (@$rules) {
2231 next if $rule->{type} ne 'out';
aedde2c2 2232 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
92e976b3
DM
2233 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2234 # check also other tap rules later
88c26d5e
DM
2235 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2236 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject" },
2237 undef, $cluster_conf);
9d31b418 2238 }
9d31b418
AD
2239}
2240
51bae274
DM
2241my $MAX_NETS = 32;
2242my $valid_netdev_names = {};
2243for (my $i = 0; $i < $MAX_NETS; $i++) {
2244 $valid_netdev_names->{"net$i"} = 1;
2245}
5e1267a5 2246
51bae274 2247sub parse_fw_rule {
a523e057 2248 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
5e1267a5 2249
d4cda423
DM
2250 my $orig_line = $line;
2251
6d9246e7
DM
2252 my $rule = {};
2253
11bac5c2 2254 # we can add single line comments to the end of the rule
6d9246e7
DM
2255 if ($line =~ s/#\s*(.*?)\s*$//) {
2256 $rule->{comment} = decode('utf8', $1);
2257 }
11bac5c2
DM
2258
2259 # we can disable a rule when prefixed with '|'
ea9e5116 2260
6d9246e7 2261 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
51bae274 2262
dba740a9
DM
2263 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2264 die "unable to parse rule: $line\n";
6d9246e7
DM
2265
2266 $rule->{type} = lc($1);
2267 $rule->{action} = $2;
2268
2269 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2270 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2271 $rule->{macro} = $1;
2272 $rule->{action} = $2;
92e976b3 2273 }
51bae274
DM
2274 }
2275
dba740a9
DM
2276 while (length($line)) {
2277 if ($line =~ s/^-i (\S+)\s*//) {
6d9246e7 2278 $rule->{iface} = $1;
dba740a9
DM
2279 next;
2280 }
51bae274 2281
6d9246e7 2282 last if $rule->{type} eq 'group';
51bae274 2283
dba740a9 2284 if ($line =~ s/^-p (\S+)\s*//) {
6d9246e7 2285 $rule->{proto} = $1;
dba740a9
DM
2286 next;
2287 }
6d9246e7 2288
dba740a9 2289 if ($line =~ s/^-dport (\S+)\s*//) {
6d9246e7 2290 $rule->{dport} = $1;
dba740a9
DM
2291 next;
2292 }
6d9246e7 2293
dba740a9 2294 if ($line =~ s/^-sport (\S+)\s*//) {
6d9246e7 2295 $rule->{sport} = $1;
dba740a9
DM
2296 next;
2297 }
2298 if ($line =~ s/^-source (\S+)\s*//) {
6d9246e7 2299 $rule->{source} = $1;
dba740a9
DM
2300 next;
2301 }
2302 if ($line =~ s/^-dest (\S+)\s*//) {
6d9246e7 2303 $rule->{dest} = $1;
dba740a9
DM
2304 next;
2305 }
51bae274 2306
dba740a9
DM
2307 last;
2308 }
ba791b1f 2309
dba740a9 2310 die "unable to parse rule parameters: $line\n" if length($line);
51bae274 2311
a523e057 2312 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
d4cda423
DM
2313 if ($verbose && $rule->{errors}) {
2314 warn "$prefix - errors in rule parameters: $orig_line\n";
2315 foreach my $p (keys %{$rule->{errors}}) {
2316 warn " $p: $rule->{errors}->{$p}\n";
2317 }
2318 }
6d9246e7
DM
2319
2320 return $rule;
51bae274
DM
2321}
2322
2d404ffc 2323sub parse_vmfw_option {
85c6eaed
DM
2324 my ($line) = @_;
2325
2326 my ($opt, $value);
2327
178a63be
DM
2328 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2329
6bafd113 2330 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
9c6b6efd
DM
2331 $opt = lc($1);
2332 $value = int($2);
178a63be
DM
2333 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2334 $opt = lc($1);
2335 $value = $2 ? lc($3) : '';
72f63fde 2336 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
85c6eaed
DM
2337 $opt = lc($1);
2338 $value = uc($3);
b47ecc88
AD
2339 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2340 $opt = lc($1);
2341 $value = $2;
9c6b6efd 2342 } else {
85c6eaed
DM
2343 die "can't parse option '$line'\n"
2344 }
2345
2346 return ($opt, $value);
2347}
2348
2d404ffc
DM
2349sub parse_hostfw_option {
2350 my ($line) = @_;
2351
2352 my ($opt, $value);
2353
2354 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2355
c50a5a68 2356 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2d404ffc
DM
2357 $opt = lc($1);
2358 $value = int($2);
178a63be 2359 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2d404ffc
DM
2360 $opt = lc($1);
2361 $value = $2 ? lc($3) : '';
28c082a1 2362 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
490cdead
DM
2363 $opt = lc($1);
2364 $value = int($2);
2d404ffc 2365 } else {
2d404ffc
DM
2366 die "can't parse option '$line'\n"
2367 }
2368
2369 return ($opt, $value);
2370}
2371
c6f5cc88
DM
2372sub parse_clusterfw_option {
2373 my ($line) = @_;
2374
2375 my ($opt, $value);
2376
72d055fc 2377 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
c6f5cc88
DM
2378 $opt = lc($1);
2379 $value = int($2);
72d055fc
AG
2380 if (($value > 1) && ((time() - $value) > 60)) {
2381 $value = 0
2382 }
63324b09
DM
2383 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2384 $opt = lc($1);
2385 $value = uc($3);
c6f5cc88 2386 } else {
c6f5cc88
DM
2387 die "can't parse option '$line'\n"
2388 }
2389
2390 return ($opt, $value);
2391}
2392
6c221576
DM
2393sub resolve_alias {
2394 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2395
6d959e3f 2396 my $alias = lc($cidr);
04f5088f 2397 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
6d959e3f 2398 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
6c221576 2399
6d959e3f
DM
2400 die "no such alias '$cidr'\n" if !$e;;
2401
2402 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
6c221576
DM
2403}
2404
ae029a88
DM
2405sub parse_ip_or_cidr {
2406 my ($cidr) = @_;
2407
2408 my $ipversion;
2409
2410 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2411 $cidr =~ s|/128$||;
2412 $ipversion = 6;
2413 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2414 $cidr =~ s|/32$||;
2415 $ipversion = 4;
2416 } else {
2417 die "value does not look like a valid IP address or CIDR network\n";
2418 }
2419
2420 return wantarray ? ($cidr, $ipversion) : $cidr;
2421}
2422
e76a9f53 2423sub parse_alias {
92e1209b
AD
2424 my ($line) = @_;
2425
81d574a7
DM
2426 # we can add single line comments to the end of the line
2427 my $comment = decode('utf8', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2428
92e1209b 2429 if ($line =~ m/^(\S+)\s(\S+)$/) {
81d574a7 2430 my ($name, $cidr) = ($1, $2);
ae029a88
DM
2431 my $ipversion;
2432
2433 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2434
81d574a7
DM
2435 my $data = {
2436 name => $name,
2437 cidr => $cidr,
70e524eb 2438 ipversion => $ipversion,
81d574a7
DM
2439 };
2440 $data->{comment} = $comment if $comment;
2441 return $data;
92e1209b
AD
2442 }
2443
81d574a7 2444 return undef;
92e1209b
AD
2445}
2446
e5cd1ee0 2447sub generic_fw_config_parser {
1210ae94 2448 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
5e1267a5 2449
51bae274
DM
2450 my $section;
2451 my $group;
2452
1210ae94 2453 my $res = $empty_conf;
6158271d 2454
51bae274
DM
2455 while (defined(my $line = <$fh>)) {
2456 next if $line =~ m/^#/;
2457 next if $line =~ m/^\s*$/;
2458
c8c534f7
DM
2459 chomp $line;
2460
961b4928
DM
2461 my $linenr = $fh->input_line_number();
2462 my $prefix = "$filename (line $linenr)";
2463
1210ae94 2464 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
c6f5cc88
DM
2465 $section = 'options';
2466 next;
2467 }
2468
1210ae94 2469 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
92e1209b
AD
2470 $section = 'aliases';
2471 next;
2472 }
2473
1210ae94 2474 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
c6f5cc88 2475 $section = 'groups';
92e976b3 2476 $group = lc($1);
0d22acb3 2477 my $comment = $2;
351052d1
DM
2478 eval {
2479 die "security group name too long\n" if length($group) > $max_group_name_length;
2480 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2481 };
2482 if (my $err = $@) {
2483 ($section, $group, $comment) = undef;
2484 warn "$prefix: $err";
2485 next;
2486 }
2487
c85c87f9 2488 $res->{$section}->{$group} = [];
649e4d57
DM
2489 $res->{group_comments}->{$group} = decode('utf8', $comment)
2490 if $comment;
51bae274
DM
2491 next;
2492 }
34cdedfa 2493
1210ae94 2494 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
c6f5cc88
DM
2495 $section = 'rules';
2496 next;
2497 }
cbb5d6f3 2498
1210ae94 2499 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
34cdedfa
AD
2500 $section = 'ipset';
2501 $group = lc($1);
d72c631c 2502 my $comment = $2;
351052d1
DM
2503 eval {
2504 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2505 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2506 };
2507 if (my $err = $@) {
2508 ($section, $group, $comment) = undef;
2509 warn "$prefix: $err";
2510 next;
2511 }
2512
c85c87f9 2513 $res->{$section}->{$group} = [];
e34d0e58 2514 $res->{ipset_comments}->{$group} = decode('utf8', $comment)
649e4d57 2515 if $comment;
34cdedfa
AD
2516 next;
2517 }
2518
c6f5cc88 2519 if (!$section) {
cbb5d6f3 2520 warn "$prefix: skip line - no section\n";
51bae274
DM
2521 next;
2522 }
2523
c6f5cc88
DM
2524 if ($section eq 'options') {
2525 eval {
1210ae94
DM
2526 my ($opt, $value);
2527 if ($rule_env eq 'cluster') {
2528 ($opt, $value) = parse_clusterfw_option($line);
2529 } elsif ($rule_env eq 'host') {
2530 ($opt, $value) = parse_hostfw_option($line);
2531 } else {
2532 ($opt, $value) = parse_vmfw_option($line);
2533 }
c6f5cc88
DM
2534 $res->{options}->{$opt} = $value;
2535 };
2536 warn "$prefix: $@" if $@;
92e1209b
AD
2537 } elsif ($section eq 'aliases') {
2538 eval {
e76a9f53 2539 my $data = parse_alias($line);
81d574a7 2540 $res->{aliases}->{lc($data->{name})} = $data;
92e1209b
AD
2541 };
2542 warn "$prefix: $@" if $@;
c6f5cc88
DM
2543 } elsif ($section eq 'rules') {
2544 my $rule;
1210ae94 2545 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
c6f5cc88
DM
2546 if (my $err = $@) {
2547 warn "$prefix: $err";
2548 next;
2549 }
2550 push @{$res->{$section}}, $rule;
2551 } elsif ($section eq 'groups') {
34cdedfa 2552 my $rule;
1210ae94 2553 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group', $verbose); };
34cdedfa
AD
2554 if (my $err = $@) {
2555 warn "$prefix: $err";
2556 next;
2557 }
3f95d14a 2558 push @{$res->{$section}->{$group}}, $rule;
3f95d14a 2559 } elsif ($section eq 'ipset') {
9d6f90e6
DM
2560 # we can add single line comments to the end of the rule
2561 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
2562
30f1b100 2563 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2a052ee3 2564 my $nomatch = $1;
9d6f90e6 2565 my $cidr = $2;
d46b1ef6
DM
2566 my $errors;
2567
2568 if ($nomatch && !$feature_ipset_nomatch) {
2569 $errors->{nomatch} = "nomatch not supported by kernel";
2570 }
2a052ee3 2571
4803b296
DM
2572 eval {
2573 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2574 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2575 } else {
ae029a88 2576 $cidr = parse_ip_or_cidr($cidr);
92e1209b 2577 }
4803b296
DM
2578 };
2579 if (my $err = $@) {
c8c534f7 2580 chomp $err;
d46b1ef6 2581 $errors->{cidr} = $err;
2a052ee3 2582 }
2a052ee3 2583
e34d0e58 2584 my $entry = { cidr => $cidr };
9d6f90e6
DM
2585 $entry->{nomatch} = 1 if $nomatch;
2586 $entry->{comment} = $comment if $comment;
d46b1ef6 2587 $entry->{errors} = $errors if $errors;
e34d0e58 2588
c8c534f7 2589 if ($verbose && $errors) {
9a3061c7 2590 warn "$prefix - errors in ipset '$group': $line\n";
c8c534f7
DM
2591 foreach my $p (keys %{$errors}) {
2592 warn " $p: $errors->{$p}\n";
2593 }
2594 }
2595
9d6f90e6 2596 push @{$res->{$section}->{$group}}, $entry;
1210ae94
DM
2597 } else {
2598 warn "$prefix: skip line - unknown section\n";
2599 next;
51bae274 2600 }
5e1267a5
DM
2601 }
2602
2603 return $res;
2604}
2605
e5cd1ee0 2606sub parse_hostfw_config {
1210ae94
DM
2607 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2608
2609 my $empty_conf = { rules => [], options => {}};
2610
e5cd1ee0 2611 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host');
1210ae94
DM
2612}
2613
e5cd1ee0 2614sub parse_vmfw_config {
1210ae94
DM
2615 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2616
2617 my $empty_conf = {
2618 rules => [],
2619 options => {},
2620 aliases => {},
2621 ipset => {} ,
2622 ipset_comments => {},
2623 };
2624
e5cd1ee0 2625 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
1210ae94
DM
2626}
2627
e5cd1ee0 2628sub parse_clusterfw_config {
1210ae94
DM
2629 my ($filename, $fh, $verbose) = @_;
2630
2631 my $section;
2632 my $group;
2633
2634 my $empty_conf = {
2635 rules => [],
2636 options => {},
2637 aliases => {},
2638 groups => {},
2639 group_comments => {},
2640 ipset => {} ,
2641 ipset_comments => {},
2642 };
2643
e5cd1ee0 2644 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster');
1210ae94
DM
2645}
2646
06320eb0
DM
2647sub run_locked {
2648 my ($code, @param) = @_;
2649
2650 my $timeout = 10;
2651
2652 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2653
2654 die $@ if $@;
2655
2656 return $res;
2657}
2658
5e1267a5
DM
2659sub read_local_vm_config {
2660
5e1267a5 2661 my $qemu = {};
3b4882dc 2662 my $lxc = {};
5e1267a5 2663
fdefeeab 2664 my $vmdata = { qemu => $qemu, lxc => $lxc };
5e1267a5 2665
c8301d63
DM
2666 my $vmlist = PVE::Cluster::get_vmlist();
2667 return $vmdata if !$vmlist || !$vmlist->{ids};
2668 my $ids = $vmlist->{ids};
2669
2670 foreach my $vmid (keys %$ids) {
2671 next if !$vmid; # skip VE0
2672 my $d = $ids->{$vmid};
2673 next if !$d->{node} || $d->{node} ne $nodename;
2674 next if !$d->{type};
fdefeeab 2675 if ($d->{type} eq 'qemu') {
d9fee004
DM
2676 if ($have_qemu_server) {
2677 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2678 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2679 $qemu->{$vmid} = $conf;
2680 }
c8301d63 2681 }
3b4882dc
AG
2682 } elsif ($d->{type} eq 'lxc') {
2683 if ($have_lxc) {
2684 my $cfspath = PVE::LXC::cfs_config_path($vmid);
2685 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2686 $lxc->{$vmid} = $conf;
2687 }
2688 }
2689 }
5e1267a5 2690 }
d9fee004 2691
5e1267a5
DM
2692 return $vmdata;
2693};
2694
e7b35711 2695sub load_vmfw_conf {
a523e057 2696 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
e7b35711
DM
2697
2698 my $vmfw_conf = {};
2699
21053409 2700 $dir = $pvefw_conf_dir if !defined($dir);
8aef5177
DM
2701
2702 my $filename = "$dir/$vmid.fw";
e7b35711 2703 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 2704 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
708ba714 2705 $vmfw_conf->{vmid} = $vmid;
e7b35711
DM
2706 }
2707
2708 return $vmfw_conf;
2709}
2710
464f933e 2711my $format_rules = sub {
dba740a9 2712 my ($rules, $allow_iface) = @_;
464f933e
DM
2713
2714 my $raw = '';
2715
2716 foreach my $rule (@$rules) {
c14dacdf 2717 if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
464f933e
DM
2718 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2719 $raw .= uc($rule->{type});
7ca36671
DM
2720 if ($rule->{macro}) {
2721 $raw .= " $rule->{macro}($rule->{action})";
2722 } else {
2723 $raw .= " " . $rule->{action};
2724 }
dba740a9
DM
2725 if ($allow_iface && $rule->{iface}) {
2726 $raw .= " -i $rule->{iface}";
2727 }
c14dacdf
DM
2728
2729 if ($rule->{type} ne 'group') {
dba740a9
DM
2730 $raw .= " -source $rule->{source}" if $rule->{source};
2731 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2732 $raw .= " -p $rule->{proto}" if $rule->{proto};
2733 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2734 $raw .= " -sport $rule->{sport}" if $rule->{sport};
c14dacdf
DM
2735 }
2736
cbb5d6f3 2737 $raw .= " # " . encode('utf8', $rule->{comment})
464f933e
DM
2738 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2739 $raw .= "\n";
2740 } else {
c14dacdf 2741 die "unknown rule type '$rule->{type}'";
464f933e
DM
2742 }
2743 }
2744
2745 return $raw;
2746};
2747
2748my $format_options = sub {
68c90e21
DM
2749 my ($options) = @_;
2750
2751 my $raw = '';
464f933e
DM
2752
2753 $raw .= "[OPTIONS]\n\n";
2754 foreach my $opt (keys %$options) {
2755 $raw .= "$opt: $options->{$opt}\n";
2756 }
2757 $raw .= "\n";
68c90e21
DM
2758
2759 return $raw;
464f933e
DM
2760};
2761
0d5f0a0f
DM
2762my $format_aliases = sub {
2763 my ($aliases) = @_;
2764
2765 my $raw = '';
2766
2767 $raw .= "[ALIASES]\n\n";
2768 foreach my $k (keys %$aliases) {
81d574a7
DM
2769 my $e = $aliases->{$k};
2770 $raw .= "$e->{name} $e->{cidr}";
2771 $raw .= " # " . encode('utf8', $e->{comment})
2772 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2773 $raw .= "\n";
0d5f0a0f
DM
2774 }
2775 $raw .= "\n";
2776
2777 return $raw;
2778};
2779
1210ae94
DM
2780my $format_ipsets = sub {
2781 my ($fw_conf) = @_;
2782
9d6f90e6
DM
2783 my $raw = '';
2784
1210ae94
DM
2785 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2786 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2787 my $utf8comment = encode('utf8', $comment);
2788 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2789 } else {
2790 $raw .= "[IPSET $ipset]\n\n";
2791 }
2792 my $options = $fw_conf->{ipset}->{$ipset};
6e299ae3 2793
1210ae94
DM
2794 my $nethash = {};
2795 foreach my $entry (@$options) {
2796 $nethash->{$entry->{cidr}} = $entry;
2797 }
2798
2799 foreach my $cidr (sort keys %$nethash) {
2800 my $entry = $nethash->{$cidr};
2801 my $line = $entry->{nomatch} ? '!' : '';
2802 $line .= $entry->{cidr};
2803 $line .= " # " . encode('utf8', $entry->{comment})
2804 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2805 $raw .= "$line\n";
2806 }
2807
2808 $raw .= "\n";
9d6f90e6 2809 }
e34d0e58 2810
9d6f90e6
DM
2811 return $raw;
2812};
2813
464f933e
DM
2814sub save_vmfw_conf {
2815 my ($vmid, $vmfw_conf) = @_;
2816
2817 my $raw = '';
2818
2819 my $options = $vmfw_conf->{options};
89ea63c8 2820 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 2821
e76a9f53 2822 my $aliases = $vmfw_conf->{aliases};
89ea63c8 2823 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e76a9f53 2824
89ea63c8 2825 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
1210ae94 2826
8824b2f0 2827 my $rules = $vmfw_conf->{rules} || [];
89ea63c8 2828 if ($rules && scalar(@$rules)) {
464f933e
DM
2829 $raw .= "[RULES]\n\n";
2830 $raw .= &$format_rules($rules, 1);
2831 $raw .= "\n";
2832 }
2833
21053409
DM
2834 mkdir $pvefw_conf_dir;
2835
2836 my $filename = "$pvefw_conf_dir/$vmid.fw";
464f933e
DM
2837 PVE::Tools::file_set_contents($filename, $raw);
2838}
2839
edee9035
AG
2840sub remove_vmfw_conf {
2841 my ($vmid) = @_;
2842
2843 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
2844
2845 unlink $vmfw_conffile;
2846}
2847
5471ff7c
AG
2848sub clone_vmfw_conf {
2849 my ($vmid, $newid) = @_;
2850
2851 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
2852 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
2853
2854 if (-f $clonevm_conffile) {
2855 unlink $clonevm_conffile;
2856 }
2857 if (-f $sourcevm_conffile) {
2858 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
2859 PVE::Tools::file_set_contents($clonevm_conffile, $data);
2860 }
2861}
2862
6fc63ffd 2863sub read_vm_firewall_configs {
a523e057 2864 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
8aef5177 2865
6fc63ffd 2866 my $vmfw_configs = {};
c8301d63 2867
b6b8e6ad 2868 foreach my $vmid (keys %{$vmdata->{qemu}}) {
a523e057 2869 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm', $vmid, $dir, $verbose);
b6b8e6ad
DM
2870 next if !$vmfw_conf->{options}; # skip if file does not exists
2871 $vmfw_configs->{$vmid} = $vmfw_conf;
2872 }
3b4882dc
AG
2873 foreach my $vmid (keys %{$vmdata->{lxc}}) {
2874 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct', $vmid, $dir, $verbose);
2875 next if !$vmfw_conf->{options}; # skip if file does not exists
2876 $vmfw_configs->{$vmid} = $vmfw_conf;
2877 }
5e1267a5 2878
6fc63ffd 2879 return $vmfw_configs;
5e1267a5
DM
2880}
2881
2d404ffc
DM
2882sub get_option_log_level {
2883 my ($options, $k) = @_;
2884
2885 my $v = $options->{$k};
178a63be 2886 $v = $default_log_level if !defined($v);
2d404ffc
DM
2887
2888 return undef if $v eq '' || $v eq 'nolog';
2889
2890 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2891
2892 return $v if ($v >= 0) && ($v <= 7);
2893
2894 warn "unknown log level ($k = '$v')\n";
2895
2896 return undef;
2897}
2898
d8f2505e 2899sub generate_std_chains {
db8a955f
DM
2900 my ($ruleset, $options, $ipversion) = @_;
2901
2902 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
cbb5d6f3 2903
2d404ffc
DM
2904 my $loglevel = get_option_log_level($options, 'smurf_log_level');
2905
db8a955f 2906 my $chain;
782c4cde 2907
db8a955f
DM
2908 if ($ipversion == 4) {
2909 # same as shorewall smurflog.
2910 $chain = 'PVEFW-smurflog';
2911 $std_chains->{$chain} = [];
2912
2913 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2914 push @{$std_chains->{$chain}}, "-j DROP";
2915 }
2d404ffc
DM
2916
2917 # same as shorewall logflags action.
2918 $loglevel = get_option_log_level($options, 'tcp_flags_log_level');
782c4cde 2919 $chain = 'PVEFW-logflags';
db8a955f 2920 $std_chains->{$chain} = [];
12f3796e 2921
782c4cde 2922 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
db8a955f
DM
2923 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2924 push @{$std_chains->{$chain}}, "-j DROP";
d8f2505e 2925
db8a955f 2926 foreach my $chain (keys %$std_chains) {
d8f2505e 2927 ruleset_create_chain($ruleset, $chain);
db8a955f 2928 foreach my $rule (@{$std_chains->{$chain}}) {
d8f2505e 2929 if (ref($rule)) {
88c26d5e 2930 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
d8f2505e
DM
2931 } else {
2932 ruleset_addrule($ruleset, $chain, $rule);
2933 }
2934 }
2935 }
2936}
2937
34cdedfa 2938sub generate_ipset_chains {
88c26d5e 2939 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_; #fixme
34cdedfa 2940
dd7a13fd 2941 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
34cdedfa 2942
88c26d5e 2943 my $options = $fw_conf->{ipset}->{$ipset};
34cdedfa 2944
88c26d5e
DM
2945 # remove duplicates
2946 my $nethash = {};
2947 foreach my $entry (@$options) {
2948 next if $entry->{errors}; # skip entries with errors
2949 eval {
2950 my ($cidr, $ver);
2951 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2952 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2953 } else {
2954 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
2955 }
2956 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2957 if ($ver == 6) {
ab03c1a7 2958 $cidr = lc(Net::IP::ip_compress_address($cidr, 6));
88c26d5e
DM
2959 $cidr =~ s|/128$||;
2960 } else {
2961 $cidr =~ s|/32$||;
2962 }
34cdedfa 2963
88c26d5e
DM
2964 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2965 };
2966 warn $@ if $@;
2967 }
6d959e3f 2968
88c26d5e
DM
2969 foreach my $ipversion (4, 6) {
2970 my $data = $nethash->{$ipversion};
30f1b100 2971
88c26d5e 2972 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
6d959e3f 2973
88c26d5e
DM
2974 my $hashsize = scalar(@$options);
2975 if ($hashsize <= 64) {
2976 $hashsize = 64;
2977 } else {
2978 $hashsize = round_powerof2($hashsize);
2979 }
6d959e3f 2980
88c26d5e 2981 my $family = $ipversion == "6" ? "inet6" : "inet";
30f1b100 2982
88c26d5e 2983 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
6d959e3f 2984
88c26d5e
DM
2985 foreach my $cidr (sort keys %$data) {
2986 my $entry = $data->{$cidr};
6d959e3f 2987
88c26d5e
DM
2988 my $cmd = "add $name $cidr";
2989 if ($entry->{nomatch}) {
2990 if ($feature_ipset_nomatch) {
2991 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2992 } else {
2993 warn "ignore !$cidr - nomatch not supported by kernel\n";
2994 }
6d959e3f 2995 } else {
88c26d5e 2996 push @{$ipset_ruleset->{$name}}, $cmd;
6d959e3f 2997 }
9d6f90e6 2998 }
9d6f90e6 2999 }
34cdedfa 3000 }
2a052ee3
AD
3001}
3002
3003sub round_powerof2 {
dd7a13fd 3004 my ($int) = @_;
2a052ee3 3005
dd7a13fd
DM
3006 $int--;
3007 $int |= $int >> $_ foreach (1,2,4,8,16);
3008 return ++$int;
34cdedfa
AD
3009}
3010
fca39c2c 3011sub load_clusterfw_conf {
d4cda423 3012 my ($filename, $verbose) = @_;
8aef5177
DM
3013
3014 $filename = $clusterfw_conf_filename if !defined($filename);
530c005e 3015
fca39c2c 3016 my $cluster_conf = {};
8aef5177 3017 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 3018 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
51bae274 3019 }
5e1267a5 3020
fca39c2c 3021 return $cluster_conf;
e5d76bde
DM
3022}
3023
fca39c2c
DM
3024sub save_clusterfw_conf {
3025 my ($cluster_conf) = @_;
9c7e0858
DM
3026
3027 my $raw = '';
9c7e0858 3028
c6f5cc88 3029 my $options = $cluster_conf->{options};
89ea63c8 3030 $raw .= &$format_options($options) if $options && scalar(keys %$options);
9c7e0858 3031
0d5f0a0f 3032 my $aliases = $cluster_conf->{aliases};
89ea63c8 3033 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
e34d0e58 3034
89ea63c8 3035 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
1210ae94 3036
c6f5cc88 3037 my $rules = $cluster_conf->{rules};
89ea63c8 3038 if ($rules && scalar(@$rules)) {
c6f5cc88 3039 $raw .= "[RULES]\n\n";
63c91681 3040 $raw .= &$format_rules($rules, 1);
c6f5cc88
DM
3041 $raw .= "\n";
3042 }
3043
89ea63c8
DM
3044 if ($cluster_conf->{groups}) {
3045 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3046 my $rules = $cluster_conf->{groups}->{$group};
3047 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3048 my $utf8comment = encode('utf8', $comment);
3049 $raw .= "[group $group] # $utf8comment\n\n";
3050 } else {
3051 $raw .= "[group $group]\n\n";
3052 }
0d22acb3 3053
89ea63c8
DM
3054 $raw .= &$format_rules($rules, 0);
3055 $raw .= "\n";
3056 }
9c7e0858
DM
3057 }
3058
21053409 3059 mkdir $pvefw_conf_dir;
fca39c2c 3060 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
9c7e0858
DM
3061}
3062
8b27beb9 3063sub load_hostfw_conf {
a523e057 3064 my ($cluster_conf, $filename, $verbose) = @_;
8aef5177
DM
3065
3066 $filename = $hostfw_conf_filename if !defined($filename);
8b27beb9
DM
3067
3068 my $hostfw_conf = {};
8aef5177 3069 if (my $fh = IO::File->new($filename, O_RDONLY)) {
e5cd1ee0 3070 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
8b27beb9
DM
3071 }
3072 return $hostfw_conf;
3073}
3074
63c91681
DM
3075sub save_hostfw_conf {
3076 my ($hostfw_conf) = @_;
3077
3078 my $raw = '';
3079
3080 my $options = $hostfw_conf->{options};
89ea63c8 3081 $raw .= &$format_options($options) if $options && scalar(keys %$options);
cbb5d6f3 3082
63c91681 3083 my $rules = $hostfw_conf->{rules};
89ea63c8 3084 if ($rules && scalar(@$rules)) {
63c91681
DM
3085 $raw .= "[RULES]\n\n";
3086 $raw .= &$format_rules($rules, 1);
3087 $raw .= "\n";
3088 }
3089
3090 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3091}
3092
e5d76bde 3093sub compile {
d4cda423 3094 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3dfa8a7f 3095
8aef5177
DM
3096 my $vmfw_configs;
3097
3098 if ($vmdata) { # test mode
3099 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3100 my $filename = "$testdir/cluster.fw";
d4cda423 3101 $cluster_conf = load_clusterfw_conf($filename, $verbose);
8aef5177
DM
3102
3103 $filename = "$testdir/host.fw";
a523e057 3104 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
8aef5177 3105
a523e057 3106 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
8aef5177 3107 } else { # normal operation
d4cda423 3108 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
8aef5177 3109
a523e057 3110 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
8aef5177
DM
3111
3112 $vmdata = read_local_vm_config();
a523e057 3113 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
8aef5177 3114 }
3dfa8a7f 3115
9268573a 3116 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
638c755a
AD
3117 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3118
3119 return ($ruleset, $ipset_ruleset, $rulesetv6);
9268573a
AD
3120}
3121
3122sub compile_iptables_filter {
3123 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3124
525778d7
DM
3125 my $localnet;
3126 if ($cluster_conf->{aliases}->{local_network}) {
3127 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3128 } else {
afcd29b3
DM
3129 my $localnet_ver;
3130 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3131
3132 $cluster_conf->{aliases}->{local_network} = {
3133 name => 'local_network', cidr => $localnet, ipversion => $localnet_ver };
525778d7
DM
3134 }
3135
3136 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
bfc488f6 3137
085fd492
DM
3138 return ({}, {}) if !$cluster_conf->{options}->{enable};
3139
3fa83edf
DM
3140 my $ruleset = {};
3141
dec84fcd
DM
3142 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3143 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
5b1df9a0 3144
fadb13dd 3145 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
e34d0e58 3146
8b27beb9 3147 my $hostfw_options = $hostfw_conf->{options} || {};
fadb13dd 3148
88733a74
AD
3149 # fixme: what log level should we use here?
3150 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3151
097820b0 3152 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
88733a74 3153
e2943485 3154 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
88c26d5e 3155 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
e2943485 3156
d1b41c08 3157 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
e2943485
DM
3158
3159 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
d1b41c08 3160 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
e2943485 3161
db8a955f 3162 generate_std_chains($ruleset, $hostfw_options, $ipversion);
fadb13dd 3163
6d2ab017 3164 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2d404ffc 3165
708ba714
DM
3166 my $ipset_ruleset = {};
3167
35d1d6da 3168 if ($hostfw_enable) {
aedde2c2 3169 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
1a9978ed
DM
3170 warn $@ if $@; # just to be sure - should not happen
3171 }
3fa83edf 3172
6158271d 3173 # generate firewall rules for QEMU VMs
3fa83edf 3174 foreach my $vmid (keys %{$vmdata->{qemu}}) {
1a9978ed
DM
3175 eval {
3176 my $conf = $vmdata->{qemu}->{$vmid};
3177 my $vmfw_conf = $vmfw_configs->{$vmid};
3178 return if !$vmfw_conf;
1a9978ed 3179
708ba714
DM
3180 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3181
1a9978ed
DM
3182 foreach my $netid (keys %$conf) {
3183 next if $netid !~ m/^net(\d+)$/;
3184 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3185 next if !$net->{firewall};
3186 my $iface = "tap${vmid}i$1";
3187
3188 my $macaddr = $net->{macaddr};
3189 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3190 $vmfw_conf, $vmid, 'IN', $ipversion);
1a9978ed 3191 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
84870b1a 3192 $vmfw_conf, $vmid, 'OUT', $ipversion);
1a9978ed
DM
3193 }
3194 };
3195 warn $@ if $@; # just to be sure - should not happen
3fa83edf 3196 }
c8301d63 3197
3b4882dc
AG
3198 # generate firewall rules for LXC containers
3199 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3200 eval {
3201 my $conf = $vmdata->{lxc}->{$vmid};
3202 my $vmfw_conf = $vmfw_configs->{$vmid};
3203 return if !$vmfw_conf;
3204
3205 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3206
3207 if ($vmfw_conf->{options}->{enable}) {
3208 foreach my $netid (keys %$conf) {
3209 next if $netid !~ m/^net(\d+)$/;
3210 my $net = PVE::LXC::parse_lxc_network($conf->{$netid});
3211 next if !$net->{firewall};
3212 my $iface = "veth${vmid}i$1";
3213 my $macaddr = $net->{hwaddr};
3214 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3215 $vmfw_conf, $vmid, 'IN', $ipversion);
3216 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3217 $vmfw_conf, $vmid, 'OUT', $ipversion);
3218 }
3219 }
3220 };
3221 warn $@ if $@; # just to be sure - should not happen
3222 }
3223
097820b0
AD
3224 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3225 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3226 }
3227
708ba714 3228 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
27083984 3229
3dfa8a7f 3230 return ($ruleset, $ipset_ruleset);
3fa83edf
DM
3231}
3232
3233sub get_ruleset_status {
4bd0a9c4 3234 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3fa83edf
DM
3235
3236 my $statushash = {};
3237
3238 foreach my $chain (sort keys %$ruleset) {
4bd0a9c4 3239 my $sig = &$digest_fn($ruleset->{$chain});
9bf7d929 3240
3fa83edf
DM
3241 $statushash->{$chain}->{sig} = $sig;
3242
3243 my $oldsig = $active_chains->{$chain};
3244 if (!defined($oldsig)) {
3245 $statushash->{$chain}->{action} = 'create';
3246 } else {
3247 if ($oldsig eq $sig) {
3248 $statushash->{$chain}->{action} = 'exists';
3249 } else {
3250 $statushash->{$chain}->{action} = 'update';
3251 }
3252 }
3253 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3254 foreach my $cmd (@{$ruleset->{$chain}}) {
3255 print "\t$cmd\n" if $verbose;
3256 }
3257 }
3258
3259 foreach my $chain (sort keys %$active_chains) {
3260 if (!defined($ruleset->{$chain})) {
3261 my $sig = $active_chains->{$chain};
3262 $statushash->{$chain}->{action} = 'delete';
3263 $statushash->{$chain}->{sig} = $sig;
3264 print "delete $chain ($sig)\n" if $verbose;
3265 }
6158271d 3266 }
2a052ee3 3267
3fa83edf
DM
3268 return $statushash;
3269}
3270
3fa83edf
DM
3271sub print_sig_rule {
3272 my ($chain, $sig) = @_;
3273
09d5f68e
DM
3274 # We just use this to store a SHA1 checksum used to detect changes
3275 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
b6360c3f
DM
3276}
3277
df7cb349 3278sub get_ruleset_cmdlist {
17da5c0f 3279 my ($ruleset, $verbose, $iptablescmd) = @_;
3fa83edf 3280
3fa83edf 3281 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
cbb5d6f3 3282
17da5c0f 3283 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
4bd0a9c4 3284 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3fa83edf
DM
3285
3286 # create missing chains first
3287 foreach my $chain (sort keys %$ruleset) {
3288 my $stat = $statushash->{$chain};
3289 die "internal error" if !$stat;
3290 next if $stat->{action} ne 'create';
886aba9c 3291
3fa83edf
DM
3292 $cmdlist .= ":$chain - [0:0]\n";
3293 }
3294
4bd0a9c4 3295 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
55fad3b7
DM
3296 my $chain = "PVEFW-$h";
3297 if ($ruleset->{$chain} && !$hooks->{$h}) {
3298 $cmdlist .= "-A $h -j $chain\n";
4bd0a9c4 3299 }
3fa83edf
DM
3300 }
3301
3302 foreach my $chain (sort keys %$ruleset) {
3303 my $stat = $statushash->{$chain};
3304 die "internal error" if !$stat;
3305
3306 if ($stat->{action} eq 'update' || $stat->{action} eq 'create') {
3307 $cmdlist .= "-F $chain\n";
3308 foreach my $cmd (@{$ruleset->{$chain}}) {
3309 $cmdlist .= "$cmd\n";
3310 }
3311 $cmdlist .= print_sig_rule($chain, $stat->{sig});
3312 } elsif ($stat->{action} eq 'delete') {
f5d28682 3313 die "internal error"; # this should not happen
3fa83edf
DM
3314 } elsif ($stat->{action} eq 'exists') {
3315 # do nothing
3316 } else {
3317 die "internal error - unknown status '$stat->{action}'";
3318 }
3319 }
3320
f5d28682
DM
3321 foreach my $chain (keys %$statushash) {
3322 next if $statushash->{$chain}->{action} ne 'delete';
3323 $cmdlist .= "-F $chain\n";
3324 }
3325 foreach my $chain (keys %$statushash) {
3326 next if $statushash->{$chain}->{action} ne 'delete';
fadb13dd
DM
3327 next if $chain eq 'PVEFW-INPUT';
3328 next if $chain eq 'PVEFW-OUTPUT';
3329 next if $chain eq 'PVEFW-FORWARD';
f5d28682
DM
3330 $cmdlist .= "-X $chain\n";
3331 }
3332
3f95d14a 3333 my $changes = $cmdlist ne "*filter\n" ? 1 : 0;
4bd0a9c4 3334
3fa83edf
DM
3335 $cmdlist .= "COMMIT\n";
3336
3f95d14a 3337 return wantarray ? ($cmdlist, $changes) : $cmdlist;
6b9f68a2
DM
3338}
3339
34cdedfa 3340sub get_ipset_cmdlist {
dd7a13fd 3341 my ($ruleset, $verbose) = @_;
34cdedfa
AD
3342
3343 my $cmdlist = "";
3344
dd7a13fd
DM
3345 my $delete_cmdlist = "";
3346
4bd0a9c4
DM
3347 my $active_chains = ipset_get_chains();
3348 my $statushash = get_ruleset_status($ruleset, $active_chains, \&ipset_chain_digest, $verbose);
34cdedfa 3349
e34d0e58 3350 # remove stale _swap chains
30f1b100
DM
3351 foreach my $chain (keys %$active_chains) {
3352 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3353 $cmdlist .= "destroy $chain\n";
3354 }
3355 }
3356
c69cf614 3357 foreach my $chain (keys %$ruleset) {
c69cf614
DM
3358 my $stat = $statushash->{$chain};
3359 die "internal error" if !$stat;
3360
3361 if ($stat->{action} eq 'create') {
3362 foreach my $cmd (@{$ruleset->{$chain}}) {
3363 $cmdlist .= "$cmd\n";
3364 }
3365 }
3366 }
3367
3368 foreach my $chain (keys %$ruleset) {
6d959e3f
DM
3369 my $stat = $statushash->{$chain};
3370 die "internal error" if !$stat;
34cdedfa 3371
dd7a13fd
DM
3372 if ($stat->{action} eq 'update') {
3373 my $chain_swap = $chain."_swap";
cbb5d6f3 3374
dd7a13fd
DM
3375 foreach my $cmd (@{$ruleset->{$chain}}) {
3376 $cmd =~ s/$chain/$chain_swap/;
3377 $cmdlist .= "$cmd\n";
34cdedfa 3378 }
dd7a13fd
DM
3379 $cmdlist .= "swap $chain_swap $chain\n";
3380 $cmdlist .= "flush $chain_swap\n";
3381 $cmdlist .= "destroy $chain_swap\n";
2a052ee3 3382 }
dd7a13fd 3383 }
3f95d14a 3384
88c26d5e 3385 # the remove unused chains
c69cf614 3386 foreach my $chain (keys %$statushash) {
dd7a13fd 3387 next if $statushash->{$chain}->{action} ne 'delete';
2a052ee3 3388
dd7a13fd
DM
3389 $delete_cmdlist .= "flush $chain\n";
3390 $delete_cmdlist .= "destroy $chain\n";
34cdedfa
AD
3391 }
3392
dd7a13fd 3393 my $changes = ($cmdlist || $delete_cmdlist) ? 1 : 0;
cbb5d6f3 3394
dd7a13fd 3395 return ($cmdlist, $delete_cmdlist, $changes);
34cdedfa
AD
3396}
3397
6b9f68a2 3398sub apply_ruleset {
17da5c0f 3399 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
6b9f68a2
DM
3400
3401 enable_bridge_firewall();
3402
cbb5d6f3 3403 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
81a0bf43 3404 get_ipset_cmdlist($ipset_ruleset, undef, $verbose);
6b9f68a2 3405
81a0bf43 3406 my ($cmdlist, $changes) = get_ruleset_cmdlist($ruleset, $verbose);
17da5c0f 3407 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
2a052ee3 3408
81a0bf43
DM
3409 if ($verbose) {
3410 if ($ipset_changes) {
3411 print "ipset changes:\n";
3412 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3413 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3414 }
3f95d14a 3415
81a0bf43
DM
3416 if ($changes) {
3417 print "iptables changes:\n";
3418 print $cmdlist;
3419 }
17da5c0f
AD
3420
3421 if ($changesv6) {
3422 print "ip6tables changes:\n";
3423 print $cmdlistv6;
3424 }
81a0bf43 3425 }
3fa83edf 3426
259db1e6
DM
3427 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3428 PVE::Tools::file_set_contents($tmpfile, $ipset_create_cmdlist || '');
3429
2a052ee3 3430 ipset_restore_cmdlist($ipset_create_cmdlist);
34cdedfa 3431
259db1e6
DM
3432 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3433 PVE::Tools::file_set_contents($tmpfile, $cmdlist || '');
3434
3fa83edf 3435 iptables_restore_cmdlist($cmdlist);
259db1e6
DM
3436
3437 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3438 PVE::Tools::file_set_contents($tmpfile, $cmdlistv6 || '');
3439
17da5c0f 3440 ip6tables_restore_cmdlist($cmdlistv6);
3fa83edf 3441
259db1e6
DM
3442 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3443 PVE::Tools::file_set_contents($tmpfile, $ipset_delete_cmdlist || '');
3444
dd7a13fd 3445 ipset_restore_cmdlist($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2a052ee3 3446
6158271d 3447 # test: re-read status and check if everything is up to date
4bd0a9c4 3448 my $active_chains = iptables_get_chains();
81a0bf43 3449 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, 0);
3fa83edf
DM
3450
3451 my $errors;
3452 foreach my $chain (sort keys %$ruleset) {
3453 my $stat = $statushash->{$chain};
3454 if ($stat->{action} ne 'exists') {
3455 warn "unable to update chain '$chain'\n";
3456 $errors = 1;
3457 }
3458 }
b6360c3f 3459
17da5c0f
AD
3460 my $active_chainsv6 = iptables_get_chains("ip6tables");
3461 my $statushashv6 = get_ruleset_status($rulesetv6, $active_chainsv6, \&iptables_chain_digest, 0);
3462
3463 foreach my $chain (sort keys %$rulesetv6) {
3464 my $stat = $statushashv6->{$chain};
3465 if ($stat->{action} ne 'exists') {
3466 warn "unable to update chain '$chain'\n";
3467 $errors = 1;
3468 }
3469 }
3470
3fa83edf 3471 die "unable to apply firewall changes\n" if $errors;
46a2ac1f
AD
3472
3473 update_nf_conntrack_max($hostfw_conf);
3474
3475 update_nf_conntrack_tcp_timeout_established($hostfw_conf);
3476
b6360c3f
DM
3477}
3478
490cdead
DM
3479sub update_nf_conntrack_max {
3480 my ($hostfw_conf) = @_;
3481
3482 my $max = 65536; # reasonable default
3483
3484 my $options = $hostfw_conf->{options} || {};
3485
3486 if (defined($options->{nf_conntrack_max}) && ($options->{nf_conntrack_max} > $max)) {
3487 $max = $options->{nf_conntrack_max};
3488 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3489 }
3490
3491 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3492 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3493
3494 my $current = int(PVE::Tools::file_read_firstline($filename_nf_conntrack_max) || $max);
3495
3496 if ($current != $max) {
3497 my $hashsize = int($max/4);
3498 PVE::ProcFSTools::write_proc_entry($filename_hashsize, $hashsize);
3499 PVE::ProcFSTools::write_proc_entry($filename_nf_conntrack_max, $max);
3500 }
3501}
3502
28c082a1
AD
3503sub update_nf_conntrack_tcp_timeout_established {
3504 my ($hostfw_conf) = @_;
3505
3506 my $options = $hostfw_conf->{options} || {};
3507
3508 my $value = defined($options->{nf_conntrack_tcp_timeout_established}) ? $options->{nf_conntrack_tcp_timeout_established} : 432000;
3509
3510 PVE::ProcFSTools::write_proc_entry("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3511}
3512
c4a2e5ae
DM
3513sub remove_pvefw_chains {
3514
7b7b2654
AD
3515 PVE::Firewall::remove_pvefw_chains_iptables("iptables");
3516 PVE::Firewall::remove_pvefw_chains_iptables("ip6tables");
3517 PVE::Firewall::remove_pvefw_chains_ipset();
3518
3519}
3520
3521sub remove_pvefw_chains_iptables {
3522 my ($iptablescmd) = @_;
3523
3524 my ($chash, $hooks) = iptables_get_chains($iptablescmd);
c4a2e5ae
DM
3525 my $cmdlist = "*filter\n";
3526
3527 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3528 if ($hooks->{$h}) {
3529 $cmdlist .= "-D $h -j PVEFW-$h\n";
3530 }
3531 }
cbb5d6f3 3532
c4a2e5ae
DM
3533 foreach my $chain (keys %$chash) {
3534 $cmdlist .= "-F $chain\n";
3535 }
3536
3537 foreach my $chain (keys %$chash) {
3538 $cmdlist .= "-X $chain\n";
3539 }
3540 $cmdlist .= "COMMIT\n";
3541
7b7b2654
AD
3542 if($iptablescmd eq "ip6tables") {
3543 ip6tables_restore_cmdlist($cmdlist);
3544 } else {
3545 iptables_restore_cmdlist($cmdlist);
3546 }
3547}
3548
3549sub remove_pvefw_chains_ipset {
55fad3b7
DM
3550
3551 my $ipset_chains = ipset_get_chains();
3552
7b7b2654 3553 my $cmdlist = "";
55fad3b7
DM
3554
3555 foreach my $chain (keys %$ipset_chains) {
88c26d5e
DM
3556 $cmdlist .= "flush $chain\n";
3557 $cmdlist .= "destroy $chain\n";
55fad3b7
DM
3558 }
3559
7b7b2654 3560 ipset_restore_cmdlist($cmdlist) if $cmdlist;
c4a2e5ae
DM
3561}
3562
8b453a09
DM
3563sub init {
3564 my $cluster_conf = load_clusterfw_conf();
3565 my $cluster_options = $cluster_conf->{options};
3566 my $enable = $cluster_options->{enable};
3567
3568 return if !$enable;
3569
3570 # load required modules here
3571}
3572
6b9f68a2 3573sub update {
6b9f68a2 3574 my $code = sub {
3dfa8a7f
DM
3575
3576 my $cluster_conf = load_clusterfw_conf();
3577 my $cluster_options = $cluster_conf->{options};
3578
55fad3b7 3579 if (!$cluster_options->{enable}) {
b22130d3 3580 PVE::Firewall::remove_pvefw_chains();
3dfa8a7f
DM
3581 return;
3582 }
3583
50f9a28d 3584 my $hostfw_conf = load_hostfw_conf($cluster_conf);
3dfa8a7f 3585
638c755a 3586 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile($cluster_conf, $hostfw_conf);
490cdead 3587
17da5c0f 3588 apply_ruleset($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);
6b9f68a2
DM
3589 };
3590
3591 run_locked($code);
3592}
3593
b6360c3f 35941;