]> git.proxmox.com Git - pve-firewall.git/blame - src/pve-firewall
add debian/dirs file to install /var/lib/pve-firewall
[pve-firewall.git] / src / pve-firewall
CommitLineData
e2beb7aa
DM
1#!/usr/bin/perl
2
3use strict;
4use warnings;
5use PVE::SafeSyslog;
6use POSIX ":sys_wait_h";
7use Fcntl ':flock';
8use Getopt::Long;
9use Time::HiRes qw (gettimeofday);
10use PVE::Tools qw(dir_glob_foreach file_read_firstline);
11use PVE::INotify;
12use PVE::Cluster qw(cfs_read_file);
13use PVE::RPCEnvironment;
14use PVE::CLIHandler;
15use PVE::Firewall;
814de832
DM
16use PVE::FirewallSimulator;
17use Data::Dumper;
e2beb7aa
DM
18
19use base qw(PVE::CLIHandler);
20
21my $pve_firewall_pidfile = "/var/run/pve-firewall.pid";
22
23$SIG{'__WARN__'} = sub {
24 my $err = $@;
25 my $t = $_[0];
26 chomp $t;
27 print "$t\n";
28 syslog('warning', "WARNING: %s", $t);
29 $@ = $err;
30};
31
32initlog('pve-firewall');
33
34$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
35
36die "please run as root\n" if $> != 0;
37
38PVE::INotify::inotify_init();
39
40my $rpcenv = PVE::RPCEnvironment->init('cli');
41
42$rpcenv->init_request();
43$rpcenv->set_language($ENV{LANG});
44$rpcenv->set_user('root@pam');
45
814de832
DM
46my $nodename = PVE::INotify::nodename();
47
e2beb7aa
DM
48my $commandline = [$0, @ARGV];
49
50$0 = "pve-firewall";
51
52sub restart_server {
53 my ($waittime) = @_;
54
55 syslog('info', "server shutdown (restart)");
56
57 $ENV{RESTART_PVE_FIREWALL} = 1;
58
59 sleep($waittime) if $waittime; # avoid high server load due to restarts
60
3e998704
DM
61 PVE::INotify::inotify_close();
62
e2beb7aa
DM
63 exec (@$commandline);
64 exit (-1); # never reached?
65}
66
67sub cleanup {
68 unlink "$pve_firewall_pidfile.lock";
69 unlink $pve_firewall_pidfile;
70}
71
72sub lockpidfile {
73 my $pidfile = shift;
74 my $lkfn = "$pidfile.lock";
75
76 if (!open (FLCK, ">>$lkfn")) {
77 my $msg = "can't aquire lock on file '$lkfn' - $!";
78 syslog ('err', $msg);
79 die "ERROR: $msg\n";
80 }
81
82 if (!flock (FLCK, LOCK_EX|LOCK_NB)) {
83 close (FLCK);
84 my $msg = "can't aquire lock '$lkfn' - $!";
85 syslog ('err', $msg);
86 die "ERROR: $msg\n";
87 }
88}
89
90sub writepidfile {
91 my $pidfile = shift;
92
93 if (!open (PIDFH, ">$pidfile")) {
94 my $msg = "can't open pid file '$pidfile' - $!";
95 syslog ('err', $msg);
96 die "ERROR: $msg\n";
97 }
98 print PIDFH "$$\n";
99 close (PIDFH);
100}
101
102my $restart_request = 0;
103my $next_update = 0;
104
105my $cycle = 0;
106my $updatetime = 10;
107
108my $initial_memory_usage;
109
110sub run_server {
111 my ($param) = @_;
112
113 # try to get the lock
114 lockpidfile($pve_firewall_pidfile);
115
116 # run in background
117 my $spid;
118
119 my $restart = $ENV{RESTART_PVE_FIREWALL};
120
121 delete $ENV{RESTART_PVE_FIREWALL};
122
8b453a09
DM
123 PVE::Cluster::cfs_update();
124
125 PVE::Firewall::init();
126
e2beb7aa
DM
127 if (!$param->{debug}) {
128 open STDIN, '</dev/null' || die "can't read /dev/null";
129 open STDOUT, '>/dev/null' || die "can't write /dev/null";
130 }
131
132 if (!$restart && !$param->{debug}) {
133 $spid = fork();
134 if (!defined ($spid)) {
135 my $msg = "can't put server into background - fork failed";
136 syslog('err', $msg);
137 die "ERROR: $msg\n";
138 } elsif ($spid) { # parent
139 exit (0);
140 }
141 }
142
143 writepidfile($pve_firewall_pidfile);
144
145 open STDERR, '>&STDOUT' || die "can't close STDERR\n";
146
147 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = sub {
148 syslog('info' , "server closing");
149
150 $SIG{INT} = 'DEFAULT';
151
152 # wait for children
153 1 while (waitpid(-1, POSIX::WNOHANG()) > 0);
154
155 syslog('info' , "clear firewall rules");
156 eval { PVE::Firewall::remove_pvefw_chains(); die "STOP";};
157 warn $@ if $@;
158
159 cleanup();
160
161 exit (0);
162 };
163
164 $SIG{HUP} = sub {
165 # wake up process, so this forces an immediate firewall rules update
166 syslog('info' , "received signal HUP (restart)");
167 $restart_request = 1;
168 };
169
170 if ($restart) {
171 syslog('info' , "restarting server");
172 } else {
173 syslog('info' , "starting server");
174 }
175
176 for (;;) { # forever
177
178 eval {
179
180 local $SIG{'__WARN__'} = 'IGNORE'; # do not fill up logs
181
182 $next_update = time() + $updatetime;
183
184 my ($ccsec, $cusec) = gettimeofday ();
185 eval {
186 PVE::Cluster::cfs_update();
187 PVE::Firewall::update();
188 };
189 my $err = $@;
190
191 if ($err) {
192 syslog('err', "status update error: $err");
193 }
194
195 my ($ccsec_end, $cusec_end) = gettimeofday ();
196 my $cptime = ($ccsec_end-$ccsec) + ($cusec_end - $cusec)/1000000;
197
198 syslog('info', sprintf("firewall update time (%.3f seconds)", $cptime))
199 if ($cptime > 5);
200
201 $cycle++;
202
203 my $mem = PVE::ProcFSTools::read_memory_usage();
204
205 if (!defined($initial_memory_usage) || ($cycle < 10)) {
206 $initial_memory_usage = $mem->{resident};
207 } else {
208 my $diff = $mem->{resident} - $initial_memory_usage;
209 if ($diff > 5*1024*1024) {
210 syslog ('info', "restarting server after $cycle cycles to " .
211 "reduce memory usage (free $mem->{resident} ($diff) bytes)");
212 restart_server();
213 }
214 }
215
216 my $wcount = 0;
217 while ((time() < $next_update) &&
218 ($wcount < $updatetime) && # protect against time wrap
219 !$restart_request) { $wcount++; sleep (1); };
220
221 restart_server() if $restart_request;
222 };
223
224 my $err = $@;
225
226 if ($err) {
227 syslog ('err', "ERROR: $err");
228 restart_server(5);
229 exit (0);
230 }
231 }
232}
233
234__PACKAGE__->register_method ({
235 name => 'start',
236 path => 'start',
237 method => 'POST',
238 description => "Start the Proxmox VE firewall service.",
239 parameters => {
240 additionalProperties => 0,
241 properties => {
242 debug => {
243 description => "Debug mode - stay in foreground",
244 type => "boolean",
245 optional => 1,
246 default => 0,
247 },
248 },
249 },
250 returns => { type => 'null' },
251
252 code => sub {
253 my ($param) = @_;
254
255 run_server($param);
256
257 return undef;
258 }});
259
260__PACKAGE__->register_method ({
261 name => 'stop',
262 path => 'stop',
263 method => 'POST',
16adff04 264 description => "Stop firewall. This removes all Proxmox VE related iptable rules. The host is unprotected afterwards.",
e2beb7aa
DM
265 parameters => {
266 additionalProperties => 0,
267 properties => {},
268 },
269 returns => { type => 'null' },
270
271 code => sub {
272 my ($param) = @_;
273
274 my $pid = int(PVE::Tools::file_read_firstline($pve_firewall_pidfile) || 0);
275
276 if ($pid) {
277 if (PVE::ProcFSTools::check_process_running($pid)) {
278 kill(15, $pid); # send TERM signal
279 # give max 5 seconds to shut down
280 for (my $i = 0; $i < 5; $i++) {
281 last if !PVE::ProcFSTools::check_process_running($pid);
282 sleep (1);
283 }
284
285 # to be sure
286 kill(9, $pid);
287 waitpid($pid, 0);
288 }
289 if (-f $pve_firewall_pidfile) {
290 # try to get the lock
291 lockpidfile($pve_firewall_pidfile);
292 cleanup();
293 }
294 }
295
296 return undef;
297 }});
298
299__PACKAGE__->register_method ({
300 name => 'status',
301 path => 'status',
302 method => 'GET',
303 description => "Get firewall status.",
304 parameters => {
305 additionalProperties => 0,
306 properties => {},
307 },
308 returns => {
309 type => 'object',
310 additionalProperties => 0,
311 properties => {
312 status => {
313 type => 'string',
55fad3b7
DM
314 enum => ['unknown', 'stopped', 'running'],
315 },
316 enable => {
317 description => "Firewall is enabled (in 'cluster.fw')",
318 type => 'boolean',
e2beb7aa
DM
319 },
320 changes => {
321 description => "Set when there are pending changes.",
322 type => 'boolean',
323 optional => 1,
324 }
325 },
326 },
327 code => sub {
328 my ($param) = @_;
329
330 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
331
332 my $code = sub {
333
334 my $pid = int(PVE::Tools::file_read_firstline($pve_firewall_pidfile) || 0);
335 my $running = PVE::ProcFSTools::check_process_running($pid);
336
55fad3b7 337 my $status = $running ? 'running' : 'stopped';
e2beb7aa
DM
338
339 my $res = { status => $status };
55fad3b7
DM
340
341 my $verbose = 1; # show syntax errors
342 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
343 $res->{enable} = $cluster_conf->{options}->{enable} ? 1 : 0;
344
345 if ($status eq 'running') {
d4cda423 346
638c755a 347 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
e2beb7aa 348
d4cda423
DM
349 $verbose = 0; # do not show iptables details
350 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
55fad3b7 351 my ($test, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
17da5c0f
AD
352 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
353
354 $res->{changes} = ($ipset_changes || $ruleset_changes || $ruleset_changesv6) ? 1 : 0;
e2beb7aa
DM
355 }
356
357 return $res;
358 };
359
360 return PVE::Firewall::run_locked($code);
361 }});
362
363__PACKAGE__->register_method ({
364 name => 'compile',
365 path => 'compile',
3324948a 366 method => 'GET',
16adff04 367 description => "Compile and print firewall rules. This is useful for testing.",
e2beb7aa
DM
368 parameters => {
369 additionalProperties => 0,
370 properties => {},
371 },
372 returns => { type => 'null' },
373
374 code => sub {
375 my ($param) = @_;
376
377 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
378
379 my $code = sub {
e2beb7aa 380
d4cda423
DM
381 my $verbose = 1;
382
55fad3b7 383 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
638c755a 384 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
d4cda423 385
1cc9bd90 386 print "ipset cmdlist:\n";
d4cda423 387 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
1cc9bd90
DM
388
389 print "\niptables cmdlist:\n";
d4cda423 390 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
1cc9bd90
DM
391
392 print "\nip6tables cmdlist:\n";
17da5c0f 393 my (undef, $ruleset_changesv6) = PVE::Firewall::get_ruleset_cmdlist($rulesetv6, $verbose, "ip6tables");
55fad3b7 394
17da5c0f 395 if ($ipset_changes || $ruleset_changes || $ruleset_changesv6) {
e2beb7aa
DM
396 print "detected changes\n";
397 } else {
398 print "no changes\n";
399 }
55fad3b7
DM
400 if (!$cluster_conf->{options}->{enable}) {
401 print "firewall disabled\n";
402 }
403
e2beb7aa
DM
404 };
405
406 PVE::Firewall::run_locked($code);
407
408 return undef;
409 }});
410
e7fb6ff2
DM
411__PACKAGE__->register_method ({
412 name => 'localnet',
413 path => 'localnet',
414 method => 'GET',
415 description => "Print information about local network.",
416 parameters => {
417 additionalProperties => 0,
418 properties => {},
419 },
420 returns => { type => 'null' },
421 code => sub {
422 my ($param) = @_;
423
424 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
425
426 my $nodename = PVE::INotify::nodename();
427 print "local hostname: $nodename\n";
428
429 my $ip = PVE::Cluster::remote_node_ip($nodename);
430 print "local IP address: $ip\n";
431
432 my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
433
434 my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
435 print "network auto detect: $localnet\n";
436 if ($cluster_conf->{aliases}->{local_network}) {
437 print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
438 } else {
439 print "using detected local_network: $localnet\n";
440 }
441
442 return undef;
443 }});
444
814de832
DM
445__PACKAGE__->register_method ({
446 name => 'simulate',
447 path => 'simulate',
3324948a 448 method => 'GET',
c9902e5a 449 description => "Simulate firewall rules. This does not simulate kernel 'routing' table. Instead, this simply assumes that routing from source zone to destination zone is possible.",
814de832
DM
450 parameters => {
451 additionalProperties => 0,
452 properties => {
453 verbose => {
454 description => "Verbose output.",
455 type => 'boolean',
456 optional => 1,
457 default => 0,
458 },
459 from => {
460 description => "Source zone.",
461 type => 'string',
462 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
463 optional => 1,
464 default => 'outside',
465 },
466 to => {
467 description => "Destination zone.",
468 type => 'string',
469 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
470 optional => 1,
471 default => 'host',
472 },
473 protocol => {
474 description => "Protocol.",
475 type => 'string',
476 pattern => '(tcp|udp)',
477 optional => 1,
478 default => 'tcp',
479 },
480 dport => {
481 description => "Destination port.",
482 type => 'integer',
483 minValue => 1,
484 maxValue => 65535,
485 optional => 1,
486 },
487 sport => {
488 description => "Source port.",
489 type => 'integer',
490 minValue => 1,
491 maxValue => 65535,
492 optional => 1,
493 },
494 source => {
495 description => "Source IP address.",
496 type => 'string', format => 'ipv4',
497 optional => 1,
498 },
499 dest => {
500 description => "Destination IP address.",
501 type => 'string', format => 'ipv4',
502 optional => 1,
503 },
504 },
505 },
506 returns => { type => 'null' },
507 code => sub {
508 my ($param) = @_;
509
815b4ebf
DM
510 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
511
638c755a 512 my ($ruleset, $ipset_ruleset, $rulesetv6) = PVE::Firewall::compile(undef, undef, undef, $param->{verbose});
814de832
DM
513
514 PVE::FirewallSimulator::debug($param->{verbose} || 0);
515
516 my $host_ip = PVE::Cluster::remote_node_ip($nodename);
517
518 PVE::FirewallSimulator::reset_trace();
519 print Dumper($ruleset) if $param->{verbose};
520
521 my $test = {
522 from => $param->{from},
523 to => $param->{to},
524 proto => $param->{protocol} || 'tcp',
525 source => $param->{source},
526 dest => $param->{dest},
527 dport => $param->{dport},
528 sport => $param->{sport},
529 };
530
531 if (!defined($test->{to})) {
532 $test->{to} = 'host';
533 PVE::FirewallSimulator::add_trace("Set Zone: to => '$test->{to}'\n");
534 }
535 if (!defined($test->{from})) {
536 $test->{from} = 'outside',
537 PVE::FirewallSimulator::add_trace("Set Zone: from => '$test->{from}'\n");
538 }
539
540 my $vmdata = PVE::Firewall::read_local_vm_config();
541
542 print "Test packet:\n";
543
544 foreach my $k (qw(from to proto source dest dport sport)) {
545 printf(" %-8s: %s\n", $k, $test->{$k}) if defined($test->{$k});
546 }
547
548 $test->{action} = 'QUERY';
549
550 my $res = PVE::FirewallSimulator::simulate_firewall($ruleset, $ipset_ruleset,
551 $host_ip, $vmdata, $test);
552
553 print "ACTION: $res\n";
554
555 return undef;
556 }});
e2beb7aa
DM
557
558my $cmddef = {
559 start => [ __PACKAGE__, 'start', []],
560 stop => [ __PACKAGE__, 'stop', []],
561 compile => [ __PACKAGE__, 'compile', []],
814de832 562 simulate => [ __PACKAGE__, 'simulate', []],
e7fb6ff2 563 localnet => [ __PACKAGE__, 'localnet', []],
e2beb7aa
DM
564 status => [ __PACKAGE__, 'status', [], undef, sub {
565 my $res = shift;
55fad3b7
DM
566 my $status = ($res->{enable} ? "enabled" : "disabled") . '/' . $res->{status};
567
e2beb7aa 568 if ($res->{changes}) {
55fad3b7 569 print "Status: $status (pending changes)\n";
e2beb7aa 570 } else {
55fad3b7 571 print "Status: $status\n";
e2beb7aa
DM
572 }
573 }],
574 };
575
576my $cmd = shift;
577
578PVE::CLIHandler::handle_cmd($cmddef, $0, $cmd, \@ARGV, undef, $0);
579
580exit (0);
581
582__END__
583
584=head1 NAME
585
16adff04 586pve-firewall - PVE Firewall Daemon
e2beb7aa
DM
587
588=head1 SYNOPSIS
589
16adff04 590=include synopsis
e2beb7aa
DM
591
592=head1 DESCRIPTION
593
594This service updates iptables rules periodically.
595
16adff04 596=include pve_copyright