]> git.proxmox.com Git - pve-firewall.git/blob - src/pve-firewall
do not start daemons during installation
[pve-firewall.git] / src / pve-firewall
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use PVE::SafeSyslog;
6 use POSIX ":sys_wait_h";
7 use Fcntl ':flock';
8 use Getopt::Long;
9 use Time::HiRes qw (gettimeofday);
10 use PVE::Tools qw(dir_glob_foreach file_read_firstline);
11 use PVE::INotify;
12 use PVE::Cluster qw(cfs_read_file);
13 use PVE::RPCEnvironment;
14 use PVE::CLIHandler;
15 use PVE::Firewall;
16 use PVE::FirewallSimulator;
17 use Data::Dumper;
18
19 use base qw(PVE::CLIHandler);
20
21 my $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
32 initlog('pve-firewall');
33
34 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
35
36 die "please run as root\n" if $> != 0;
37
38 PVE::INotify::inotify_init();
39
40 my $rpcenv = PVE::RPCEnvironment->init('cli');
41
42 $rpcenv->init_request();
43 $rpcenv->set_language($ENV{LANG});
44 $rpcenv->set_user('root@pam');
45
46 my $nodename = PVE::INotify::nodename();
47
48 my $commandline = [$0, @ARGV];
49
50 $0 = "pve-firewall";
51
52 sub 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
61 PVE::INotify::inotify_close();
62
63 exec (@$commandline);
64 exit (-1); # never reached?
65 }
66
67 sub cleanup {
68 unlink "$pve_firewall_pidfile.lock";
69 unlink $pve_firewall_pidfile;
70 }
71
72 sub 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
90 sub 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
102 my $restart_request = 0;
103 my $next_update = 0;
104
105 my $cycle = 0;
106 my $updatetime = 10;
107
108 my $initial_memory_usage;
109
110 sub 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
123 PVE::Cluster::cfs_update();
124
125 PVE::Firewall::init();
126
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',
264 description => "Stop firewall. This removes all Proxmox VE related iptable rules. The host is unprotected afterwards.",
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',
314 enum => ['unknown', 'stopped', 'running'],
315 },
316 enable => {
317 description => "Firewall is enabled (in 'cluster.fw')",
318 type => 'boolean',
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
337 my $status = $running ? 'running' : 'stopped';
338
339 my $res = { status => $status };
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') {
346
347 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
348
349 $verbose = 0; # do not show iptables details
350 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
351 my ($test, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
352
353 $res->{changes} = ($ipset_changes || $ruleset_changes) ? 1 : 0;
354 }
355
356 return $res;
357 };
358
359 return PVE::Firewall::run_locked($code);
360 }});
361
362 __PACKAGE__->register_method ({
363 name => 'compile',
364 path => 'compile',
365 method => 'GET',
366 description => "Compile and print firewall rules. This is useful for testing.",
367 parameters => {
368 additionalProperties => 0,
369 properties => {},
370 },
371 returns => { type => 'null' },
372
373 code => sub {
374 my ($param) = @_;
375
376 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
377
378 my $code = sub {
379
380 my $verbose = 1;
381
382 my $cluster_conf = PVE::Firewall::load_clusterfw_conf(undef, $verbose);
383 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile($cluster_conf, undef, undef, $verbose);
384
385 my (undef, undef, $ipset_changes) = PVE::Firewall::get_ipset_cmdlist($ipset_ruleset, $verbose);
386 my (undef, $ruleset_changes) = PVE::Firewall::get_ruleset_cmdlist($ruleset, $verbose);
387
388 if ($ipset_changes || $ruleset_changes) {
389 print "detected changes\n";
390 } else {
391 print "no changes\n";
392 }
393 if (!$cluster_conf->{options}->{enable}) {
394 print "firewall disabled\n";
395 }
396
397 };
398
399 PVE::Firewall::run_locked($code);
400
401 return undef;
402 }});
403
404 __PACKAGE__->register_method ({
405 name => 'localnet',
406 path => 'localnet',
407 method => 'GET',
408 description => "Print information about local network.",
409 parameters => {
410 additionalProperties => 0,
411 properties => {},
412 },
413 returns => { type => 'null' },
414 code => sub {
415 my ($param) = @_;
416
417 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
418
419 my $nodename = PVE::INotify::nodename();
420 print "local hostname: $nodename\n";
421
422 my $ip = PVE::Cluster::remote_node_ip($nodename);
423 print "local IP address: $ip\n";
424
425 my $cluster_conf = PVE::Firewall::load_clusterfw_conf();
426
427 my $localnet = PVE::Firewall::local_network() || '127.0.0.0/8';
428 print "network auto detect: $localnet\n";
429 if ($cluster_conf->{aliases}->{local_network}) {
430 print "using user defined local_network: $cluster_conf->{aliases}->{local_network}->{cidr}\n";
431 } else {
432 print "using detected local_network: $localnet\n";
433 }
434
435 return undef;
436 }});
437
438 __PACKAGE__->register_method ({
439 name => 'simulate',
440 path => 'simulate',
441 method => 'GET',
442 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.",
443 parameters => {
444 additionalProperties => 0,
445 properties => {
446 verbose => {
447 description => "Verbose output.",
448 type => 'boolean',
449 optional => 1,
450 default => 0,
451 },
452 from => {
453 description => "Source zone.",
454 type => 'string',
455 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
456 optional => 1,
457 default => 'outside',
458 },
459 to => {
460 description => "Destination zone.",
461 type => 'string',
462 pattern => '(host|outside|vm\d+|ct\d+|vmbr\d+/\S+)',
463 optional => 1,
464 default => 'host',
465 },
466 protocol => {
467 description => "Protocol.",
468 type => 'string',
469 pattern => '(tcp|udp)',
470 optional => 1,
471 default => 'tcp',
472 },
473 dport => {
474 description => "Destination port.",
475 type => 'integer',
476 minValue => 1,
477 maxValue => 65535,
478 optional => 1,
479 },
480 sport => {
481 description => "Source port.",
482 type => 'integer',
483 minValue => 1,
484 maxValue => 65535,
485 optional => 1,
486 },
487 source => {
488 description => "Source IP address.",
489 type => 'string', format => 'ipv4',
490 optional => 1,
491 },
492 dest => {
493 description => "Destination IP address.",
494 type => 'string', format => 'ipv4',
495 optional => 1,
496 },
497 },
498 },
499 returns => { type => 'null' },
500 code => sub {
501 my ($param) = @_;
502
503 local $SIG{'__WARN__'} = 'DEFAULT'; # do not fill up syslog
504
505 my ($ruleset, $ipset_ruleset) = PVE::Firewall::compile(undef, undef, undef, $param->{verbose});
506
507 PVE::FirewallSimulator::debug($param->{verbose} || 0);
508
509 my $host_ip = PVE::Cluster::remote_node_ip($nodename);
510
511 PVE::FirewallSimulator::reset_trace();
512 print Dumper($ruleset) if $param->{verbose};
513
514 my $test = {
515 from => $param->{from},
516 to => $param->{to},
517 proto => $param->{protocol} || 'tcp',
518 source => $param->{source},
519 dest => $param->{dest},
520 dport => $param->{dport},
521 sport => $param->{sport},
522 };
523
524 if (!defined($test->{to})) {
525 $test->{to} = 'host';
526 PVE::FirewallSimulator::add_trace("Set Zone: to => '$test->{to}'\n");
527 }
528 if (!defined($test->{from})) {
529 $test->{from} = 'outside',
530 PVE::FirewallSimulator::add_trace("Set Zone: from => '$test->{from}'\n");
531 }
532
533 my $vmdata = PVE::Firewall::read_local_vm_config();
534
535 print "Test packet:\n";
536
537 foreach my $k (qw(from to proto source dest dport sport)) {
538 printf(" %-8s: %s\n", $k, $test->{$k}) if defined($test->{$k});
539 }
540
541 $test->{action} = 'QUERY';
542
543 my $res = PVE::FirewallSimulator::simulate_firewall($ruleset, $ipset_ruleset,
544 $host_ip, $vmdata, $test);
545
546 print "ACTION: $res\n";
547
548 return undef;
549 }});
550
551 my $cmddef = {
552 start => [ __PACKAGE__, 'start', []],
553 stop => [ __PACKAGE__, 'stop', []],
554 compile => [ __PACKAGE__, 'compile', []],
555 simulate => [ __PACKAGE__, 'simulate', []],
556 localnet => [ __PACKAGE__, 'localnet', []],
557 status => [ __PACKAGE__, 'status', [], undef, sub {
558 my $res = shift;
559 my $status = ($res->{enable} ? "enabled" : "disabled") . '/' . $res->{status};
560
561 if ($res->{changes}) {
562 print "Status: $status (pending changes)\n";
563 } else {
564 print "Status: $status\n";
565 }
566 }],
567 };
568
569 my $cmd = shift;
570
571 PVE::CLIHandler::handle_cmd($cmddef, $0, $cmd, \@ARGV, undef, $0);
572
573 exit (0);
574
575 __END__
576
577 =head1 NAME
578
579 pve-firewall - PVE Firewall Daemon
580
581 =head1 SYNOPSIS
582
583 =include synopsis
584
585 =head1 DESCRIPTION
586
587 This service updates iptables rules periodically.
588
589 =include pve_copyright