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