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