blib/lib/Ereshkigal.pm

filter: Statementstmt 5.3% 34 / 636 Branchbran 0.0% 0 / 300 Conditioncond 0.0% 0 / 135 MC/DCmcdc 0.0% 0 / 80 Subroutinesub 16.9% 11 / 65 Podpod 100% 5 / 5 totaltotal 4.1% 50 / 1221 CC 219 SCAR 55.9
CC
219
Cov
3%
new
992.0
_check_kur_def
812.0
_build_kur_cmd
342.0
CRAP 266.4
↑ Summary blib/lib/Ereshkigal/Kur.pm »
1 package Ereshkigal;
2  
3 3 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use base 'Error::Helper';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use FindBin ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use POE qw( Wheel::Run );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use POE::Component::Server::JSONUnix ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use TOML::Tiny qw( from_toml );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Ereshkigal::Client ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Ereshkigal::IP qw( normalize_ip normalize_cidr );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Ereshkigal::LogDrek qw( log_drek );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 =head1 NAME
16  
17 Ereshkigal - Handle firewall or similar bans.
18  
19 =head1 VERSION
20  
21 Version 0.0.1
22  
23 =cut
24  
25 3 our $VERSION = '0.0.1';
26  
27 =head1 SYNOPSIS
28  
29 use Ereshkigal;
30  
31 my $ereshkigal = Ereshkigal->new( config => '/usr/local/etc/ereshkigal.toml' );
32  
33 $ereshkigal->start_server;
34  
35 Ereshkigal is a ban manager for firewalls. It wrangles various
36 L<Ereshkigal::Kur> instances, spawned via the C<kur> bin, each of which runs
37 as its own process and uses L<Net::Firewall::BlockerHelper> for talking to
38 the firewall.
39  
40 The manager listens on a unix socket, by default
41 C</var/run/ereshkigal/socket>, speaking the newline delimited JSON protocol
42 of L<POE::Component::Server::JSONUnix>, and proxies per instance work to the
43 kur sockets under C</var/run/ereshkigal/kur/>.
44  
45 =head1 CONFIG FILE
46  
47 The config file is TOML. Hashes under C<kur> define instances. The instance
48 name is the hash name, so the hash at C<kur.sshd> is the kur instance
49 C<sshd>. Keys inside are what kur/L<Net::Firewall::BlockerHelper> take...
50 C<backend>, C<ports>, C<protocols>, C<prefix>, C<self_heal>, and the backend
51 specific C<options> table.
52  
53 Values in the C<options> table must be plain scalars, with one exception...
54 C<interfaces>, which backends such as xdp want as an array, may be given as
55 one. Any other array or table valued option is refused at config load rather
56 than being handed to the backend as a stringified ref.
57  
58 Top level keys are manager settings.
59  
60 - socket_group :: Group ownership of the manager socket.
61 Default :: the default group of the root user
62  
63 - socket_mode :: Perms for the manager socket. Processed via oct, so
64 should be specified as a string such as "0660". Kur sockets are
65 always 0600 and not configurable.
66 Default :: 0660
67  
68 - run_base_dir :: Base dir for run files.
69 Default :: /var/run/ereshkigal
70  
71 - cache_base_dir :: Base dir for cache files, passed to kur.
72 Default :: /var/cache/ereshkigal
73  
74 - kur_bin :: The kur bin to spawn instances with.
75 Default :: kur
76  
77 - timeout :: Timeout in seconds used when talking to kur sockets. For
78 commands touching multiple kurs this bounds the whole fan out
79 rather than each kur individually.
80 Default :: 30
81  
82 - ban_time :: How long bans should last in seconds. 0 means bans never
83 time out. May be overridden per kur via ban_time in its hash and
84 per ban request.
85 Default :: 600
86  
87 - checkpoint :: Seconds between periodic rewrites of each kur's ban
88 state CSV. 0 disables the periodic rewrite... ban/unban, stop,
89 and on demand checkpoints still happen. May be overridden per kur
90 via checkpoint in its hash.
91 Default :: 60
92  
93 - enable_cidr :: Whether CIDR banning is enabled. May be overridden per
94 kur via enable_cidr in its hash. Even when set, the cidr_ban and
95 cidr_unban commands only work on a kur whose backend supports CIDR
96 bans.
97 Default :: false
98  
99 - cidr_silent_drop :: How a kur handles a CIDR command when CIDR banning
100 is not available for it, either because enable_cidr is off or the
101 backend cannot do CIDR. When set such a kur silently drops the
102 command rather than erroring, which keeps a fan out across a mix of
103 CIDR capable and incapable kurs from being spoiled by the incapable
104 ones. May be overridden per kur via cidr_silent_drop in its hash.
105 Default :: false
106  
107 - enable_auth :: Enables the L<POE::Component::Server::JSONUnix>
108 auth_required cookie file ownership challenge on the manager
109 socket, along with authorization via authed_users/authed_groups.
110 Default :: 0
111  
112 - authed_users :: An array of users with global access.
113 Default :: []
114  
115 - authed_groups :: An array of groups with global access.
116 Default :: []
117  
118 - auth_temp_dir :: Dir used for the ownership challenge cookie files,
119 passed through to L<POE::Component::Server::JSONUnix>.
120 Default :: undef
121  
122 A kur hash may instead carry C<fan_out>, an array of other kur names, in
123 place of C<backend>. Such a kur is manager side only... no process and no
124 socket of its own. Commands targeted at it (C<ban> and C<cidr_ban> with
125 args.kur, C<checkpoint>, C<re_init>, and C<clear_retries> with args.kur,
126 and C<status_kur>) fan out to its members instead, making it usable as a
127 single point of contact for driving a whole set of kurs. With enable_auth
128 on, authorization for a command targeted at a fan_out kur is checked
129 against the fan_out kur's own lists rather than its members', so an
130 integration may be granted just the gate without being listed on any
131 member. Members must be defined non fan_out kurs... fan_out kurs may not
132 nest. Untargeted commands (C<ban> and C<cidr_ban> without args.kur,
133 C<unban>, C<cidr_unban>, C<banned>, and C<checkpoint>, C<re_init>, and
134 C<clear_retries> without args.kur) touch only real kurs, never fan_out
135 ones.
136  
137 [kur.baphomet]
138 fan_out = [ "sshd", "smtp" ]
139 authed_users = [ "baphomet" ]
140  
141 Each kur hash may also carry its own C<authed_users>/C<authed_groups>,
142 which expand upon the global ones for that kur... the effective lists for
143 a kur are the global ones plus its own. A command must be authorized for
144 every kur it touches, with untargeted fan-out commands touching every kur,
145 while commands about the manager itself (stop, add_kur, remove_kur, and
146 the whole manager views status/status_all) require the global lists. UID 0
147 is always authorized. The kur backends do no checking at all... their
148 sockets are 0600 and only ereshkigal is expected to be able to write to
149 them, so enforcement is entirely the manager's responsibility.
150  
151 A refused command comes back as a normal JSONUnix error response carrying
152 a machine-readable C<code>, C<permission_denied> for an authorization
153 refusal, matching the C<code> field convention of
154 L<POE::Component::Server::JSONUnix>'s own permission and auth errors, so a
155 consumer may branch on the code rather than matching the message text.
156  
157 Example...
158  
159 socket_group = "wheel"
160 socket_mode = "0660"
161  
162 [kur.sshd]
163 backend = "ipfw"
164 ports = [ "22" ]
165 protocols = [ "tcp" ]
166  
167 =head1 METHODS
168  
169 =head2 new
170  
171 Initiates the object. All errors are considered fatal, meaning if new fails
172 it will die.
173  
174 - config :: Path to the TOML config file.
175 Default :: /usr/local/etc/ereshkigal.toml
176  
177 =cut
178  
179 0 ▶sub new {
Subroutine new: not called CC=31 SCAR=69.0
Pod documented
180 0 my ( $blank, %opts ) = @_;
181  
182 0 my $self = {
183 perror => undef,
184 error => undef,
185 errorLine => undef,
186 errorFilename => undef,
187 errorString => "",
188 errorExtra => {
189 all_errors_fatal => 1,
190 all_fatal => 1,
191 flags => {
192 1 => 'configReadFailed',
193 2 => 'configParseFailed',
194 3 => 'invalidKurDef',
195 4 => 'runBaseDirError',
196 5 => 'badSocketGroup',
197 6 => 'invalidBanTime',
198 7 => 'invalidCheckpoint',
199 8 => 'invalidAuthedList',
200 },
201 fatal_flags => {},
202 perror_not_fatal => 0,
203 },
204 config => '/usr/local/etc/ereshkigal.toml',
205 run_base_dir => '/var/run/ereshkigal',
206 cache_base_dir => '/var/cache/ereshkigal',
207 kur_bin => 'kur',
208 timeout => 30,
209 ban_time => 600,
210 checkpoint => 60,
211 enable_cidr => 0,
212 cidr_silent_drop => 0,
213 enable_auth => 0,
214 authed_users => [],
215 authed_groups => [],
216 auth_temp_dir => undef,
217 socket_group => undef,
218 socket_mode => oct('0660'),
219 kurs => {},
220 wheel_to_kur => {},
221 pid_to_kur => {},
222 shutting_down => 0,
223 started => undef,
224 server => undef,
225 };
226 0 bless $self;
227  
228 0 ▶ if ( defined( $opts{config} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"config"}) 0 0 0
229 0 $self->{config} = $opts{config};
230 }
231  
232 0 my $raw_config;
233 {
234 0 local $/ = undef;
235 0 my $fh;
236 0 ▶ if ( !open( $fh, '<', $self->{config} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, "<", $self->{"config"}) 0 0 0
237 0 $self->{perror} = 1;
238 0 $self->{error} = 1;
239 0 $self->{errorString} = 'Failed to open the config, "' . $self->{config} . '"... ' . $!;
240 0 $self->warn;
241 }
242 0 $raw_config = <$fh>;
243 0 close($fh);
244 }
245  
246 0 my ( $config, $parse_error ) = from_toml($raw_config);
247 0 ▶ if ( !defined($config) || ref($config) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $config or ref $config ne "HASH") 0 0 0
Condition0%0/3
not defined $config or ref $config ne "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $config or ref $config ne "HASH"
not defined $config ref $config ne "HASH"
Truth table0%0/3
not(A) or B
A= not defined $configB= ref $config ne "HASH"
ABresult
1X1
011
000
248 0 $self->{perror} = 1;
249 0 $self->{error} = 2;
250 $self->{errorString}
251 = 'Failed to parse the config, "'
252 0 ▶ . $self->{config} . '"... '
Branch: 1 branch
BranchTrueFalseTotal
defined $parse_error ? : 0 0 0
253 . ( defined($parse_error) ? $parse_error : 'parsing did not return a hash' );
254 0 $self->warn;
255 }
256  
257 0 my @settings_to_merge = (
258 'run_base_dir', 'cache_base_dir', 'kur_bin', 'timeout',
259 'ban_time', 'checkpoint', 'enable_cidr', 'cidr_silent_drop',
260 'enable_auth', 'auth_temp_dir', 'socket_group'
261 );
262 0 foreach my $item (@settings_to_merge) {
263 0 ▶ if ( defined( $config->{$item} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{$item}) 0 0 0
264 0 $self->{$item} = $config->{$item};
265 }
266 }
267 0 ▶ if ( defined( $config->{socket_mode} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"socket_mode"}) 0 0 0
268 # vetted before oct is trusted with it, as oct hands back 0 for
269 # anything unparseable, which would leave the socket unusable by
270 # everyone rather than erroring
271 0 ▶ if ( '' . $config->{socket_mode} !~ /^0[0-7]{1,4}$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ('' . !($config->{"socket_mode"} =~ /^0[0-7]{1,4}$/)) 0 0 0
272 0 $self->{perror} = 1;
273 0 $self->{error} = 2;
274 $self->{errorString}
275 0 = 'socket_mode, "' . $config->{socket_mode} . '", is not an octal mode string such as "0660"';
276 0 $self->warn;
277 }
278 0 $self->{socket_mode} = oct( '' . $config->{socket_mode} );
279 } ## end if ( defined( $config->{socket_mode} ) )
280  
281 # A bare kur_bin (no path separator) is resolved against the directory
282 # ereshkigal was invoked from, since kur is installed alongside it. This
283 # avoids relying on $PATH, which is stripped down under service managers
284 # such as FreeBSD's rc.subr (no /usr/local/bin) and would otherwise make
285 # exec of the kur bin fail with "No such file or directory".
286 0 ▶ if ( $self->{kur_bin} !~ m{/} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"kur_bin"} =~ m[/]) 0 0 0
287 0 my $sibling = $FindBin::RealBin . '/' . $self->{kur_bin};
288 0 ▶ if ( -x $sibling ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-x $sibling) 0 0 0
289 0 $self->{kur_bin} = $sibling;
290 }
291 }
292  
293 0 ▶ if ( $self->{ban_time} !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"ban_time"} =~ /^[0-9]+$/) 0 0 0
294 0 $self->{perror} = 1;
295 0 $self->{error} = 6;
296 0 $self->{errorString} = 'ban_time, "' . $self->{ban_time} . '", is not a non-negative int of seconds';
297 0 $self->warn;
298 }
299  
300 0 ▶ if ( $self->{checkpoint} !~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"checkpoint"} =~ /^[0-9]+$/) 0 0 0
301 0 $self->{perror} = 1;
302 0 $self->{error} = 7;
303 0 $self->{errorString} = 'checkpoint, "' . $self->{checkpoint} . '", is not a non-negative int of seconds';
304 0 $self->warn;
305 }
306  
307 0 foreach my $item ( 'authed_users', 'authed_groups' ) {
308 0 ▶ if ( defined( $config->{$item} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{$item}) 0 0 0
309 0 my $list_error = _authed_list_error( $config->{$item} );
310 0 ▶ if ( defined($list_error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $list_error) 0 0 0
311 0 $self->{perror} = 1;
312 0 $self->{error} = 8;
313 0 $self->{errorString} = $item . ' is ' . $list_error;
314 0 $self->warn;
315 }
316 0 $self->{$item} = $config->{$item};
317 } ## end if ( defined( $config->{$item} ) )
318 } ## end foreach my $item ( 'authed_users', 'authed_groups')
319  
320 # default to the default group of the root user... wheel on the BSDs, root on Linux
321 0 ▶ if ( !defined( $self->{socket_group} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{'socket_group'}) { } 0 0 0
322 0 $self->{socket_gid} = ( getpwnam('root') )[3];
323 } else {
324 0 $self->{socket_gid} = getgrnam( $self->{socket_group} );
325 }
326 0 ▶ if ( !defined( $self->{socket_gid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"socket_gid"}) 0 0 0
327 0 $self->{perror} = 1;
328 0 $self->{error} = 5;
329 $self->{errorString}
330 = 'Failed to resolve the socket group'
331 0 ▶ . ( defined( $self->{socket_group} ) ? ', "' . $self->{socket_group} . '",' : ' for the root user' )
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'socket_group'} ? : 0 0 0
332 . ' to a GID';
333 0 $self->warn;
334 }
335  
336 0 ▶ if ( defined( $config->{kur} ) && ref( $config->{kur} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"kur"} and ref $config->{"kur"} ne "HASH") 0 0 0
Condition0%0/3
defined $config->{"kur"} and ref $config->{"kur"} ne "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $config->{"kur"} and ref $config->{"kur"} ne "HASH"
defined $config->{"kur"} ref $config->{"kur"} ne "HASH"
Truth table0%0/3
A and B
A= defined $config->{"kur"}B= ref $config->{"kur"} ne "HASH"
ABresult
0X0
100
111
337 0 $self->{perror} = 1;
338 0 $self->{error} = 3;
339 0 $self->{errorString} = 'kur in the config is defined but not a hash';
340 0 $self->warn;
341 }
342 0 ▶ if ( defined( $config->{kur} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"kur"}) 0 0 0
343 0 foreach my $name ( keys( %{ $config->{kur} } ) ) {
344 0 my $def = $config->{kur}{$name};
345 0 $self->_check_kur_def( $name, $def, 1 );
346 0 $self->{kurs}{$name} = {
347 'opts' => $def,
348 'wheel' => undef,
349 'pid' => undef,
350 'restarts' => 0,
351 'delay' => 1,
352 'enabled' => 1,
353 'spawned' => undef,
354 };
355 } ## end foreach my $name ( keys( %{ $config->{kur} } ) )
356 # member validation has to wait till every kur is registered
357 0 foreach my $name ( keys( %{ $config->{kur} } ) ) {
358 0 ▶ if ( defined( $config->{kur}{$name}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $config->{"kur"}{$name}{"fan_out"}) 0 0 0
359 0 $self->_check_fan_out_members( $name, $config->{kur}{$name}, 1 );
360 }
361 }
362 } ## end if ( defined( $config->{kur} ) )
363  
364 # create these here rather than in start_server as the PID file gets
365 # written prior to start_server being called
366 0 foreach my $dir ( $self->{run_base_dir}, $self->{run_base_dir} . '/kur' ) {
367 0 ▶ if ( !-e $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $dir) 0 0 0
368 # don't need to check if this worked failed or not here as the next if statement will handle that
369 0 eval { mkdir($dir); };
370 }
371 0 ▶ if ( !-d $dir || !-r $dir || !-w $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir and -r $dir and -w $dir) 0 0 0
Condition0%0/6
-d $dir and -r $dir and -w $dir
!ll&&!rl&&r
000
-d $dir and -r $dir
!ll&&!rl&&r
000
MC/DC0%0/3
-d $dir and -r $dir and -w $dir
-d $dir -r $dir -w $dir
Truth table0%0/4
A and B and C
A= -d $dirB= -r $dirC= -w $dir
ABCresult
0XX0
10X0
1100
1111
372 0 $self->{perror} = 1;
373 0 $self->{error} = 4;
374 0 $self->{errorString} = 'The dir "' . $dir . '" is not a directory or is not read/writable';
375 0 $self->warn;
376 }
377 } ## end foreach my $dir ( $self->{run_base_dir}, $self->...)
378  
379 0 return $self;
380 } ## end sub new
381  
382 =head2 socket_path
383  
384 Returns the path of the manager unix socket.
385  
386 my $socket_path = $ereshkigal->socket_path;
387  
388 =cut
389  
390 0 ▶sub socket_path {
Subroutine socket_path: not called CC=1 SCAR=6.9
Pod documented
391 0 my ($self) = @_;
392  
393 0 return $self->{run_base_dir} . '/socket';
394 }
395  
396 =head2 pid_path
397  
398 Returns the path of the manager PID file.
399  
400 my $pid_path = $ereshkigal->pid_path;
401  
402 =cut
403  
404 0 ▶sub pid_path {
Subroutine pid_path: not called CC=1 SCAR=6.9
Pod documented
405 0 my ($self) = @_;
406  
407 0 return $self->{run_base_dir} . '/pid';
408 }
409  
410 =head2 kur_socket_path
411  
412 Returns the path of the unix socket for the specified kur instance.
413  
414 my $kur_socket_path = $ereshkigal->kur_socket_path($name);
415  
416 =cut
417  
418 0 ▶sub kur_socket_path {
Subroutine kur_socket_path: not called CC=1 SCAR=6.9
Pod documented
419 0 my ( $self, $name ) = @_;
420  
421 0 return $self->{run_base_dir} . '/kur/' . $name . '.sock';
422 }
423  
424 =head2 start_server
425  
426 Starts the manager. Spawns all configured kur instances, each supervised and
427 restarted with a backoff should it die, and brings up the
428 L<POE::Component::Server::JSONUnix> server on the manager socket, then calls
429 $poe_kernel->run.
430  
431 This should not be expected to return till the manager is told to stop.
432  
433 After binding, the manager socket is chowned to the configured group and
434 chmoded to the configured mode.
435  
436 The JSON commands handled are as below.
437  
438 - status :: Manager status... uptime and kur list with up/down state.
439  
440 - status_all :: The above plus each kur's full status block.
441  
442 - status_kur :: Full status of the kur instance args.name. For a
443 fan_out kur this is its member list plus each member's status.
444  
445 - banned :: Banned IPs, grouped per kur, along with when each expires.
446  
447 - ban :: Ban the IPs args.ips on the kur args.kur, or on all kurs if
448 args.kur is not specified. If args.kur is a fan_out kur it expands
449 to its members. args.ban_time, if defined, is forwarded
450 to the kurs, overriding their default for how long the bans should
451 last in seconds, with 0 meaning never time out. IPs are validated
452 and normalized to their canonical form before being fanned out,
453 with anything failing to validate reported back per IP under
454 rejected rather than being sent to the kurs. If nothing validates
455 the request as a whole errors.
456  
457 - unban :: If args.all is true, flush every kur. Otherwise validate and
458 normalize args.ip, erroring if it fails to validate, then check
459 each kur for it and unban it from each kur it is present on.
460  
461 - cidr_ban :: Ban the CIDR ranges args.cidrs, otherwise behaving like
462 ban including the args.kur targeting and args.ban_time forwarding.
463 CIDRs are validated and reduced to their canonical network form
464 before being fanned out. A targeted kur, or an untargeted fan out,
465 for which CIDR is not available answers per kur with either a drop
466 or an error depending on its cidr_silent_drop.
467  
468 - cidr_unban :: Validate and normalize args.cidr, erroring if it fails to
469 validate, then check each kur for it and unban it from each kur it
470 is present on. There is no all form... unban with args.all already
471 flushes CIDR bans alongside single IP bans.
472  
473 - add_kur :: Define and start a new kur instance, args.name and
474 args.opts. Does not rewrite the config file.
475  
476 - remove_kur :: Stop the kur instance args.name and deregister it. Does
477 not rewrite the config file.
478  
479 - checkpoint :: Force the kur args.kur, or all kurs if args.kur is not
480 specified, to write their ban state CSVs out now. If args.kur is a
481 fan_out kur it expands to its members.
482  
483 - re_init :: Have the kur args.kur, or all kurs if args.kur is not
484 specified, tear their firewall setup down and rebuild it, re-banning
485 everything their ban book carries. Expands a fan_out kur the same
486 way checkpoint does. Bans are briefly not enforced while the setup
487 is being rebuilt.
488  
489 - clear_retries :: Have the kur args.kur, or all kurs if args.kur is not
490 specified, forget unbans still owed to the firewall. args.ip or
491 args.cidr, at most one of them, names a single owed unban to
492 forget rather than the lot. Expands a fan_out kur the same way
493 checkpoint does. Nothing is asked of the firewall, so anything
494 genuinely still banished there stays that way.
495  
496 - stop :: Stop all kur instances and then the manager.
497  
498 =cut
499  
500 0 ▶sub start_server {
Subroutine start_server: not called CC=4 SCAR=30.0
Pod documented
501 0 my ($self) = @_;
502  
503 0 $self->errorblank;
504  
505 0 POE::Session->create(
506 object_states => [
507 $self => {
508 '_start' => '_poe_start',
509 'spawn_kur' => '_poe_spawn_kur',
510 'restart_kur' => '_poe_restart_kur',
511 'kur_stdout' => '_poe_kur_stdout',
512 'kur_stderr' => '_poe_kur_stderr',
513 'kur_reaped' => '_poe_kur_reaped',
514 'remove_kur' => '_poe_remove_kur',
515 'stop_all' => '_poe_stop_all',
516 },
517 ],
518 );
519  
520 my $server = POE::Component::Server::JSONUnix->spawn(
521 'socket_path' => $self->socket_path,
522 'socket_mode' => $self->{socket_mode},
523 'alias' => 'ereshkigal_server',
524 'auth_required' => $self->{enable_auth} ? 1 : 0,
525 defined( $self->{auth_temp_dir} ) ? ( 'auth_temp_dir' => $self->{auth_temp_dir} ) : (),
526 0 ▶ 'on_error' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
527 0 my ( $operation, $errnum, $errstr ) = @_;
528 0 log_drek( 'err', 'socket error during ' . $operation . '... ' . $errstr . ' (' . $errnum . ')' );
529 },
530 'commands' => {
531 0 ▶ 'status' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
532 0 my ( undef, undef, $ctx ) = @_;
533 0 $self->_authorize($ctx);
534 0 return $self->_cmd_status;
535 },
536 0 ▶ 'status_all' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
537 0 my ( undef, undef, $ctx ) = @_;
538 0 $self->_authorize($ctx);
539 0 return $self->_cmd_status_all;
540 },
541 0 ▶ 'status_kur' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
542 0 my ( undef, $request, $ctx ) = @_;
543 0 return $self->_cmd_status_kur( $request, $ctx );
544 },
545 0 ▶ 'banned' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
546 0 my ( undef, undef, $ctx ) = @_;
547 0 $self->_authorize( $ctx, $self->_real_kur_names );
548 0 return $self->_cmd_banned;
549 },
550 0 ▶ 'ban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
551 0 my ( undef, $request, $ctx ) = @_;
552 0 return $self->_cmd_ban( $request, $ctx );
553 },
554 0 ▶ 'unban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
555 0 my ( undef, $request, $ctx ) = @_;
556 0 $self->_authorize( $ctx, $self->_real_kur_names );
557 0 return $self->_cmd_unban($request);
558 },
559 0 ▶ 'cidr_ban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
560 0 my ( undef, $request, $ctx ) = @_;
561 0 return $self->_cmd_cidr_ban( $request, $ctx );
562 },
563 0 ▶ 'cidr_unban' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
564 0 my ( undef, $request, $ctx ) = @_;
565 0 $self->_authorize( $ctx, $self->_real_kur_names );
566 0 return $self->_cmd_cidr_unban($request);
567 },
568 0 ▶ 'add_kur' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
569 0 my ( undef, $request, $ctx ) = @_;
570 0 $self->_authorize($ctx);
571 0 return $self->_cmd_add_kur($request);
572 },
573 0 ▶ 'remove_kur' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
574 0 my ( undef, $request, $ctx ) = @_;
575 0 $self->_authorize($ctx);
576 0 return $self->_cmd_remove_kur($request);
577 },
578 0 ▶ 'checkpoint' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
579 0 my ( undef, $request, $ctx ) = @_;
580 0 return $self->_cmd_checkpoint( $request, $ctx );
581 },
582 0 ▶ 'clear_retries' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
583 0 my ( undef, $request, $ctx ) = @_;
584 0 return $self->_cmd_clear_retries( $request, $ctx );
585 },
586 0 ▶ 're_init' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
587 0 my ( undef, $request, $ctx ) = @_;
588 0 return $self->_cmd_re_init( $request, $ctx );
589 },
590 0 ▶ 'stop' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
591 0 my ( undef, undef, $ctx ) = @_;
592 0 $self->_authorize($ctx);
593 0 log_drek( 'info', 'stop requested' );
594 0 $poe_kernel->post( 'ereshkigal_manager', 'stop_all' );
595 # the current session is the JSONUnix server session, so this
596 # fires its shutdown state after the response has had time to flush
597 0 $poe_kernel->delay( 'shutdown', 1 );
598 0 return { 'stopping' => 1 };
599 },
600 },
601 0 ▶ );
Branch: 2 branches
BranchTrueFalseTotal
$self->{'enable_auth'} ? : 0 0 0
defined $self->{'auth_temp_dir'} ? : 0 0 0
602 0 $self->{server} = $server;
603  
604 # group ownership gates who may drive the manager
605 0 ▶ if ( !chown( $>, $self->{socket_gid}, $self->socket_path ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (chown $>, $self->{"socket_gid"}, $self->socket_path) 0 0 0
606 0 log_drek( 'err', 'chown of "' . $self->socket_path . '" to GID ' . $self->{socket_gid} . ' failed... ' . $! );
607 }
608  
609 0 $self->{started} = time;
610  
611 log_drek( 'info',
612 0 'started... socket=' . $self->socket_path . ' kurs=' . join( ',', sort( keys( %{ $self->{kurs} } ) ) ) );
613  
614 0 $poe_kernel->run;
615  
616 0 log_drek( 'info', 'stopped' );
617  
618 0 return;
619 } ## end sub start_server
620  
621 # Validates one kur definition, the hash that sits under kur.<name> in the
622 # config or arrives as args.opts on an add_kur request. Both paths run this so
623 # a kur added at runtime is held to exactly the same rules as one loaded from
624 # disk. It deliberately does not check fan_out members against the registry,
625 # as at config load that can only be done once every kur is registered...
626 # _check_fan_out_members is the second pass for that.
627 #
628 # The checks run as an if/elsif chain, so the first thing wrong is the thing
629 # reported. In order... the name matches /^[a-zA-Z0-9\-]+$/, the def is a
630 # hash, exactly one of backend and fan_out is present, fan_out is a non empty
631 # array of valid kur names, ban_time and checkpoint are non-negative ints,
632 # authed_users and authed_groups pass _authed_list_error, and options passes
633 # _options_error.
634 #
635 # Args, all required and positional...
636 #
637 # $name :: The kur instance name the def is for, as a string. Used both
638 # as the thing being validated and in every error message.
639 # undef is allowed in the sense that it is caught and reported
640 # rather than warning.
641 # $def :: A hash ref of the kur definition. Recognized keys are
642 # backend, fan_out, ports, protocols, prefix, self_heal,
643 # ban_time, checkpoint, enable_cidr, cidr_silent_drop,
644 # options, authed_users, and authed_groups. Anything else is
645 # ignored here. A non hash ref, including undef, is caught and
646 # reported.
647 # $perror :: Boolean for whether a failure is an Error::Helper permanent
648 # error as well as a die. Pass 1 from config load, where a bad
649 # def means the object is unusable and new should die via
650 # Error::Helper with flag 3, invalidKurDef. Pass 0 from
651 # add_kur, where the die is caught and turned into an error
652 # response and the manager carries on serving.
653 #
654 # Returns nothing meaningful, an empty return, when the def is good.
655 #
656 # Dies with a plain string describing the first problem found. When $perror
657 # is true it also sets perror, error 3, and errorString and calls warn first,
658 # so the die is preceded by the usual Error::Helper machinery.
659 #
660 # # config load... a bad def should kill the object
661 # $self->_check_kur_def( 'sshd', { 'backend' => 'pf' }, 1 );
662 #
663 # # add_kur... the caller wants the die, not a dead manager
664 # eval { $self->_check_kur_def( $name, $args->{opts}, 0 ); };
665 # if ($@) { return { 'error' => $@ }; }
666 0 ▶sub _check_kur_def {
Subroutine _check_kur_def: not called CC=28 SCAR=67.0
667 0 my ( $self, $name, $def, $perror ) = @_;
668  
669 0 my $error;
670 0 ▶ if ( !defined($name) || $name !~ /^[a-zA-Z0-9\-]+$/ ) {
Branch: 11 branches
BranchTrueFalseTotal
if (not defined $name && $name =~ /^[a-zA-Z0-9\-]+$/) { } 0 0 0
elsif (ref $def ne 'HASH') { } 0 0 0
elsif (defined $def->{'backend'} and defined $def->{'fan_out'}) { } 0 0 0
elsif (not defined $def->{'backend'} || defined $def->{'fan_out'}) { } 0 0 0
elsif (defined $def->{'fan_out'} and ref $def->{'fan_out'} ne 'ARRAY' || !@{$def->{'fan_out'};}) { } 0 0 0
elsif (defined $def->{'fan_out'} and grep {not defined $_ or ref $_ ne '' or not $_ =~ /^[a-zA-Z0-9\-]+$/;} @{$$def{'fan_out'};}) { } 0 0 0
elsif (defined $def->{'ban_time'} and not $def->{'ban_time'} =~ /^[0-9]+$/) { } 0 0 0
elsif (defined $def->{'checkpoint'} and not $def->{'checkpoint'} =~ /^[0-9]+$/) { } 0 0 0
elsif (defined $def->{'authed_users'} and defined _authed_list_error($def->{'authed_users'})) { } 0 0 0
elsif (defined $def->{'authed_groups'} and defined _authed_list_error($def->{'authed_groups'})) { } 0 0 0
elsif (defined $def->{'options'} and defined _options_error($def->{'options'})) { } 0 0 0
Condition0%0/3
defined $name && $name =~ /^[a-zA-Z0-9\-]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name && $name =~ /^[a-zA-Z0-9\-]+$/
defined $name $name =~ /^[a-zA-Z0-9\-]+$/
Truth table0%0/3
A && B
A= defined $nameB= $name =~ /^[a-zA-Z0-9\-]+$/
ABresult
0X0
100
111
671 0 ▶ $error = 'The kur name, "' . ( defined($name) ? $name : 'undef' ) . '", does not match /^[a-zA-Z0-9\-]+$/';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 0 0 0
672 } elsif ( ref($def) ne 'HASH' ) {
673 0 $error = 'The def for the kur "' . $name . '" is not a hash';
674 ▶ } elsif ( defined( $def->{backend} ) && defined( $def->{fan_out} ) ) {
Condition0%0/3
defined $def->{"backend"} and defined $def->{"fan_out"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"backend"} and defined $def->{"fan_out"}
defined $def->{"backend"} defined $def->{"fan_out"}
Truth table0%0/3
A and B
A= defined $def->{"backend"}B= defined $def->{"fan_out"}
ABresult
0X0
100
111
675 0 $error = 'The def for the kur "' . $name . '" has both a backend and a fan_out';
676 ▶ } elsif ( !defined( $def->{backend} ) && !defined( $def->{fan_out} ) ) {
Condition0%0/3
defined $def->{'backend'} || defined $def->{'fan_out'}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $def->{'backend'} || defined $def->{'fan_out'}
defined $def->{'backend'} defined $def->{'fan_out'}
Truth table0%0/3
A || B
A= defined $def->{'backend'}B= defined $def->{'fan_out'}
ABresult
1X1
011
000
677 0 $error = 'The def for the kur "' . $name . '" lacks a backend or a fan_out';
678 0 ▶ } elsif ( defined( $def->{fan_out} ) && ( ref( $def->{fan_out} ) ne 'ARRAY' || !@{ $def->{fan_out} } ) ) {
Condition0%0/6
defined $def->{"fan_out"} and ref $def->{"fan_out"} ne "ARRAY" || !@{$def->{"fan_out"};}
!ll&&!rl&&r
000
ref $def->{"fan_out"} ne "ARRAY" or not @{$def->{"fan_out"};}
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $def->{"fan_out"} and ref $def->{"fan_out"} ne "ARRAY" || !@{$def->{"fan_out"};}
defined $def->{"fan_out"} ref $def->{"fan_out"} ne "ARRAY" not @{$def->{"fan_out"};}
Truth table0%0/4
A and B or not(C)
A= defined $def->{"fan_out"}B= ref $def->{"fan_out"} ne "ARRAY"C= not @{$def->{"fan_out"};}
ABCresult
0XX0
1000
11X1
1011
679 0 $error = 'The fan_out for the kur "' . $name . '" is not an array of one or more kur names';
680 ▶ } elsif ( defined( $def->{fan_out} )
Condition0%0/3
defined $def->{"fan_out"} and grep {not defined $_ or ref $_ ne "" or not $_ =~ /^[a-zA-Z0-9\-]+$/;} @{$$def{"fan_out"};}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"fan_out"} and grep {not defined $_ or ref $_ ne "" or not $_ =~ /^[a-zA-Z0-9\-]+$/;} @{$$def{"fan_out"};}
defined $def->{"fan_out"} grep {not defined $_ or ref $_ ne "" or not $_ =~ /^[a-zA-Z0-9\-]+$/;} @{$$def{"fan_out"};}
Truth table0%0/3
A and B
A= defined $def->{"fan_out"}B= grep {not defined $_ or ref $_ ne "" or not $_ =~ /^[a-zA-Z0-9\-]+$/;} @{$$def{"fan_out"};}
ABresult
0X0
100
111
681 0 ▶ && grep { !defined($_) || ref($_) ne '' || $_ !~ /^[a-zA-Z0-9\-]+$/ } @{ $def->{fan_out} } )
Condition0%0/6
!defined($_) || ref $_ ne '' || !($_ =~ /^[a-zA-Z0-9\-]+$/)
l!l&&r!l&&!r
000
not defined $_ or ref $_ ne ""
l!l&&r!l&&!r
000
MC/DC0%0/3
!defined($_) || ref $_ ne '' || !($_ =~ /^[a-zA-Z0-9\-]+$/)
not defined $_ ref $_ ne "" !($_ =~ /^[a-zA-Z0-9\-]+$/)
Truth table0%0/4
not(A) or B || not(C)
A= not defined $_B= ref $_ ne ""C= !($_ =~ /^[a-zA-Z0-9\-]+$/)
ABCresult
1XX1
01X1
0011
0000
682 {
683 0 $error = 'The fan_out for the kur "' . $name . '" contains an invalid kur name';
684 ▶ } elsif ( defined( $def->{ban_time} ) && $def->{ban_time} !~ /^[0-9]+$/ ) {
Condition0%0/3
defined $def->{"ban_time"} and not $def->{"ban_time"} =~ /^[0-9]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"ban_time"} and not $def->{"ban_time"} =~ /^[0-9]+$/
defined $def->{"ban_time"} not $def->{"ban_time"} =~ /^[0-9]+$/
Truth table0%0/3
A and not(B)
A= defined $def->{"ban_time"}B= not $def->{"ban_time"} =~ /^[0-9]+$/
ABresult
0X0
100
111
685 $error
686 = 'The ban_time for the kur "'
687 . $name . '", "'
688 . $def->{ban_time}
689 0 . '", is not a non-negative int of seconds';
690 ▶ } elsif ( defined( $def->{checkpoint} ) && $def->{checkpoint} !~ /^[0-9]+$/ ) {
Condition0%0/3
defined $def->{"checkpoint"} and not $def->{"checkpoint"} =~ /^[0-9]+$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"checkpoint"} and not $def->{"checkpoint"} =~ /^[0-9]+$/
defined $def->{"checkpoint"} not $def->{"checkpoint"} =~ /^[0-9]+$/
Truth table0%0/3
A and not(B)
A= defined $def->{"checkpoint"}B= not $def->{"checkpoint"} =~ /^[0-9]+$/
ABresult
0X0
100
111
691 $error
692 = 'The checkpoint for the kur "'
693 . $name . '", "'
694 . $def->{checkpoint}
695 0 . '", is not a non-negative int of seconds';
696 ▶ } elsif ( defined( $def->{authed_users} ) && defined( _authed_list_error( $def->{authed_users} ) ) ) {
Condition0%0/3
defined $def->{"authed_users"} and defined _authed_list_error($def->{"authed_users"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"authed_users"} and defined _authed_list_error($def->{"authed_users"})
defined $def->{"authed_users"} defined _authed_list_error($def->{"authed_users"})
Truth table0%0/3
A and B
A= defined $def->{"authed_users"}B= defined _authed_list_error($def->{"authed_users"})
ABresult
0X0
100
111
697 0 $error = 'The authed_users for the kur "' . $name . '" is ' . _authed_list_error( $def->{authed_users} );
698 ▶ } elsif ( defined( $def->{authed_groups} ) && defined( _authed_list_error( $def->{authed_groups} ) ) ) {
Condition0%0/3
defined $def->{"authed_groups"} and defined _authed_list_error($def->{"authed_groups"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"authed_groups"} and defined _authed_list_error($def->{"authed_groups"})
defined $def->{"authed_groups"} defined _authed_list_error($def->{"authed_groups"})
Truth table0%0/3
A and B
A= defined $def->{"authed_groups"}B= defined _authed_list_error($def->{"authed_groups"})
ABresult
0X0
100
111
699 0 $error = 'The authed_groups for the kur "' . $name . '" is ' . _authed_list_error( $def->{authed_groups} );
700 ▶ } elsif ( defined( $def->{options} ) && defined( _options_error( $def->{options} ) ) ) {
Condition0%0/3
defined $def->{"options"} and defined _options_error($def->{"options"})
!ll&&!rl&&r
000
MC/DC0%0/2
defined $def->{"options"} and defined _options_error($def->{"options"})
defined $def->{"options"} defined _options_error($def->{"options"})
Truth table0%0/3
A and B
A= defined $def->{"options"}B= defined _options_error($def->{"options"})
ABresult
0X0
100
111
701 0 $error = 'The options for the kur "' . $name . '" is ' . _options_error( $def->{options} );
702 }
703  
704 0 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 0 0 0
705 0 ▶ if ($perror) {
Branch: 1 branch
BranchTrueFalseTotal
if ($perror) 0 0 0
706 0 $self->{perror} = 1;
707 0 $self->{error} = 3;
708 0 $self->{errorString} = $error;
709 0 $self->warn;
710 }
711 0 die($error);
712 }
713  
714 0 return;
715 } ## end sub _check_kur_def
716  
717 # Validates every member of a fan_out kur is a defined non fan_out kur...
718 # separate from _check_kur_def as it needs the kur registry, meaning at
719 # config load it can only happen once every kur is registered. _check_kur_def
720 # has already confirmed fan_out is a non empty array of syntactically valid
721 # names by the time this runs, so this only judges the names against what is
722 # actually registered.
723 #
724 # Walks the member list in order and stops at the first member that is either
725 # unknown to the registry or is itself a fan_out kur, gates not being
726 # allowed to nest.
727 #
728 # Args, all required and positional...
729 #
730 # $name :: The name of the fan_out kur whose members are being checked,
731 # as a string. Used in the error messages.
732 # $def :: A hash ref of that kur's definition, which must carry a
733 # fan_out key holding an array ref of member kur names.
734 # _check_kur_def is expected to have validated its shape
735 # already, so a missing or malformed fan_out here just walks
736 # nothing and passes.
737 # $perror :: Boolean, exactly as _check_kur_def takes it. 1 from config
738 # load so a bad gate is an Error::Helper permanent error with
739 # flag 3, invalidKurDef; 0 from add_kur so the die can be
740 # turned into an error response.
741 #
742 # Returns nothing meaningful, an empty return, when every member checks out.
743 #
744 # Dies with a plain string naming the offending member and why. When $perror
745 # is true it sets perror, error 3, and errorString and warns first.
746 #
747 # $self->_check_fan_out_members( 'baphomet', { 'fan_out' => [ 'sshd' ] }, 1 );
748 0 ▶sub _check_fan_out_members {
Subroutine _check_fan_out_members: not called CC=6 SCAR=37.4
749 0 my ( $self, $name, $def, $perror ) = @_;
750  
751 0 my $error;
752 0 foreach my $member ( @{ $def->{fan_out} } ) {
753 0 ▶ if ( !defined( $self->{kurs}{$member} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$member}) 0 0 0
754 0 $error = 'The fan_out for the kur "' . $name . '" contains an unknown kur, "' . $member . '"';
755 0 last;
756 }
757 0 ▶ if ( defined( $self->{kurs}{$member}{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"kurs"}{$member}{"opts"}{"fan_out"}) 0 0 0
758 0 $error
759 = 'The fan_out for the kur "'
760 . $name
761 . '" contains the fan_out kur "'
762 . $member
763 . '"... fan_out kurs may not nest';
764 0 last;
765 }
766 } ## end foreach my $member ( @{ $def->{fan_out} } )
767  
768 0 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 0 0 0
769 0 ▶ if ($perror) {
Branch: 1 branch
BranchTrueFalseTotal
if ($perror) 0 0 0
770 0 $self->{perror} = 1;
771 0 $self->{error} = 3;
772 0 $self->{errorString} = $error;
773 0 $self->warn;
774 }
775 0 die($error);
776 }
777  
778 0 return;
779 } ## end sub _check_fan_out_members
780  
781 # Judges whether a value is usable as an authed_users or authed_groups list,
782 # which has to be an array of plain strings. Used by _check_kur_def for the
783 # per kur lists and by new for the manager wide ones, which is why it reports
784 # rather than dies... each caller wants to wrap the answer in its own
785 # message naming which list was wrong. It is a plain sub rather than a
786 # method, taking no invocant.
787 #
788 # Checks the value is an array ref and then that every element is defined and
789 # not a ref. Empty arrays are fine, an empty list simply granting nobody.
790 #
791 # Args, required and positional...
792 #
793 # $list :: The value to judge. Anything at all may be passed... an array
794 # ref of strings is the only thing that passes, and undef, a
795 # plain string, a hash ref, or an array containing refs or undefs
796 # all come back with an error string.
797 #
798 # Returns undef when the value is a valid list, or an error string fragment
799 # otherwise... either 'not an array' or 'not an array of just strings'. The
800 # fragments are written to read as the tail of a sentence, callers prefixing
801 # them with something like 'The authed_users for the kur "sshd" is '.
802 #
803 # my $error = _authed_list_error( [ 'zane', 'root' ] ); # undef
804 # my $error = _authed_list_error('zane'); # 'not an array'
805 # my $error = _authed_list_error( [ 'zane', {} ] );
806 # # 'not an array of just strings'
807 0 ▶sub _authed_list_error {
Subroutine _authed_list_error: not called CC=5 SCAR=34.0
808 0 my ($list) = @_;
809  
810 0 ▶ if ( ref($list) ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $list ne "ARRAY") 0 0 0
811 0 return 'not an array';
812 }
813 0 foreach my $item ( @{$list} ) {
814 0 ▶ if ( !defined($item) || ref($item) ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $item or ref $item ne "") 0 0 0
Condition0%0/3
not defined $item or ref $item ne ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $item or ref $item ne ""
not defined $item ref $item ne ""
Truth table0%0/3
not(A) or B
A= not defined $itemB= ref $item ne ""
ABresult
1X1
011
000
815 0 return 'not an array of just strings';
816 }
817 }
818  
819 0 return undef;
820 } ## end sub _authed_list_error
821  
822 # Judges whether a backend options table is something _build_kur_cmd can
823 # actually hand to the kur bin. The command line can only carry scalars, so a
824 # array or hash valued option would otherwise reach the backend stringified
825 # as ARRAY(0x...) and fail confusingly at init... this catches it at config
826 # load instead. The one exception is interfaces, which backends such as xdp
827 # want as an array and which rides its own --interfaces flag. Like
828 # _authed_list_error it reports rather than dies, and is a plain sub taking
829 # no invocant.
830 #
831 # Checks the value is a hash ref, then walks every key. A scalar value passes
832 # immediately. The interfaces key additionally passes when it is an array ref
833 # containing only scalars. Anything else fails, naming the key.
834 #
835 # Args, required and positional...
836 #
837 # $options :: The value to judge, expected to be a hash ref of backend
838 # option name to value. Anything may be passed... a non hash
839 # ref, including undef, comes back as 'not a hash'. Key
840 # names are not judged at all, only their values, as which
841 # options a backend takes is the backend's business.
842 #
843 # Returns undef when the table is usable, or an error string fragment
844 # otherwise... 'not a hash', or a longer one naming the offending key. As
845 # with _authed_list_error the fragments read as the tail of a sentence the
846 # caller prefixes.
847 #
848 # my $error = _options_error( { 'kill' => 1 } ); # undef
849 # my $error = _options_error( { 'interfaces' => ['eth0'] } ); # undef
850 # my $error = _options_error( { 'bad' => ['a'] } );
851 # # 'carrying a non-scalar value for the option "bad"... only interfaces
852 # # may be an array, and only of plain scalars'
853 0 ▶sub _options_error {
Subroutine _options_error: not called CC=7 SCAR=40.3
854 0 my ($options) = @_;
855  
856 0 ▶ if ( ref($options) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $options ne "HASH") 0 0 0
857 0 return 'not a hash';
858 }
859 0 foreach my $key ( keys( %{$options} ) ) {
860 0 my $value = $options->{$key};
861 0 ▶ next if ( ref($value) eq '' );
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "" 0 0 0
862 0 ▶ if ( $key eq 'interfaces' && ref($value) eq 'ARRAY' && !grep { ref($_) ne '' } @{$value} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "interfaces" and ref $value eq "ARRAY" and not grep({ref $_ ne "";} @{$value;})) 0 0 0
Condition0%0/6
$key eq "interfaces" and ref $value eq "ARRAY" and not grep({ref $_ ne "";} @{$value;})
!ll&&!rl&&r
000
$key eq "interfaces" and ref $value eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/3
$key eq "interfaces" and ref $value eq "ARRAY" and not grep({ref $_ ne "";} @{$value;})
$key eq "interfaces" ref $value eq "ARRAY" not grep({ref $_ ne "";} @{$value;})
Truth table0%0/4
A and B and not(C)
A= $key eq "interfaces"B= ref $value eq "ARRAY"C= not grep({ref $_ ne "";} @{$value;})
ABCresult
0XX0
10X0
1100
1111
863 0 next;
864 }
865 0 return 'carrying a non-scalar value for the option "' . $key
866 . '"... only interfaces may be an array, and only of plain scalars';
867 }
868  
869 0 return undef;
870 } ## end sub _options_error
871  
872 # Checks if the user is in the passed users list or a member of one of the
873 # passed groups. The one place membership is actually decided, called by
874 # _authorize for both the manager level lists and the per kur ones, so the
875 # rule stays identical for both. It renders no verdict of its own about what
876 # that membership means... it answers yes or no and _authorize decides what
877 # to do about it.
878 #
879 # Names are compared as exact strings, no case folding and no globbing.
880 # Group membership, primary and secondary both, comes from the JSONUnix
881 # context rather than being resolved here, which is what lets user and group
882 # database changes apply without a restart... the context resolves it
883 # through NSS and caches it per connection.
884 #
885 # Args, all required and positional...
886 #
887 # $ctx :: The POE::Component::Server::JSONUnix context object for
888 # the connection the request arrived on. Only its in_group
889 # method is used here. Must be a real context... there is no
890 # guard against undef, as every caller has already taken uid
891 # and username off it.
892 # $username :: The username to match against $users, as a plain string.
893 # _authorize passes '' rather than undef when the context
894 # has no username, so an empty string simply matches nothing.
895 # $users :: An array ref of usernames granted access. May be empty.
896 # $groups :: An array ref of group names granted access. May be empty. A
897 # group that does not exist just never matches rather than
898 # erroring.
899 #
900 # Returns 1 if the user matches by name or by any group, 0 if none of them
901 # match.
902 #
903 # if ( $self->_user_in_lists( $ctx, 'zane', ['root'], ['wheel'] ) ) {
904 # # zane is not the user root, but may still be in the wheel group
905 # }
906 0 ▶sub _user_in_lists {
Subroutine _user_in_lists: not called CC=5 SCAR=34.0
907 0 my ( $self, $ctx, $username, $users, $groups ) = @_;
908  
909 0 foreach my $user ( @{$users} ) {
910 0 ▶ if ( $user eq $username ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($user eq $username) 0 0 0
911 0 return 1;
912 }
913 }
914  
915 0 foreach my $group ( @{$groups} ) {
916 # unknown groups just never match rather than erroring
917 0 ▶ if ( $ctx->in_group($group) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ctx->in_group($group)) 0 0 0
918 0 return 1;
919 }
920 }
921  
922 0 return 0;
923 } ## end sub _user_in_lists
924  
925 # Authorizes the authenticated user behind the context for the specified
926 # kurs, or for manager level commands when no kurs are specified. This is the
927 # whole of the trust model... every command handler calls it before doing
928 # anything, and a command must be authorized for every kur it touches. It is
929 # a no-op when enable_auth is off, so the same handlers serve both modes with
930 # out branching.
931 #
932 # The decision, in order... enable_auth off means yes. A context with no uid
933 # means the JSONUnix auth gate has somehow been bypassed and is refused. UID
934 # 0 is always yes. With no kurs named it is a manager level command and only
935 # the global lists are consulted. With kurs named, each is checked against
936 # the global lists plus that kur's own, which expand rather than replace
937 # them, and the first kur the user is not entitled to refuses the lot.
938 #
939 # Note the empty kur list case is load bearing rather than accidental...
940 # untargeted commands on a manager carrying zero real kurs land there
941 # deliberately, as with no per-kur lists to expand the global lists are all
942 # there is to check. That is why callers authorize before reporting that
943 # there is nothing to act on.
944 #
945 # Args...
946 #
947 # $ctx :: Required. The POE::Component::Server::JSONUnix context for
948 # the connection, which supplies uid, username, and in_group. A
949 # context whose uid method returns undef is treated as a
950 # authentication failure rather than trusted.
951 # @kurs :: Optional, zero or more kur names as plain strings. Zero names
952 # means the manager level check. Names that are not registered
953 # are still checked, against the global lists alone, so that a
954 # refusal and a nonexistent kur look the same to a caller who
955 # is not entitled to either... callers rely on this to keep kur
956 # names from being enumerated.
957 #
958 # Returns nothing meaningful, an empty return, when the user is allowed.
959 #
960 # Dies with a HASH ref rather than a string when refusing, which is how a
961 # machine readable code reaches the JSONUnix error response. The shape is
962 # { error => '...', code => '...' }, where code is 'permission_denied' for a
963 # authorization refusal and 'auth_required' for the should-be-unreachable
964 # missing uid case. Consumers are told to branch on code rather than match
965 # the message text, so the code matters as much as the message.
966 #
967 # # manager level... stop, add_kur, remove_kur, the whole manager views
968 # $self->_authorize($ctx);
969 #
970 # # one named kur, as a targeted ban does
971 # $self->_authorize( $ctx, 'sshd' );
972 #
973 # # every real kur, as an untargeted command does
974 # $self->_authorize( $ctx, $self->_real_kur_names );
975 0 ▶sub _authorize {
Subroutine _authorize: not called CC=12 SCAR=50.5
976 0 my ( $self, $ctx, @kurs ) = @_;
977  
978 0 ▶ if ( !$self->{enable_auth} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"enable_auth"}) 0 0 0
979 0 return;
980 }
981  
982 0 my $uid = $ctx->uid;
983 0 my $username = $ctx->username;
984 0 ▶ if ( !defined($uid) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $uid) 0 0 0
985 # should be unreachable as JSONUnix gates unauthed commands first...
986 # a hash ref die carries a machine-readable code through to the
987 # JSONUnix error response, matching its own auth_required code
988 0 die( { 'error' => 'authentication required', 'code' => 'auth_required' } );
989 }
990 0 ▶ if ( $uid == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uid == 0) 0 0 0
991 0 return;
992 }
993 0 ▶ $username = '' if !defined($username);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $username 0 0 0
994  
995 # no kurs named means a manager level command... untargeted commands on a
996 # manager with zero real kurs also land here, deliberately, as with no
997 # per-kur lists to expand the global lists are all there is to check
998 0 ▶ if ( !@kurs ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@kurs) 0 0 0
999 0 ▶ if ( $self->_user_in_lists( $ctx, $username, $self->{authed_users}, $self->{authed_groups} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_user_in_lists($ctx, $username, $self->{"authed_users"}, $self->{"authed_groups"})) 0 0 0
1000 0 return;
1001 }
1002 die(
1003 {
1004 0 'error' => 'The user "' . $username . '" is not authorized for manager level commands',
1005 'code' => 'permission_denied',
1006 }
1007 );
1008 } ## end if ( !@kurs )
1009  
1010 0 foreach my $name (@kurs) {
1011 # the effective lists for a kur are the global ones plus its own
1012 0 ▶ my $def = defined( $self->{kurs}{$name} ) ? $self->{kurs}{$name}{opts} : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'kurs'}{$name} ? : 0 0 0
1013 my @users
1014 0 ▶ = ( @{ $self->{authed_users} }, ref( $def->{authed_users} ) eq 'ARRAY' ? @{ $def->{authed_users} } : () );
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{'authed_users'} eq 'ARRAY' ? : 0 0 0
1015 0 ▶ my @groups = ( @{ $self->{authed_groups} },
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{'authed_groups'} eq 'ARRAY' ? : 0 0 0
1016 0 ref( $def->{authed_groups} ) eq 'ARRAY' ? @{ $def->{authed_groups} } : () );
1017 0 ▶ if ( !$self->_user_in_lists( $ctx, $username, \@users, \@groups ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_user_in_lists($ctx, $username, \@users, \@groups)) 0 0 0
1018 0 die(
1019 {
1020 'error' => 'The user "' . $username . '" is not authorized for the kur "' . $name . '"',
1021 'code' => 'permission_denied',
1022 }
1023 );
1024 }
1025 } ## end foreach my $name (@kurs)
1026  
1027 0 return;
1028 } ## end sub _authorize
1029  
1030 # Builds an Ereshkigal::Client aimed at one kur's socket, carrying the
1031 # manager wide timeout. Used where a single kur has to be spoken to on its
1032 # own rather than fanned to, which is the two shutdown paths, _poe_stop_all
1033 # and _poe_remove_kur. Everything else goes through _fan_out, as that answers
1034 # per kur and bounds the whole conversation with one deadline.
1035 #
1036 # Nothing is connected here... the client only opens a socket when a call is
1037 # made on it, so a client for a kur that is not running is fine to build and
1038 # will simply fail at call time.
1039 #
1040 # Args, required and positional...
1041 #
1042 # $name :: The kur instance name, as a plain string. Not checked against
1043 # the registry... the path is built from it regardless, so a
1044 # name that is not registered yields a client pointed at a
1045 # socket that does not exist.
1046 #
1047 # Returns a new Ereshkigal::Client instance with its socket set to that
1048 # kur's path under run_base_dir/kur/ and its timeout set to the manager's
1049 # timeout setting.
1050 #
1051 # eval { $self->_kur_client('sshd')->call_ok('stop'); };
1052 # if ($@) { log_drek( 'err', 'could not stop sshd... ' . $@ ); }
1053 0 ▶sub _kur_client {
Subroutine _kur_client: not called CC=1 SCAR=6.9
1054 0 my ( $self, $name ) = @_;
1055  
1056 return Ereshkigal::Client->new(
1057 'socket' => $self->kur_socket_path($name),
1058 'timeout' => $self->{timeout},
1059 0 );
1060 }
1061  
1062 # The names of the kurs that are actual processes, sorted... fan_out kurs
1063 # are manager side only and get excluded everywhere an untargeted command
1064 # resolves its targets. Every untargeted command runs through this, which is
1065 # what keeps a gate from being double counted... banning with no --kur
1066 # reaches each real kur once rather than once directly and again through
1067 # every gate naming it.
1068 #
1069 # Takes only the invocant. Reads the kur registry and filters out any entry
1070 # whose opts carry a fan_out key, whether or not it is running... this is
1071 # about what a kur is, not what state it is in.
1072 #
1073 # Returns the names as a sorted list, not an array ref, so it drops straight
1074 # into a call expecting a list. A manager with no real kurs returns the empty
1075 # list, which callers are careful to authorize on before reporting.
1076 #
1077 # my @targets = $self->_real_kur_names;
1078 # my $kurs = $self->_fan_out( \@targets, 'banned' );
1079 #
1080 # # or straight into a call taking a list
1081 # $self->_authorize( $ctx, $self->_real_kur_names );
1082 0 ▶sub _real_kur_names {
Subroutine _real_kur_names: not called CC=1 SCAR=6.9
1083 0 my ($self) = @_;
1084  
1085 0 return grep { !defined( $self->{kurs}{$_}{opts}{fan_out} ) } sort( keys( %{ $self->{kurs} } ) );
1086 }
1087  
1088 # Expands a targeted kur name into fan out targets... a fan_out kur becomes
1089 # its members while a plain kur is just itself. This is what makes a gate
1090 # usable as a single point of contact, and it is deliberately separate from
1091 # authorization... the caller authorizes against the name it was given, not
1092 # against what that name expands to, which is exactly why being granted a
1093 # gate covers its members without being listed on any of them.
1094 #
1095 # One level only. Gates may not nest, which _check_fan_out_members enforces
1096 # at definition time, so there is no recursion here.
1097 #
1098 # Args, required and positional...
1099 #
1100 # $name :: The kur instance name that was targeted, as a plain string. A
1101 # name that is not registered is not an error here... it comes
1102 # back as itself, and the fan out then answers it with a not
1103 # running error. Callers that want an unknown kur to be an error
1104 # check the registry themselves, after authorizing.
1105 #
1106 # Returns a list of kur names to actually act on. For a gate that is its
1107 # member list in the order the fan_out array carries them; for anything else
1108 # it is a one element list holding the name it was given.
1109 #
1110 # my @targets = $self->_expand_kur_targets('sshd'); # ('sshd')
1111 # my @targets = $self->_expand_kur_targets('baphomet'); # ('sshd','smtp')
1112 0 ▶sub _expand_kur_targets {
Subroutine _expand_kur_targets: not called CC=3 SCAR=24.8
1113 0 my ( $self, $name ) = @_;
1114  
1115 0 my $entry = $self->{kurs}{$name};
1116 0 ▶ if ( defined($entry) && defined( $entry->{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry and defined $entry->{"opts"}{"fan_out"}) 0 0 0
Condition0%0/3
defined $entry and defined $entry->{"opts"}{"fan_out"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $entry and defined $entry->{"opts"}{"fan_out"}
defined $entry defined $entry->{"opts"}{"fan_out"}
Truth table0%0/3
A and B
A= defined $entryB= defined $entry->{"opts"}{"fan_out"}
ABresult
0X0
100
111
1117 0 return @{ $entry->{opts}{fan_out} };
1118 }
1119  
1120 0 return ($name);
1121 } ## end sub _expand_kur_targets
1122  
1123 # Fans one command out to the passed kur instances concurrently via
1124 # Ereshkigal::Client->call_many. Almost every command handler ends in a call
1125 # to this, and its return is what they hand back as the kurs value of their
1126 # response, so the per kur shape a consumer sees is decided here.
1127 #
1128 # Kurs that are not running are answered locally with a not running error and
1129 # never dialled, so a stopped kur costs nothing and cannot slow the fan out
1130 # down. Whatever is left is handed to call_many in one go, which talks to
1131 # them concurrently under a single shared deadline... the wall time is the
1132 # slowest kur capped at one timeout rather than the sum of all of them.
1133 #
1134 # It does no authorizing and no target expansion of its own... callers have
1135 # already run _authorize and _expand_kur_targets by the time they get here.
1136 #
1137 # Args...
1138 #
1139 # $targets :: Required. An array ref of kur names to reach, already
1140 # expanded, so a gate's members rather than the gate. May be
1141 # empty, which answers with an empty hash and dials nothing.
1142 # Names not in the registry are answered as not running.
1143 # $command :: Required. The command name to send each kur, as a plain
1144 # string... 'ban', 'banned', 'checkpoint', 're_init' and so
1145 # on. Sent verbatim, so a command the kur does not handle
1146 # comes back as that kur's error.
1147 # $args :: Optional. A hash ref sent as the args value of the request,
1148 # the same for every kur. Omitted or undef sends no args key
1149 # at all, which is what commands taking none expect.
1150 #
1151 # Returns a hash ref keyed by kur name, every name in $targets present. Each
1152 # value is either that kur's result, whatever shape the kur's own handler
1153 # returned, or { error => '...' } when it could not be reached or answered
1154 # with an error status. A caller can tell the two apart by looking for an error
1155 # key, which is what _cmd_status_all and _cmd_status_kur do.
1156 #
1157 # my $kurs = $self->_fan_out( [ 'sshd', 'smtp' ], 'banned' );
1158 # # { sshd => { banned => [...], ... }, smtp => { error => 'not running' } }
1159 #
1160 # my $kurs = $self->_fan_out(
1161 # [ $self->_real_kur_names ],
1162 # 'ban',
1163 # { 'ips' => ['1.2.3.4'], 'ban_time' => 3600 }
1164 # );
1165 0 ▶sub _fan_out {
Subroutine _fan_out: not called CC=8 SCAR=42.8
1166 0 my ( $self, $targets, $command, $args ) = @_;
1167  
1168 0 my $kurs = {};
1169 0 my $sockets = {};
1170 0 foreach my $name ( @{$targets} ) {
1171 0 my $entry = $self->{kurs}{$name};
1172 0 ▶ if ( !defined($entry) || !defined( $entry->{pid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry and defined $entry->{"pid"}) 0 0 0
Condition0%0/3
defined $entry and defined $entry->{"pid"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $entry and defined $entry->{"pid"}
defined $entry defined $entry->{"pid"}
Truth table0%0/3
A and B
A= defined $entryB= defined $entry->{"pid"}
ABresult
0X0
100
111
1173 0 $kurs->{$name} = { 'error' => 'not running' };
1174 0 next;
1175 }
1176 0 $sockets->{$name} = $self->kur_socket_path($name);
1177 }
1178  
1179 0 ▶ if ( %{$sockets} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$sockets;}) 0 0 0
1180 my $answers = Ereshkigal::Client->call_many(
1181 'sockets' => $sockets,
1182 'command' => $command,
1183 defined($args) ? ( 'args' => $args ) : (),
1184 'timeout' => $self->{timeout},
1185 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
defined $args ? : 0 0 0
1186 0 foreach my $name ( keys( %{$answers} ) ) {
1187 0 ▶ if ( defined( $answers->{$name}{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $answers->{$name}{'error'}) { } 0 0 0
1188 0 $kurs->{$name} = { 'error' => $answers->{$name}{error} };
1189 } else {
1190 0 $kurs->{$name} = $answers->{$name}{result};
1191 }
1192 }
1193 } ## end if ( %{$sockets} )
1194  
1195 0 return $kurs;
1196 } ## end sub _fan_out
1197  
1198 # Builds the argv the manager spawns a kur process with, translating that
1199 # kur's config hash into the kur bin's flags. This is the single place the
1200 # manager side config and the kur bin's command line meet, so anything the
1201 # kur bin learns to take has to be taught here too or it can never be set
1202 # from the config.
1203 #
1204 # Layering is resolved here rather than kur side... ban_time and checkpoint
1205 # fall back to the manager wide values when the kur names none, and the two
1206 # CIDR toggles do the same and are collapsed to a clean 1 or 0 so the kur is
1207 # not left folding config strings. ports and protocols are comma joined.
1208 # Backend options ride --option key=value, sorted for a stable command line,
1209 # with interfaces the one exception... it may be an array and so rides its
1210 # own --interfaces flag, comma joined, for the kur bin to split back apart.
1211 # _options_error has already refused any other array valued option by now.
1212 #
1213 # Always passes --foreground, as the manager supervises the process through a
1214 # POE::Wheel::Run and must not have it daemonize away from its wheel.
1215 #
1216 # Args, required and positional...
1217 #
1218 # $name :: The kur instance name, as a plain string. Must already be
1219 # registered... its opts hash is read straight out of the
1220 # registry, so an unknown name warns and builds a broken command.
1221 #
1222 # Returns the command as a list, ready to hand to POE::Wheel::Run as its
1223 # Program... the kur bin path first, then the flags. Not a string, so no
1224 # quoting is needed or applied and an option value carrying spaces survives.
1225 #
1226 # my @cmd = $self->_build_kur_cmd('sshd');
1227 # # ( '/usr/local/bin/kur', '--foreground', '--name', 'sshd',
1228 # # '--backend', 'pf', '--run', '/var/run/ereshkigal', ... )
1229 # my $wheel = POE::Wheel::Run->new( 'Program' => \@cmd, ... );
1230 0 ▶sub _build_kur_cmd {
Subroutine _build_kur_cmd: not called CC=18 SCAR=58.3
1231 0 my ( $self, $name ) = @_;
1232  
1233 0 my $def = $self->{kurs}{$name}{opts};
1234  
1235 my @cmd = (
1236 $self->{kur_bin}, '--foreground', '--name', $name,
1237 '--backend', $def->{backend}, '--run', $self->{run_base_dir},
1238 '--cache', $self->{cache_base_dir},
1239 0 );
1240  
1241 0 foreach my $listy ( 'ports', 'protocols' ) {
1242 0 ▶ if ( defined( $def->{$listy} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $def->{$listy}) 0 0 0
1243 0 ▶ my @items = ref( $def->{$listy} ) eq 'ARRAY' ? @{ $def->{$listy} } : ( $def->{$listy} );
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{$listy} eq 'ARRAY' ? : 0 0 0
1244 0 ▶ if (@items) {
Branch: 1 branch
BranchTrueFalseTotal
if (@items) 0 0 0
1245 0 push( @cmd, '--' . $listy, join( ',', @items ) );
1246 }
1247 }
1248 }
1249  
1250 0 ▶ if ( defined( $def->{prefix} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $def->{"prefix"}) 0 0 0
1251 0 push( @cmd, '--prefix', $def->{prefix} );
1252 }
1253  
1254 0 ▶ if ( defined( $def->{self_heal} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $def->{"self_heal"}) 0 0 0
1255 0 ▶ push( @cmd, '--self-heal', $def->{self_heal} ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$def->{'self_heal'} ? : 0 0 0
1256 }
1257  
1258 # the kur ban_time and checkpoint, defaulting to the manager wide ones
1259 0 ▶ push( @cmd, '--ban-time', defined( $def->{ban_time} ) ? $def->{ban_time} : $self->{ban_time} );
Branch: 1 branch
BranchTrueFalseTotal
defined $def->{'ban_time'} ? : 0 0 0
1260 0 ▶ push( @cmd, '--checkpoint', defined( $def->{checkpoint} ) ? $def->{checkpoint} : $self->{checkpoint} );
Branch: 1 branch
BranchTrueFalseTotal
defined $def->{'checkpoint'} ? : 0 0 0
1261  
1262 # the CIDR toggles, per kur overriding the manager wide ones, collapsed to
1263 # 1/0 here so the kur is handed a clean boolean
1264 0 ▶ my $enable_cidr = defined( $def->{enable_cidr} ) ? $def->{enable_cidr} : $self->{enable_cidr};
Branch: 1 branch
BranchTrueFalseTotal
defined $def->{'enable_cidr'} ? : 0 0 0
1265 0 ▶ my $cidr_silent_drop = defined( $def->{cidr_silent_drop} ) ? $def->{cidr_silent_drop} : $self->{cidr_silent_drop};
Branch: 1 branch
BranchTrueFalseTotal
defined $def->{'cidr_silent_drop'} ? : 0 0 0
1266 0 ▶ push( @cmd, '--enable-cidr', $enable_cidr ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$enable_cidr ? : 0 0 0
1267 0 ▶ push( @cmd, '--cidr-silent-drop', $cidr_silent_drop ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$cidr_silent_drop ? : 0 0 0
1268  
1269 0 ▶ if ( ref( $def->{options} ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $def->{"options"} eq "HASH") 0 0 0
1270 0 foreach my $key ( sort( keys( %{ $def->{options} } ) ) ) {
1271 0 my $value = $def->{options}{$key};
1272 # interfaces is the one array valued option, riding its own flag
1273 # so the kur bin can rebuild the array
1274 0 ▶ if ( $key eq 'interfaces' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq 'interfaces') { } 0 0 0
1275 0 ▶ push( @cmd, '--interfaces', ref($value) eq 'ARRAY' ? join( ',', @{$value} ) : $value );
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 0 0 0
1276 } else {
1277 0 push( @cmd, '--option', $key . '=' . $value );
1278 }
1279 } ## end foreach my $key ( sort( keys( %{ $def->{options...}})))
1280 } ## end if ( ref( $def->{options} ) eq 'HASH' )
1281  
1282 0 return @cmd;
1283 } ## end sub _build_kur_cmd
1284  
1285 #
1286 # POE states for the manager session
1287 #
1288  
1289 # The manager session's _start handler, run by the POE kernel once when the
1290 # session created in start_server comes up. Not called directly by anything.
1291 #
1292 # Claims the alias 'ereshkigal_manager', which is how every other part of the
1293 # process reaches this session... the JSONUnix command handlers post to that
1294 # alias rather than holding a session reference, and _cmd_add_kur and
1295 # _cmd_remove_kur both rely on it. Then yields a spawn_kur for every kur in
1296 # the registry, sorted, rather than spawning inline, so the session is fully
1297 # up before any child process work begins.
1298 #
1299 # POE calling convention... invoked as an object state, so @_ carries OBJECT
1300 # and KERNEL...
1301 #
1302 # $_[OBJECT] :: This Ereshkigal instance.
1303 # $_[KERNEL] :: The POE kernel, used to set the alias and to yield the
1304 # per kur spawn_kur events.
1305 #
1306 # Returns nothing meaningful, an empty return. POE ignores the return of a
1307 # state handler.
1308 #
1309 # # not called directly... the kernel fires it when the session starts
1310 # POE::Session->create(
1311 # object_states => [ $self => { '_start' => '_poe_start', ... } ] );
1312 0 ▶sub _poe_start {
Subroutine _poe_start: not called CC=2 SCAR=17.9
1313 0 my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
1314  
1315 0 $kernel->alias_set('ereshkigal_manager');
1316  
1317 0 foreach my $name ( sort( keys( %{ $self->{kurs} } ) ) ) {
1318 0 $kernel->yield( 'spawn_kur', $name );
1319 }
1320  
1321 0 return;
1322 } ## end sub _poe_start
1323  
1324 # The manager session's spawn_kur handler, which actually starts one kur
1325 # process. Reached three ways... _poe_start yields it per kur at startup,
1326 # _poe_restart_kur yields it after a death, and _cmd_add_kur posts it for a
1327 # kur added at runtime. All three go through the session because a
1328 # POE::Wheel::Run must be created and destroyed in the session that watches
1329 # it.
1330 #
1331 # Refuses to do anything, silently, when the kur is unknown, disabled,
1332 # already has a wheel, or the manager is shutting down... that last one is
1333 # what keeps a death during shutdown from being restarted into a race. A
1334 # fan_out kur also returns early, having no process to spawn.
1335 #
1336 # Otherwise builds the command via _build_kur_cmd, starts it under a
1337 # POE::Wheel::Run wired to the kur_stdout and kur_stderr events, and asks the
1338 # kernel to send kur_reaped when it exits. The registry entry then records
1339 # the wheel, the PID, and the spawn time, and both the wheel_to_kur and
1340 # pid_to_kur lookups gain an entry... those two are how the output and reap
1341 # handlers, which are only told a wheel ID or a PID, learn which kur they are
1342 # about.
1343 #
1344 # POE calling convention... invoked as an object state...
1345 #
1346 # $_[OBJECT] :: This Ereshkigal instance.
1347 # $_[KERNEL] :: The POE kernel, used for sig_child.
1348 # $_[ARG0] :: The kur instance name to spawn, as a plain string. A name
1349 # that is not registered is ignored rather than erroring.
1350 #
1351 # Returns nothing meaningful, an empty return.
1352 #
1353 # $kernel->yield( 'spawn_kur', 'sshd' );
1354 # $poe_kernel->post( 'ereshkigal_manager', 'spawn_kur', 'sshd' );
1355 0 ▶sub _poe_spawn_kur {
Subroutine _poe_spawn_kur: not called CC=6 SCAR=37.4
1356 0 my ( $self, $kernel, $name ) = @_[ OBJECT, KERNEL, ARG0 ];
1357  
1358 0 my $entry = $self->{kurs}{$name};
1359 0 ▶ if ( !defined($entry) || !$entry->{enabled} || defined( $entry->{wheel} ) || $self->{shutting_down} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $entry && $entry->{"enabled"} or defined $entry->{"wheel"} or $self->{"shutting_down"}) 0 0 0
Condition0%0/9
not defined $entry && $entry->{"enabled"} or defined $entry->{"wheel"} or $self->{"shutting_down"}
l!l&&r!l&&!r
000
not defined $entry && $entry->{"enabled"} or defined $entry->{"wheel"}
l!l&&r!l&&!r
000
defined $entry && $entry->{'enabled'}
!ll&&!rl&&r
000
MC/DC0%0/4
not defined $entry && $entry->{"enabled"} or defined $entry->{"wheel"} or $self->{"shutting_down"}
defined $entry $entry->{'enabled'} defined $entry->{"wheel"} $self->{"shutting_down"}
Truth table0%0/5
not(A && B) or C or D
A= defined $entryB= $entry->{'enabled'}C= defined $entry->{"wheel"}D= $self->{"shutting_down"}
ABCDresult
0XXX1
10XX1
111X1
11011
11000
1360 0 return;
1361 }
1362  
1363 # fan_out kurs are manager side only... nothing to spawn
1364 0 ▶ if ( defined( $entry->{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"opts"}{"fan_out"}) 0 0 0
1365 0 return;
1366 }
1367  
1368 0 my @cmd = $self->_build_kur_cmd($name);
1369  
1370 0 my $wheel = POE::Wheel::Run->new(
1371 'Program' => \@cmd,
1372 'StdoutEvent' => 'kur_stdout',
1373 'StderrEvent' => 'kur_stderr',
1374 );
1375  
1376 0 $kernel->sig_child( $wheel->PID, 'kur_reaped' );
1377  
1378 0 $entry->{wheel} = $wheel;
1379 0 $entry->{pid} = $wheel->PID;
1380 0 $entry->{spawned} = time;
1381  
1382 0 $self->{wheel_to_kur}{ $wheel->ID } = $name;
1383 0 $self->{pid_to_kur}{ $wheel->PID } = $name;
1384  
1385 0 log_drek( 'info', 'spawned kur "' . $name . '" as PID ' . $wheel->PID . '... ' . join( ' ', @cmd ) );
1386  
1387 0 return;
1388 } ## end sub _poe_spawn_kur
1389  
1390 # The manager session's restart_kur handler, which exists only so a delayed
1391 # restart has something to land on. _poe_kur_reaped sets a delay_set for this
1392 # rather than for spawn_kur directly, keeping the two apart so the backoff
1393 # timer is visibly a restart rather than looking like a fresh spawn... all it
1394 # does is yield spawn_kur, which holds every one of the guards about whether
1395 # spawning is actually appropriate by then.
1396 #
1397 # That indirection matters for one case in particular... between the delay
1398 # being set and it firing, the kur may have been removed or the manager may
1399 # have begun shutting down, and spawn_kur is where both are noticed.
1400 #
1401 # POE calling convention... invoked as an object state...
1402 #
1403 # $_[OBJECT] :: This Ereshkigal instance.
1404 # $_[KERNEL] :: The POE kernel, used to yield spawn_kur.
1405 # $_[ARG0] :: The kur instance name to restart, as a plain string,
1406 # passed straight through to spawn_kur.
1407 #
1408 # Returns nothing meaningful, an empty return.
1409 #
1410 # # from _poe_kur_reaped, after a death, with the current backoff
1411 # $kernel->delay_set( 'restart_kur', $delay, $name );
1412 0 ▶sub _poe_restart_kur {
Subroutine _poe_restart_kur: not called CC=1 SCAR=6.9
1413 0 my ( $self, $kernel, $name ) = @_[ OBJECT, KERNEL, ARG0 ];
1414  
1415 0 $kernel->yield( 'spawn_kur', $name );
1416  
1417 0 return;
1418 }
1419  
1420 # The manager session's kur_stdout handler, fired by the POE::Wheel::Run of
1421 # a kur process for each line that child writes to stdout. A kur normally
1422 # says nothing there, logging through syslog itself, so anything arriving
1423 # is worth relaying rather than swallowing... it is usually a module warning
1424 # or something printed before logging was up.
1425 #
1426 # The wheel only reports which wheel ID the line came from, so the kur name
1427 # is looked up through wheel_to_kur. A line arriving after the entry has gone
1428 # is logged against 'unknown' rather than dropped or warned about.
1429 #
1430 # POE calling convention... invoked as an object state, and note it does not
1431 # take KERNEL...
1432 #
1433 # $_[OBJECT] :: This Ereshkigal instance.
1434 # $_[ARG0] :: The line the child wrote, as a string. The wheel has
1435 # already split on newlines, but the line is chomped here
1436 # anyway before it reaches the log.
1437 # $_[ARG1] :: The ID of the POE::Wheel::Run the line came from, used to
1438 # resolve the kur name via wheel_to_kur.
1439 #
1440 # Returns nothing meaningful, an empty return.
1441 #
1442 # # not called directly... wired up when the wheel is created
1443 # POE::Wheel::Run->new( 'StdoutEvent' => 'kur_stdout', ... );
1444 0 ▶sub _poe_kur_stdout {
Subroutine _poe_kur_stdout: not called CC=2 SCAR=17.9
1445 0 my ( $self, $line, $wheel_id ) = @_[ OBJECT, ARG0, ARG1 ];
1446  
1447 0 my $name = $self->{wheel_to_kur}{$wheel_id};
1448 0 ▶ $name = 'unknown' if !defined($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 0 0
1449 0 chomp($line);
1450 0 log_drek( 'info', 'kur "' . $name . '" stdout... ' . $line );
1451  
1452 0 return;
1453 } ## end sub _poe_kur_stdout
1454  
1455 # The manager session's kur_stderr handler, the stderr twin of
1456 # _poe_kur_stdout, differing only in logging at err rather than info. This is
1457 # where a kur that dies before it can log for itself ends up being heard
1458 # from... a backend init failure or a missing binary arrives here, which is
1459 # why it is relayed at err and not quietly discarded.
1460 #
1461 # As with stdout the wheel only reports a wheel ID, so the kur name comes
1462 # from wheel_to_kur, and a line that outlives the entry is logged against
1463 # 'unknown'.
1464 #
1465 # POE calling convention... invoked as an object state, without KERNEL...
1466 #
1467 # $_[OBJECT] :: This Ereshkigal instance.
1468 # $_[ARG0] :: The line the child wrote to stderr, as a string, chomped
1469 # here before logging.
1470 # $_[ARG1] :: The ID of the POE::Wheel::Run it came from, used to
1471 # resolve the kur name via wheel_to_kur.
1472 #
1473 # Returns nothing meaningful, an empty return.
1474 #
1475 # # not called directly... wired up when the wheel is created
1476 # POE::Wheel::Run->new( 'StderrEvent' => 'kur_stderr', ... );
1477 0 ▶sub _poe_kur_stderr {
Subroutine _poe_kur_stderr: not called CC=2 SCAR=17.9
1478 0 my ( $self, $line, $wheel_id ) = @_[ OBJECT, ARG0, ARG1 ];
1479  
1480 0 my $name = $self->{wheel_to_kur}{$wheel_id};
1481 0 ▶ $name = 'unknown' if !defined($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 0 0
1482 0 chomp($line);
1483 0 log_drek( 'err', 'kur "' . $name . '" stderr... ' . $line );
1484  
1485 0 return;
1486 } ## end sub _poe_kur_stderr
1487  
1488 # The manager session's kur_reaped handler, fired by the kernel's sig_child
1489 # watch when a kur process exits however it exited... cleanly via stop, by
1490 # signal, or by crashing. This is the whole of the supervision policy.
1491 #
1492 # First the bookkeeping, which happens for every death... the PID is taken
1493 # out of pid_to_kur, and if the registry entry still holds the wheel that is
1494 # dropped from wheel_to_kur and the entry's wheel and pid cleared, so a kur
1495 # that is down is visibly down everywhere. Note the wheel_to_kur cleanup only
1496 # happens while the entry is still around, which is why _poe_remove_kur does
1497 # its own before deleting one.
1498 #
1499 # Then the restart decision. Nothing is restarted while shutting_down is set,
1500 # nor for a kur that has been removed or disabled... those are all deaths we
1501 # asked for. Otherwise the backoff runs... a process that stayed up longer
1502 # than 60 seconds is considered to have started fine and has its delay reset
1503 # to 1, so a kur that is merely restarted occasionally does not creep toward
1504 # the cap. The restart is then scheduled at the current delay and the delay
1505 # doubled for next time, capped at 60 seconds, and the restart count bumped.
1506 #
1507 # POE calling convention... invoked as an object state via sig_child, so note
1508 # the argument slots are the signal handler's rather than ARG0 onward...
1509 #
1510 # $_[OBJECT] :: This Ereshkigal instance.
1511 # $_[KERNEL] :: The POE kernel, used for the delay_set that schedules the
1512 # restart.
1513 # $_[ARG1] :: The PID that exited, which is what pid_to_kur is keyed by.
1514 # A PID that is not in there, which is any child not ours,
1515 # returns immediately.
1516 # $_[ARG2] :: The raw wait status, with the signal that killed it in
1517 # the low seven bits and the exit code in the next eight.
1518 # Both are decoded, so being killed by signal 9 and
1519 # exiting 9 are logged as the different things they are.
1520 # It never changes the decision though. Whether a kur
1521 # comes back is the manager's call alone, so a kur does
1522 # not get a vote by choosing how it exits... a clean exit
1523 # the manager did not ask for is restarted exactly as a
1524 # crash is, and logged as the error it is. The status is
1525 # only ever wording.
1526 #
1527 # Returns nothing meaningful, an empty return.
1528 #
1529 # # not called directly... armed per child when it is spawned
1530 # $kernel->sig_child( $wheel->PID, 'kur_reaped' );
1531 0 ▶sub _poe_kur_reaped {
Subroutine _poe_kur_reaped: not called CC=11 SCAR=48.8
1532 0 my ( $self, $kernel, $pid, $exit ) = @_[ OBJECT, KERNEL, ARG1, ARG2 ];
1533  
1534 0 my $name = delete( $self->{pid_to_kur}{$pid} );
1535 0 ▶ if ( !defined($name) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 0 0 0
1536 0 return;
1537 }
1538  
1539 0 my $entry = $self->{kurs}{$name};
1540 0 ▶ if ( defined($entry) && defined( $entry->{wheel} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry and defined $entry->{"wheel"}) 0 0 0
Condition0%0/3
defined $entry and defined $entry->{"wheel"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $entry and defined $entry->{"wheel"}
defined $entry defined $entry->{"wheel"}
Truth table0%0/3
A and B
A= defined $entryB= defined $entry->{"wheel"}
ABresult
0X0
100
111
1541 0 delete( $self->{wheel_to_kur}{ $entry->{wheel}->ID } );
1542 0 $entry->{wheel} = undef;
1543 0 $entry->{pid} = undef;
1544 }
1545  
1546 # the raw wait status packs the signal that killed it into the low seven
1547 # bits and the exit code into the next eight, so decode both rather than
1548 # shifting blindly... a kur killed by signal 9 and one that exited 9 of
1549 # its own accord are not the same event and should not read alike
1550 0 my $signal = $exit & 127;
1551 0 ▶ my $how = $signal ? 'was killed by signal ' . $signal : 'exited with ' . ( $exit >> 8 );
Branch: 1 branch
BranchTrueFalseTotal
$signal ? : 0 0 0
1552 0 log_drek( 'info', 'kur "' . $name . '" PID ' . $pid . ' ' . $how );
1553  
1554 0 ▶ if ( $self->{shutting_down} || !defined($entry) || !$entry->{enabled} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutting_down"} or not defined $entry or not $entry->{"enabled"}) 0 0 0
Condition0%0/6
$self->{"shutting_down"} or not defined $entry or not $entry->{"enabled"}
l!l&&r!l&&!r
000
$self->{"shutting_down"} or not defined $entry
l!l&&r!l&&!r
000
MC/DC0%0/3
$self->{"shutting_down"} or not defined $entry or not $entry->{"enabled"}
$self->{"shutting_down"} not defined $entry not $entry->{"enabled"}
Truth table0%0/4
A or not(B) or not(C)
A= $self->{"shutting_down"}B= not defined $entryC= not $entry->{"enabled"}
ABCresult
1XX1
01X1
0011
0000
1555 0 return;
1556 }
1557  
1558 # it ran long enough to be considered to have started fine, so reset the backoff
1559 0 ▶ if ( defined( $entry->{spawned} ) && ( time - $entry->{spawned} ) > 60 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"spawned"} and time - $entry->{"spawned"} > 60) 0 0 0
Condition0%0/3
defined $entry->{"spawned"} and time - $entry->{"spawned"} > 60
!ll&&!rl&&r
000
MC/DC0%0/2
defined $entry->{"spawned"} and time - $entry->{"spawned"} > 60
defined $entry->{"spawned"} time - $entry->{"spawned"} > 60
Truth table0%0/3
A and B
A= defined $entry->{"spawned"}B= time - $entry->{"spawned"} > 60
ABresult
0X0
100
111
1560 0 $entry->{delay} = 1;
1561 }
1562  
1563 0 my $delay = $entry->{delay};
1564 0 ▶ $entry->{delay} = $delay * 2 > 60 ? 60 : $delay * 2;
Branch: 1 branch
BranchTrueFalseTotal
$delay * 2 > 60 ? : 0 0 0
1565 0 $entry->{restarts}++;
1566  
1567 # whether a kur comes back is the manager's call and only the manager's...
1568 # a kur does not get a vote in it by choosing how it exits, so anything
1569 # the manager did not itself ask for is restarted, tidily as it may have
1570 # gone. The stops that were asked for never reach here, stop_all having
1571 # set shutting_down and remove_kur having cleared enabled before either
1572 # takes a kur down, so what is left is a kur that went away on its own.
1573 # That is an error whatever status it managed to exit with, and is logged
1574 # as one... the status only changes the wording, never the decision
1575 0 log_drek( 'err', 'kur "' . $name . '" ' . $how . ', restarting in ' . $delay . ' seconds' );
1576  
1577 0 $kernel->delay_set( 'restart_kur', $delay, $name );
1578  
1579 0 return;
1580 } ## end sub _poe_kur_reaped
1581  
1582 # The manager session's remove_kur handler, which stops one kur and drops it
1583 # from the registry for good. The actual removal has to happen in the manager
1584 # session as destroying a POE::Wheel::Run from within another session leaves
1585 # its watchers behind, keeping the manager session alive forever... which is
1586 # why _cmd_remove_kur only marks the entry disabled and posts here rather
1587 # than doing the work itself.
1588 #
1589 # A running kur is asked to stop over its own socket, so it checkpoints its
1590 # tablets and tears its firewall setup down properly. Only if that fails is
1591 # it sent a TERM, which gets the process gone but leaves whatever it was
1592 # holding in the firewall. Either way the entry is then unwired... its wheel
1593 # dropped from wheel_to_kur, its PID from pid_to_kur, and the registry entry
1594 # deleted.
1595 #
1596 # Those two lookups are cleaned here rather than being left to the reap
1597 # handler because the reap handler only cleans them while the registry entry
1598 # is still around, and it is about to not be... without this every add and
1599 # remove cycle would leak a wheel_to_kur entry.
1600 #
1601 # POE calling convention... invoked as an object state, and note it does not
1602 # take KERNEL...
1603 #
1604 # $_[OBJECT] :: This Ereshkigal instance.
1605 # $_[ARG0] :: The kur instance name to remove, as a plain string. A
1606 # name that is no longer registered returns immediately, so
1607 # a doubled post is harmless.
1608 #
1609 # Returns nothing meaningful, an empty return.
1610 #
1611 # # from _cmd_remove_kur, after marking the entry disabled
1612 # $poe_kernel->post( 'ereshkigal_manager', 'remove_kur', $name );
1613 0 ▶sub _poe_remove_kur {
Subroutine _poe_remove_kur: not called CC=7 SCAR=40.3
1614 0 my ( $self, $name ) = @_[ OBJECT, ARG0 ];
1615  
1616 0 my $entry = $self->{kurs}{$name};
1617 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
1618 0 return;
1619 }
1620  
1621 0 ▶ if ( defined( $entry->{pid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"pid"}) 0 0 0
1622 0 eval { $self->_kur_client($name)->call_ok('stop'); };
1623 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1624 0 log_drek( 'err', 'stopping kur "' . $name . '" via it\'s socket failed, sending TERM... ' . $@ );
1625 0 ▶ if ( defined( $entry->{wheel} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"wheel"}) 0 0 0
1626 0 $entry->{wheel}->kill('TERM');
1627 }
1628 }
1629 }
1630  
1631 # the reaped handler only cleans these up while the registry entry is
1632 # still around, which it is about to not be, so they are cleaned here...
1633 # otherwise every add/remove cycle leaks a wheel_to_kur entry
1634 0 ▶ if ( defined( $entry->{wheel} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"wheel"}) 0 0 0
1635 0 delete( $self->{wheel_to_kur}{ $entry->{wheel}->ID } );
1636 }
1637 0 ▶ if ( defined( $entry->{pid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"pid"}) 0 0 0
1638 0 delete( $self->{pid_to_kur}{ $entry->{pid} } );
1639 }
1640  
1641 0 delete( $self->{kurs}{$name} );
1642  
1643 0 log_drek( 'info', 'removed kur "' . $name . '"' );
1644  
1645 0 return;
1646 } ## end sub _poe_remove_kur
1647  
1648 # The manager session's stop_all handler, which brings every kur down and
1649 # then lets the manager session end. Posted by the stop command handler,
1650 # which answers the client first and leaves the shutdown to happen behind
1651 # its back.
1652 #
1653 # Sets shutting_down before anything else, which is what stops _poe_kur_reaped
1654 # from restarting the deaths that are about to happen... without that, every
1655 # kur stopped here would be dutifully brought back.
1656 #
1657 # Then each running kur is asked to stop over its own socket, in name order,
1658 # so it checkpoints and tears its firewall setup down properly. A kur whose
1659 # socket will not answer is sent a TERM instead, which ends the process but
1660 # leaves its firewall state behind. This is done one at a time and inline
1661 # rather than fanned out, as the manager has nothing else to do and each stop
1662 # should be given its own full timeout.
1663 #
1664 # Finally the session's alarms are cleared and the alias dropped, which is
1665 # what actually lets the session, and so the kernel, finish.
1666 #
1667 # POE calling convention... invoked as an object state...
1668 #
1669 # $_[OBJECT] :: This Ereshkigal instance.
1670 # $_[KERNEL] :: The POE kernel, used to clear alarms and drop the alias.
1671 #
1672 # Returns nothing meaningful, an empty return.
1673 #
1674 # # from the stop command handler, after its response has been queued
1675 # $poe_kernel->post( 'ereshkigal_manager', 'stop_all' );
1676 0 ▶sub _poe_stop_all {
Subroutine _poe_stop_all: not called CC=5 SCAR=34.0
1677 0 my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
1678  
1679 0 $self->{shutting_down} = 1;
1680  
1681 0 foreach my $name ( sort( keys( %{ $self->{kurs} } ) ) ) {
1682 0 my $entry = $self->{kurs}{$name};
1683 0 ▶ if ( !defined( $entry->{pid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry->{"pid"}) 0 0 0
1684 0 next;
1685 }
1686 0 eval { $self->_kur_client($name)->call_ok('stop'); };
1687 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1688 0 log_drek( 'err', 'stopping kur "' . $name . '" via it\'s socket failed, sending TERM... ' . $@ );
1689 0 ▶ if ( defined( $entry->{wheel} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"wheel"}) 0 0 0
1690 0 $entry->{wheel}->kill('TERM');
1691 }
1692 }
1693 } ## end foreach my $name ( sort( keys( %{ $self->{kurs}...})))
1694  
1695 0 $kernel->alarm_remove_all;
1696 0 $kernel->alias_remove('ereshkigal_manager');
1697  
1698 0 return;
1699 } ## end sub _poe_stop_all
1700  
1701 #
1702 # JSONUnix command handlers
1703 #
1704  
1705 # Builds the per kur summary rows that _cmd_status and, through it,
1706 # _cmd_status_all hand back as their kurs value. Everything here comes out of
1707 # the manager's own registry... no kur is asked anything, which is the point.
1708 # It is what lets status answer promptly and truthfully even when a kur has
1709 # wedged, and _cmd_status_all is what layers the asking on top.
1710 #
1711 # Takes only the invocant. A real kur's row reports whether it is running,
1712 # from whether the registry holds a PID, along with that PID, its restart
1713 # count, and whether it is enabled. A gate has no process of its own, so
1714 # its row carries its member list instead of a PID or restart count and
1715 # counts as running only when every one of its members is... a gate with a
1716 # dead member reads as not running, which is the honest answer given a
1717 # command through it would only partly land.
1718 #
1719 # Returns a hash ref keyed by kur name. A real kur's value is
1720 # { running => 1|0, pid => PID or undef, restarts => N, enabled => 1|0 } and
1721 # a gate's is { fan_out => [ names ], running => 1|0, enabled => 1|0 }. The
1722 # presence of a fan_out key is how callers tell the two apart, which is what
1723 # _cmd_status_all filters on before deciding who to ask for more.
1724 #
1725 # my $kurs = $self->_kur_summary;
1726 # # { sshd => { running => 1, pid => 4242, restarts => 0, enabled => 1 },
1727 # # baphomet => { fan_out => ['sshd','smtp'], running => 1, enabled => 1 } }
1728 0 ▶sub _kur_summary {
Subroutine _kur_summary: not called CC=9 SCAR=45.0
1729 0 my ($self) = @_;
1730  
1731 0 my $kurs = {};
1732 0 foreach my $name ( keys( %{ $self->{kurs} } ) ) {
1733 0 my $entry = $self->{kurs}{$name};
1734 # a fan_out kur has no process of its own... it counts as running
1735 # when every member is
1736 0 ▶ if ( defined( $entry->{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"opts"}{"fan_out"}) 0 0 0
1737 0 my $running = 1;
1738 0 foreach my $member ( @{ $entry->{opts}{fan_out} } ) {
1739 0 ▶ if ( !defined( $self->{kurs}{$member} ) || !defined( $self->{kurs}{$member}{pid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$member} and defined $self->{"kurs"}{$member}{"pid"}) 0 0 0
Condition0%0/3
defined $self->{"kurs"}{$member} and defined $self->{"kurs"}{$member}{"pid"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"kurs"}{$member} and defined $self->{"kurs"}{$member}{"pid"}
defined $self->{"kurs"}{$member} defined $self->{"kurs"}{$member}{"pid"}
Truth table0%0/3
A and B
A= defined $self->{"kurs"}{$member}B= defined $self->{"kurs"}{$member}{"pid"}
ABresult
0X0
100
111
1740 0 $running = 0;
1741 0 last;
1742 }
1743 }
1744 $kurs->{$name} = {
1745 'fan_out' => $entry->{opts}{fan_out},
1746 'running' => $running,
1747 0 ▶ 'enabled' => $entry->{enabled} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'enabled'} ? : 0 0 0
1748 };
1749 0 next;
1750 } ## end if ( defined( $entry->{opts}{fan_out} ) )
1751 $kurs->{$name} = {
1752 'running' => defined( $entry->{pid} ) ? 1 : 0,
1753 'pid' => $entry->{pid},
1754 'restarts' => $entry->{restarts},
1755 0 ▶ 'enabled' => $entry->{enabled} ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
defined $entry->{'pid'} ? : 0 0 0
$entry->{'enabled'} ? : 0 0 0
1756 };
1757 } ## end foreach my $name ( keys( %{ $self->{kurs} } ) )
1758  
1759 0 return $kurs;
1760 } ## end sub _kur_summary
1761  
1762 # Handles the status command... the manager's own info plus the bare summary
1763 # row for each kur, without asking any kur process anything. That is what
1764 # makes it the cheap view and the one to reach for when something has gone
1765 # quiet, as it answers from the registry alone and so cannot be held up by a
1766 # kur that will not talk.
1767 #
1768 # Takes only the invocant. Authorization is not done here... the dispatch
1769 # entry in start_server has already run _authorize with no kur names, this
1770 # being a manager level view.
1771 #
1772 # Returns a hash ref carrying the manager's pid, its uptime in seconds since
1773 # start_server finished coming up, the config path it was loaded from,
1774 # enable_auth as 1 or 0, and kurs holding whatever _kur_summary built.
1775 #
1776 # my $status = $self->_cmd_status;
1777 # # { pid => 1234, uptime => 3600, config => '/usr/local/etc/ereshkigal.toml',
1778 # # enable_auth => 0, kurs => { sshd => { running => 1, ... } } }
1779 0 ▶sub _cmd_status {
Subroutine _cmd_status: not called CC=2 SCAR=17.9
1780 0 my ($self) = @_;
1781  
1782 return {
1783 'pid' => $$,
1784 'uptime' => time - $self->{started},
1785 'config' => $self->{config},
1786 0 ▶ 'enable_auth' => $self->{enable_auth} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$self->{'enable_auth'} ? : 0 0 0
1787 'kurs' => $self->_kur_summary,
1788 };
1789 } ## end sub _cmd_status
1790  
1791 # Handles the status_all command... _cmd_status with each running real kur
1792 # additionally asked for its own status, which is where ban counts, the next
1793 # expiry, the CIDR flags, per instance stats, and what unbans are still owed
1794 # to the firewall come from. Those live kur side, so the only way to have
1795 # them is to ask.
1796 #
1797 # Takes only the invocant. Only running real kurs are asked... a stopped one
1798 # has nothing to answer with and stays a bare summary row, and a gate has no
1799 # socket of its own, its members being asked in their own right anyway.
1800 #
1801 # A kur that is running but will not answer has its failure reported under a
1802 # error key on its row rather than a status one, which is the same shape
1803 # _cmd_status_kur uses, so a consumer checks one place for either view.
1804 #
1805 # Returns the same hash ref shape _cmd_status does, with each asked kur's row
1806 # gaining either a status key holding that kur's whole status hash or an error
1807 # key holding why it could not be had.
1808 #
1809 # my $status = $self->_cmd_status_all;
1810 # # $status->{kurs}{sshd}{status}{banned_count} is 12
1811 # # $status->{kurs}{smtp}{error} is 'timed out after 30 seconds'
1812 0 ▶sub _cmd_status_all {
Subroutine _cmd_status_all: not called CC=4 SCAR=30.0
1813 0 my ($self) = @_;
1814  
1815 0 my $status = $self->_cmd_status;
1816  
1817 # only the running real ones... a not running kur stays a bare summary
1818 # row and a fan_out kur has no socket to ask
1819 0 ▶ my @running = grep { $status->{kurs}{$_}{running} && !defined( $status->{kurs}{$_}{fan_out} ) }
Condition0%0/3
$status->{'kurs'}{$_}{'running'} && !defined($status->{'kurs'}{$_}{'fan_out'})
!ll&&!rl&&r
000
MC/DC0%0/2
$status->{'kurs'}{$_}{'running'} && !defined($status->{'kurs'}{$_}{'fan_out'})
$status->{'kurs'}{$_}{'running'} !defined($status->{'kurs'}{$_}{'fan_out'})
Truth table0%0/3
A && not(B)
A= $status->{'kurs'}{$_}{'running'}B= !defined($status->{'kurs'}{$_}{'fan_out'})
ABresult
0X0
100
111
1820 0 sort( keys( %{ $status->{kurs} } ) );
1821 0 my $answers = $self->_fan_out( \@running, 'status' );
1822 0 foreach my $name (@running) {
1823 0 ▶ if ( defined( $answers->{$name}{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $answers->{$name}{'error'}) { } 0 0 0
1824 0 $status->{kurs}{$name}{error} = $answers->{$name}{error};
1825 } else {
1826 0 $status->{kurs}{$name}{status} = $answers->{$name};
1827 }
1828 }
1829  
1830 0 return $status;
1831 } ## end sub _cmd_status_all
1832  
1833 # Handles the status_kur command... the summary row for the kur named by
1834 # args.name plus its own status when running, or the member list plus each
1835 # member's status when it is a gate.
1836 #
1837 # Note the ordering... the name is authorized before the registry is
1838 # consulted, so a caller who is not entitled to a kur cannot tell a refusal
1839 # from a nonexistent name and so cannot use the difference to enumerate what
1840 # the manager is carrying. Every targeted command handler does this.
1841 #
1842 # A running kur is asked through _fan_out rather than a bare client call, so
1843 # a live process with a wedged socket degrades to an error entry rather than
1844 # dying the whole command, and that error is reported under an error key
1845 # beside status rather than nested inside it... the same shape
1846 # _cmd_status_all uses.
1847 #
1848 # Args...
1849 #
1850 # $request :: Required. The decoded request hash ref. Must carry an args
1851 # key holding a hash ref with a name key naming the kur, as a
1852 # plain string. A missing args or name dies.
1853 # $ctx :: The JSONUnix context for the connection, handed to
1854 # _authorize. May be undef when enable_auth is off, as
1855 # _authorize returns before touching it.
1856 #
1857 # Returns, for a real kur, a hash ref of { name, running, pid, restarts,
1858 # enabled }, gaining either a status key holding that kur's full status hash
1859 # or an error key when it is running but could not be reached. For a gate it
1860 # is { name, fan_out => [ members ], enabled, kurs => { per member } }, with
1861 # no running or pid of its own.
1862 #
1863 # Dies with a plain string when args.name is missing or names no registered
1864 # kur. Authorization failures die with the { error, code } hash ref
1865 # _authorize raises, code being 'permission_denied'.
1866 #
1867 # my $status = $self->_cmd_status_kur( { 'args' => { 'name' => 'sshd' } }, $ctx );
1868 # # { name => 'sshd', running => 1, pid => 4242, restarts => 0,
1869 # # enabled => 1, status => { backend => 'pf', banned_count => 12, ... } }
1870 0 ▶sub _cmd_status_kur {
Subroutine _cmd_status_kur: not called CC=10 SCAR=47.0
1871 0 my ( $self, $request, $ctx ) = @_;
1872  
1873 0 my $args = $request->{args};
1874 0 ▶ if ( !defined($args) || !defined( $args->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args and defined $args->{"name"}) 0 0 0
Condition0%0/3
defined $args and defined $args->{"name"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"name"}
defined $args defined $args->{"name"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"name"}
ABresult
0X0
100
111
1875 0 die('args.name must be the name of a kur instance');
1876 }
1877 0 my $name = $args->{name};
1878  
1879 # authorized before existence is checked, so an unauthorized caller can
1880 # not use the difference in errors to enumerate kur names
1881 0 $self->_authorize( $ctx, $name );
1882  
1883 0 my $entry = $self->{kurs}{$name};
1884 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
1885 0 die( 'No such kur instance, "' . $name . '"' );
1886 }
1887  
1888 # a fan_out kur has no process of its own, so its status is its
1889 # member list plus each member's status
1890 0 ▶ if ( defined( $entry->{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $entry->{"opts"}{"fan_out"}) 0 0 0
1891 return {
1892 'name' => $name,
1893 'fan_out' => $entry->{opts}{fan_out},
1894 'enabled' => $entry->{enabled} ? 1 : 0,
1895 0 ▶ 'kurs' => $self->_fan_out( $entry->{opts}{fan_out}, 'status' ),
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'enabled'} ? : 0 0 0
1896 };
1897 }
1898  
1899 my $status = {
1900 'name' => $name,
1901 'running' => defined( $entry->{pid} ) ? 1 : 0,
1902 'pid' => $entry->{pid},
1903 'restarts' => $entry->{restarts},
1904 0 ▶ 'enabled' => $entry->{enabled} ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
defined $entry->{'pid'} ? : 0 0 0
$entry->{'enabled'} ? : 0 0 0
1905 };
1906  
1907 0 ▶ if ( $status->{running} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status->{"running"}) 0 0 0
1908 # via _fan_out rather than a bare call_ok so a live process with a
1909 # wedged socket degrades to an error entry, reported under the same
1910 # error key status_all uses rather than nested inside status
1911 0 my $answer = $self->_fan_out( [$name], 'status' )->{$name};
1912 0 ▶ if ( defined( $answer->{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $answer->{'error'}) { } 0 0 0
1913 0 $status->{error} = $answer->{error};
1914 } else {
1915 0 $status->{status} = $answer;
1916 }
1917 } ## end if ( $status->{running} )
1918  
1919 0 return $status;
1920 } ## end sub _cmd_status_kur
1921  
1922 # Handles the banned command... fans banned out to every real kur and trims
1923 # each successful answer down to the fields this view is about, dropping
1924 # anything else the kur happened to include.
1925 #
1926 # Takes only the invocant. Authorization has already been done by the
1927 # dispatch entry, against every real kur, this being an untargeted command.
1928 # Gates are not asked, _real_kur_names excluding them, as their members are
1929 # each asked in their own right.
1930 #
1931 # The trimming is an explicit whitelist rather than a passthrough, so any
1932 # field a kur learns to report has to be added here as well or it will never
1933 # reach a consumer... the retry books are in the list for exactly that
1934 # reason, having once been dropped on the way out.
1935 #
1936 # A kur that could not be reached keeps its { error => ... } row untouched,
1937 # the trimming only applying to successful answers.
1938 #
1939 # Returns a hash ref of { kurs => { name => row } }. A successful row carries
1940 # banned as an array ref of the IPs the firewall itself reports, expires as a
1941 # hash ref of IP to the epoch its sentence ends with 0 meaning never, the
1942 # same pair as banned_cidr and cidr_expires for ranges, and unban_retries and
1943 # cidr_unban_retries as hash refs of entry to its retry book keeping. A
1944 # failed row is { error => '...' }.
1945 #
1946 # my $result = $self->_cmd_banned;
1947 # # { kurs => { sshd => { banned => ['1.2.3.4'],
1948 # # expires => { '1.2.3.4' => 1785919052 },
1949 # # banned_cidr => [], cidr_expires => {},
1950 # # unban_retries => {}, cidr_unban_retries => {} } } }
1951 0 ▶sub _cmd_banned {
Subroutine _cmd_banned: not called CC=3 SCAR=24.8
1952 0 my ($self) = @_;
1953  
1954 0 my $kurs = $self->_fan_out( [ $self->_real_kur_names ], 'banned' );
1955 0 foreach my $name ( keys( %{$kurs} ) ) {
1956 0 ▶ if ( !defined( $kurs->{$name}{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $kurs->{$name}{"error"}) 0 0 0
1957 $kurs->{$name} = {
1958 'banned' => $kurs->{$name}{banned},
1959 'expires' => $kurs->{$name}{expires},
1960 'banned_cidr' => $kurs->{$name}{banned_cidr},
1961 'cidr_expires' => $kurs->{$name}{cidr_expires},
1962 'unban_retries' => $kurs->{$name}{unban_retries},
1963 'cidr_unban_retries' => $kurs->{$name}{cidr_unban_retries},
1964 0 };
1965 } ## end if ( !defined( $kurs->{$name}{error} ) )
1966 } ## end foreach my $name ( keys( %{$kurs} ) )
1967  
1968 0 return { 'kurs' => $kurs };
1969 } ## end sub _cmd_banned
1970  
1971 # Handles the ban command... fans args.ips out to the targeted kurs. All of
1972 # the shared validate, authorize, and fan out work lives in _cmd_ban_common,
1973 # this being nothing but the single IP half of the spec that tells it apart
1974 # from the CIDR one.
1975 #
1976 # Args...
1977 #
1978 # $request :: Required. The decoded request hash ref. Must carry args
1979 # holding an ips key with an array ref of one or more IPs, and
1980 # may carry a kur key naming one kur or gate to send them to
1981 # and a ban_time key overriding how long they last. See
1982 # _cmd_ban_common, which does the judging.
1983 # $ctx :: The JSONUnix context, handed through to _authorize. May be
1984 # undef when enable_auth is off.
1985 #
1986 # Returns whatever _cmd_ban_common returns... a hash ref of
1987 # { kurs => { name => per kur result } } plus a rejected key when any of the
1988 # IPs would not validate.
1989 #
1990 # Dies as _cmd_ban_common does... a plain string for a bad request or a
1991 # unknown kur, or the { error, code } hash ref from _authorize for a refusal.
1992 #
1993 # my $result = $self->_cmd_ban(
1994 # { 'args' => { 'ips' => ['1.2.3.4'], 'kur' => 'sshd' } }, $ctx );
1995 0 ▶sub _cmd_ban {
Subroutine _cmd_ban: not called CC=1 SCAR=6.9
1996 0 my ( $self, $request, $ctx ) = @_;
1997  
1998 0 return $self->_cmd_ban_common(
1999 $request, $ctx,
2000 {
2001 'arg_key' => 'ips',
2002 'noun' => 'IP',
2003 'noun_long' => 'IPv4 or IPv6 IP',
2004 'normalizer' => \&normalize_ip,
2005 'command' => 'ban',
2006 }
2007 );
2008 } ## end sub _cmd_ban
2009  
2010 # Handles the unban command... args.all set fans flush out to every real kur,
2011 # otherwise args.ip is normalized and unban fanned out instead.
2012 #
2013 # There is deliberately no kur targeting here, unlike ban... an unban goes
2014 # wherever the address actually is, every real kur being asked whether it is
2015 # holding it and releasing it if so. That is why the per kur answers carry
2016 # was_banned rather than a plain success, and why a kur that never had the IP
2017 # is not an error.
2018 #
2019 # The all form is a flush rather than a mass unban, so it empties range bans
2020 # alongside single IPs on every kur in one command.
2021 #
2022 # Note this takes no context and does no authorizing of its own... the
2023 # dispatch entry in start_server has already authorized against every real
2024 # kur before calling, this being untargeted either way.
2025 #
2026 # Args...
2027 #
2028 # $request :: Required. The decoded request hash ref. Must carry args
2029 # holding either a true all key or an ip key with a single
2030 # IPv4 or IPv6 address as a plain string. Neither one dies.
2031 # The IP is normalized here rather than kur side, so garbage
2032 # is bounced once instead of by every kur, and what is fanned
2033 # out is the canonical form... which is what lets a variant
2034 # spelling of an IPv6 address still find its ban.
2035 #
2036 # Returns a hash ref of { kurs => { name => per kur result } }. For the all
2037 # form each result is that kur's flush answer, { flushed => 1 }; for a single
2038 # IP it is { ip => '...', was_banned => 1|0 }. Unreachable kurs are
2039 # { error => '...' } as always.
2040 #
2041 # Dies with a plain string when neither args.all nor args.ip is given, or
2042 # when args.ip will not normalize as an IP.
2043 #
2044 # my $result = $self->_cmd_unban( { 'args' => { 'ip' => '1.2.3.4' } } );
2045 # # { kurs => { sshd => { ip => '1.2.3.4', was_banned => 1 },
2046 # # smtp => { ip => '1.2.3.4', was_banned => 0 } } }
2047 #
2048 # my $result = $self->_cmd_unban( { 'args' => { 'all' => 1 } } );
2049 # # { kurs => { sshd => { flushed => 1 }, smtp => { flushed => 1 } } }
2050 0 ▶sub _cmd_unban {
Subroutine _cmd_unban: not called CC=6 SCAR=37.4
2051 0 my ( $self, $request ) = @_;
2052  
2053 0 my $args = $request->{args};
2054 0 ▶ if ( !defined($args) || ( !$args->{all} && !defined( $args->{ip} ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args and $args->{"all"} || defined $args->{"ip"}) 0 0 0
Condition0%0/6
defined $args and $args->{"all"} || defined $args->{"ip"}
!ll&&!rl&&r
000
$args->{"all"} or defined $args->{"ip"}
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $args and $args->{"all"} || defined $args->{"ip"}
defined $args $args->{"all"} defined $args->{"ip"}
Truth table0%0/4
A and B or C
A= defined $argsB= $args->{"all"}C= defined $args->{"ip"}
ABCresult
0XX0
1000
11X1
1011
2055 0 die('Either args.all must be true or args.ip must be an IP');
2056 }
2057  
2058 0 my @all = $self->_real_kur_names;
2059 0 my $kurs;
2060 0 ▶ if ( $args->{all} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'all'}) { } 0 0 0
2061 0 $kurs = $self->_fan_out( \@all, 'flush' );
2062 } else {
2063 # bounce garbage here instead of fanning it out just for every kur
2064 # to report it absent, and fan out the canonical form so variant
2065 # spellings of the same IP all find the ban
2066 0 my $ip = normalize_ip( $args->{ip} );
2067 0 ▶ if ( !defined($ip) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ip) 0 0 0
2068 0 die( '"' . $args->{ip} . '" does not appear to be an IPv4 or IPv6 IP' );
2069 }
2070 # the kur checks if the IP is present and only unbans it if it is,
2071 # reporting back via was_banned
2072 0 $kurs = $self->_fan_out( \@all, 'unban', { 'ip' => $ip } );
2073 } ## end else [ if ( $args->{all} ) ]
2074  
2075 0 return { 'kurs' => $kurs };
2076 } ## end sub _cmd_unban
2077  
2078 # The CIDR twin of _cmd_ban... fans args.cidrs out to the targeted kurs, all
2079 # of the shared validate, authorize, and fan out work living in
2080 # _cmd_ban_common. Only the spec differs... the args key, the normalizer, the
2081 # kur command, and the noun used in error messages.
2082 #
2083 # Whether a given kur will actually act on it is not decided here. A kur with
2084 # CIDR banning off, or on a backend that cannot match a prefix, either
2085 # refuses or silently drops per its own cidr_silent_drop setting, and that
2086 # answer comes back in its row like any other.
2087 #
2088 # Args...
2089 #
2090 # $request :: Required. The decoded request hash ref. Must carry args
2091 # holding a cidrs key with an array ref of one or more ranges,
2092 # and may carry kur and ban_time exactly as ban does. Host
2093 # bits are masked off during pre-flight, so 1.2.3.4/24 and
2094 # 1.2.3.0/24 are the same range and dedupe against each other.
2095 # $ctx :: The JSONUnix context, handed through to _authorize. May be
2096 # undef when enable_auth is off.
2097 #
2098 # Returns whatever _cmd_ban_common returns... { kurs => { name => result } }
2099 # plus a rejected key when any of the ranges would not validate.
2100 #
2101 # Dies as _cmd_ban_common does... a plain string for a bad request or unknown
2102 # kur, or the { error, code } hash ref from _authorize.
2103 #
2104 # my $result = $self->_cmd_cidr_ban(
2105 # { 'args' => { 'cidrs' => ['1.2.3.0/24'], 'ban_time' => 0 } }, $ctx );
2106 0 ▶sub _cmd_cidr_ban {
Subroutine _cmd_cidr_ban: not called CC=1 SCAR=6.9
2107 0 my ( $self, $request, $ctx ) = @_;
2108  
2109 0 return $self->_cmd_ban_common(
2110 $request, $ctx,
2111 {
2112 'arg_key' => 'cidrs',
2113 'noun' => 'CIDR',
2114 'noun_long' => 'IPv4 or IPv6 CIDR',
2115 'normalizer' => \&normalize_cidr,
2116 'command' => 'cidr_ban',
2117 }
2118 );
2119 } ## end sub _cmd_cidr_ban
2120  
2121 # The shared body of _cmd_ban and _cmd_cidr_ban, which differ only in the
2122 # args key, the normalizer, the kur command, and the noun used in errors.
2123 #
2124 # The ordering here is deliberate and worth keeping. Targets are resolved and
2125 # authorization checked before anything is done with the payload, so a caller
2126 # who is not entitled can neither enumerate kur names nor make the manager
2127 # burn cycles validating a list it is never going to send. Within that, a
2128 # named kur is authorized against the name as given rather than what it
2129 # expands to, which is what makes a gate grant cover its members; and a
2130 # untargeted command authorizes before reporting that there are no kurs, so
2131 # a refusal never leaks whether the manager is carrying anything.
2132 #
2133 # Entries are then pre-flighted... each is normalized, garbage collected into
2134 # a rejected hash rather than being fanned out for every kur to bounce
2135 # separately, and duplicates dropped. Normalizing here also means variant
2136 # spellings of one address dedupe against each other and what reaches the
2137 # kurs is canonical. A request where nothing at all survives is a die rather
2138 # than a fan out of nothing.
2139 #
2140 # Args, all required and positional...
2141 #
2142 # $request :: The decoded request hash ref. Must carry args holding the
2143 # spec's arg_key with an array ref of one or more entries. May
2144 # also carry kur, naming one kur or gate rather than all of
2145 # them, and ban_time, an override in seconds passed through
2146 # unvalidated for the kur to judge, 0 meaning never expire.
2147 # $ctx :: The JSONUnix context for the connection, handed to
2148 # _authorize. May be undef when enable_auth is off.
2149 # $spec :: A hash ref of the per family knobs, which is how the two
2150 # callers differ. Every key is required...
2151 # arg_key :: the args key holding the entries, 'ips' or
2152 # 'cidrs'
2153 # noun :: the short noun for errors, 'IP' or 'CIDR'
2154 # noun_long :: the long one, 'IPv4 or IPv6 IP' or the CIDR
2155 # equivalent
2156 # normalizer :: a code ref taking a raw entry and returning
2157 # its canonical form or undef, so normalize_ip
2158 # or normalize_cidr
2159 # command :: the command name to fan out, 'ban' or
2160 # 'cidr_ban'
2161 #
2162 # Returns a hash ref carrying kurs, a hash ref of kur name to that kur's
2163 # per entry results, and, only when something was refused during pre-flight,
2164 # rejected, a hash ref of the raw entry to
2165 # { status => 'error', error => '...' }. The rejected key being absent is how
2166 # a caller knows every entry it sent was at least well formed.
2167 #
2168 # Dies with a plain string when args or the entry array is missing or empty,
2169 # when a named kur is not registered, or when not one entry validated.
2170 # Authorization failures die with _authorize's { error, code } hash ref.
2171 #
2172 # my $result = $self->_cmd_ban_common(
2173 # $request, $ctx,
2174 # {
2175 # 'arg_key' => 'ips',
2176 # 'noun' => 'IP',
2177 # 'noun_long' => 'IPv4 or IPv6 IP',
2178 # 'normalizer' => \&normalize_ip,
2179 # 'command' => 'ban',
2180 # }
2181 # );
2182 # # { kurs => { sshd => { ips => { '1.2.3.4' => { status => 'ok' } } } },
2183 # # rejected => { 'nope' => { status => 'error', error => '...' } } }
2184 0 ▶sub _cmd_ban_common {
Subroutine _cmd_ban_common: not called CC=17 SCAR=57.2
2185 0 my ( $self, $request, $ctx, $spec ) = @_;
2186  
2187 0 my $args = $request->{args};
2188 0 my $arg_key = $spec->{arg_key};
2189 0 ▶ if ( !defined($args) || ref( $args->{$arg_key} ) ne 'ARRAY' || !@{ $args->{$arg_key} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $args or ref $args->{$arg_key} ne "ARRAY" or not @{$args->{$arg_key};}) 0 0 0
Condition0%0/6
not defined $args or ref $args->{$arg_key} ne "ARRAY" or not @{$args->{$arg_key};}
l!l&&r!l&&!r
000
not defined $args or ref $args->{$arg_key} ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/3
not defined $args or ref $args->{$arg_key} ne "ARRAY" or not @{$args->{$arg_key};}
not defined $args ref $args->{$arg_key} ne "ARRAY" not @{$args->{$arg_key};}
Truth table0%0/4
not(A) or B or not(C)
A= not defined $argsB= ref $args->{$arg_key} ne "ARRAY"C= not @{$args->{$arg_key};}
ABCresult
1XX1
01X1
0011
0000
2190 0 die( 'args.' . $arg_key . ' must be an array of one or more ' . $spec->{noun} . 's' );
2191 }
2192  
2193 # targets are resolved and authorization checked before anything is done
2194 # with the payload, so an unauthorized caller can neither enumerate kur
2195 # names nor burn cycles on validation
2196 0 my @targets;
2197 0 ▶ if ( defined( $args->{kur} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{'kur'}) { } 0 0 0
2198 # authorization is checked against the requested name... for a
2199 # fan_out kur being authorized for the gateway is the grant, which
2200 # is what makes one usable as a single point of contact
2201 0 $self->_authorize( $ctx, $args->{kur} );
2202 0 ▶ if ( !defined( $self->{kurs}{ $args->{kur} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$args->{"kur"}}) 0 0 0
2203 0 die( 'No such kur instance, "' . $args->{kur} . '"' );
2204 }
2205 0 @targets = $self->_expand_kur_targets( $args->{kur} );
2206 } else {
2207 0 @targets = $self->_real_kur_names;
2208 # authorized before the empty check, matching every other untargeted
2209 # command... with zero real kurs this is the manager level check, so
2210 # an unauthorized caller is refused rather than being told what the
2211 # manager is carrying
2212 0 $self->_authorize( $ctx, @targets );
2213 0 ▶ if ( !@targets ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@targets) 0 0 0
2214 0 die('No kur instances');
2215 }
2216 } ## end else [ if ( defined( $args->{kur} ) ) ]
2217  
2218 # ban_time is pre-flighted for the same reason the entries below are...
2219 # every kur would otherwise judge it separately and answer with the same
2220 # error, so a single bad value comes back N times rather than once. The
2221 # check matches the kur's own in Ereshkigal::Kur::_resolve_ban_time, which
2222 # still runs and is still the authority for anything reaching a kur by
2223 # another route
2224 0 ▶ if ( defined( $args->{ban_time} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"ban_time"} and ref $args->{"ban_time"} ne "" || !($args->{"ban_time"} =~ /^[0-9]+$/)) 0 0 0
Condition0%0/6
defined $args->{"ban_time"} and ref $args->{"ban_time"} ne "" || !($args->{"ban_time"} =~ /^[0-9]+$/)
!ll&&!rl&&r
000
ref $args->{"ban_time"} ne "" or not $args->{"ban_time"} =~ /^[0-9]+$/
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $args->{"ban_time"} and ref $args->{"ban_time"} ne "" || !($args->{"ban_time"} =~ /^[0-9]+$/)
defined $args->{"ban_time"} ref $args->{"ban_time"} ne "" not $args->{"ban_time"} =~ /^[0-9]+$/
Truth table0%0/4
A and B or not(C)
A= defined $args->{"ban_time"}B= ref $args->{"ban_time"} ne ""C= not $args->{"ban_time"} =~ /^[0-9]+$/
ABCresult
0XX0
1000
11X1
1011
2225 && ( ref( $args->{ban_time} ) ne '' || $args->{ban_time} !~ /^[0-9]+$/ ) )
2226 {
2227 0 die('args.ban_time must be a non-negative int of seconds');
2228 }
2229  
2230 # pre-flight the entries so garbage is bounced here instead of being
2231 # fanned out just for every kur to bounce it, and so what is fanned out
2232 # is the canonical form... variant spellings also dedupe here
2233 0 my @entries;
2234 my %seen;
2235 0 my $rejected = {};
2236 0 foreach my $raw_entry ( @{ $args->{$arg_key} } ) {
2237 0 my $entry = $spec->{normalizer}->($raw_entry);
2238 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
2239 0 ▶ my $key = defined($raw_entry) ? $raw_entry : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $raw_entry ? : 0 0 0
2240 $rejected->{$key}
2241 0 = { 'status' => 'error', 'error' => '"' . $key . '" does not appear to be an ' . $spec->{noun_long} };
2242 0 next;
2243 }
2244 0 ▶ if ( !$seen{$entry} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen{$entry}) 0 0 0
2245 0 $seen{$entry} = 1;
2246 0 push( @entries, $entry );
2247 }
2248 } ## end foreach my $raw_entry ( @{ $args->{$arg_key} } )
2249 0 ▶ if ( !@entries ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@entries) 0 0 0
2250 0 die( 'None of the ' . $spec->{noun} . 's in args.' . $arg_key . ' appear to be an ' . $spec->{noun_long} );
2251 }
2252  
2253 0 my $kur_args = { $arg_key => \@entries };
2254 0 ▶ if ( defined( $args->{ban_time} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"ban_time"}) 0 0 0
2255 0 $kur_args->{ban_time} = $args->{ban_time};
2256 }
2257  
2258 0 my $response = { 'kurs' => $self->_fan_out( \@targets, $spec->{command}, $kur_args ) };
2259 0 ▶ if ( %{$rejected} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$rejected;}) 0 0 0
2260 0 $response->{rejected} = $rejected;
2261 }
2262  
2263 0 return $response;
2264 } ## end sub _cmd_ban_common
2265  
2266 # The CIDR twin of _cmd_unban, minus the all form... args.cidr is normalized
2267 # and cidr_unban fanned out to every real kur. There is no all here because
2268 # unban --all already flushes ranges alongside single IPs, so a second way to
2269 # empty everything would only be a second way to get it wrong.
2270 #
2271 # As with unban there is no kur targeting... every real kur is asked whether
2272 # it holds the range and releases it if so. Host bits are masked off during
2273 # normalization, so naming any address inside a banned network finds it.
2274 #
2275 # Takes no context and authorizes nothing itself... the dispatch entry has
2276 # already authorized against every real kur.
2277 #
2278 # Args...
2279 #
2280 # $request :: Required. The decoded request hash ref. Must carry args
2281 # holding a cidr key with a single range as a plain string,
2282 # such as '1.2.3.0/24'. Normalized here rather than kur side
2283 # so garbage is bounced once and what is fanned out is the
2284 # canonical network form.
2285 #
2286 # Returns a hash ref of { kurs => { name => per kur result } }, each result
2287 # being { cidr => '...', was_banned => 1|0 }, or { error => '...' } for a kur
2288 # that could not be reached.
2289 #
2290 # Dies with a plain string when args.cidr is missing or will not normalize.
2291 #
2292 # my $result = $self->_cmd_cidr_unban( { 'args' => { 'cidr' => '1.2.3.4/24' } } );
2293 # # { kurs => { sshd => { cidr => '1.2.3.0/24', was_banned => 1 } } }
2294 0 ▶sub _cmd_cidr_unban {
Subroutine _cmd_cidr_unban: not called CC=4 SCAR=30.0
2295 0 my ( $self, $request ) = @_;
2296  
2297 0 my $args = $request->{args};
2298 0 ▶ if ( !defined($args) || !defined( $args->{cidr} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args and defined $args->{"cidr"}) 0 0 0
Condition0%0/3
defined $args and defined $args->{"cidr"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"cidr"}
defined $args defined $args->{"cidr"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"cidr"}
ABresult
0X0
100
111
2299 0 die('args.cidr must be a CIDR');
2300 }
2301  
2302 # bounce garbage here instead of fanning it out just for every kur to
2303 # report it absent, and fan out the canonical network form so variant
2304 # spellings of the same range all find the ban
2305 0 my $cidr = normalize_cidr( $args->{cidr} );
2306 0 ▶ if ( !defined($cidr) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cidr) 0 0 0
2307 0 die( '"' . $args->{cidr} . '" does not appear to be an IPv4 or IPv6 CIDR' );
2308 }
2309  
2310 # the kur checks if the CIDR is present and only unbans it if it is,
2311 # reporting back via was_banned
2312 0 my $kurs = $self->_fan_out( [ $self->_real_kur_names ], 'cidr_unban', { 'cidr' => $cidr } );
2313  
2314 0 return { 'kurs' => $kurs };
2315 } ## end sub _cmd_cidr_unban
2316  
2317 # Handles the checkpoint command... fans checkpoint out to the kurs behind
2318 # args.kur when given, or every real kur otherwise, having each write its
2319 # tablets to disk now rather than waiting for its next mutation or interval.
2320 #
2321 # Authorization follows the same pattern every targeted command uses... a
2322 # named kur is authorized against the name as given, before the registry is
2323 # consulted, so a gate grant covers the fanned command and kur names cannot
2324 # be enumerated by the difference between a refusal and an unknown name. The
2325 # untargeted form authorizes against every real kur, which with none
2326 # registered is the manager level check.
2327 #
2328 # Args...
2329 #
2330 # $request :: Required. The decoded request hash ref. args is optional
2331 # here, and when present may carry a kur key naming one kur
2332 # or gate. With no args, or no kur key, every real kur is
2333 # checkpointed.
2334 # $ctx :: The JSONUnix context, handed to _authorize. May be undef
2335 # when enable_auth is off.
2336 #
2337 # Returns a hash ref of { kurs => { name => per kur result } }, each result
2338 # being that kur's checkpoint answer... { checkpointed => 1, bans => N,
2339 # cidr_bans => N, unban_retries => N, cidr_unban_retries => N }, or
2340 # { error => '...' } for one that could not be reached.
2341 #
2342 # Dies with a plain string when args.kur names no registered kur, or with
2343 # _authorize's { error, code } hash ref on a refusal.
2344 #
2345 # my $result = $self->_cmd_checkpoint( {}, $ctx ); # all
2346 # my $result = $self->_cmd_checkpoint( { 'args' => { 'kur' => 'sshd' } }, $ctx );
2347 0 ▶sub _cmd_checkpoint {
Subroutine _cmd_checkpoint: not called CC=4 SCAR=30.0
2348 0 my ( $self, $request, $ctx ) = @_;
2349  
2350 0 my $args = $request->{args};
2351  
2352 0 my @targets;
2353 0 ▶ if ( defined($args) && defined( $args->{kur} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args and defined $args->{'kur'}) { } 0 0 0
Condition0%0/3
defined $args and defined $args->{"kur"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"kur"}
defined $args defined $args->{"kur"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"kur"}
ABresult
0X0
100
111
2354 # like ban, authorization is against the requested name, so a
2355 # fan_out kur grant covers the fanned command... and it comes before
2356 # the existence check so kur names cannot be enumerated
2357 0 $self->_authorize( $ctx, $args->{kur} );
2358 0 ▶ if ( !defined( $self->{kurs}{ $args->{kur} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$args->{"kur"}}) 0 0 0
2359 0 die( 'No such kur instance, "' . $args->{kur} . '"' );
2360 }
2361 0 @targets = $self->_expand_kur_targets( $args->{kur} );
2362 } else {
2363 0 @targets = $self->_real_kur_names;
2364 0 $self->_authorize( $ctx, @targets );
2365 }
2366  
2367 0 return { 'kurs' => $self->_fan_out( \@targets, 'checkpoint' ) };
2368 } ## end sub _cmd_checkpoint
2369  
2370 # Handles the re_init command... fans re_init out the same way checkpoint
2371 # does, having the kurs tear their firewall setup down and rebuild it from
2372 # what their ban books carry. This is the repair for a setup something
2373 # outside Ereshkigal has interfered with, a firewall reload or a flushed
2374 # table having taken the rules with it.
2375 #
2376 # Worth knowing what it costs... bans are not enforced during the rebuild,
2377 # brief as that window is, so it is not something to fan at every kur on a
2378 # busy edge without meaning to. It also settles any unban debts, tearing down
2379 # taking with it whatever rule a failed unban left behind.
2380 #
2381 # Authorization and targeting are exactly checkpoint's, down to authorizing a
2382 # named kur before the registry is consulted.
2383 #
2384 # Args...
2385 #
2386 # $request :: Required. The decoded request hash ref. args is optional,
2387 # and when present may carry a kur key naming one kur or
2388 # gate. With no args, or no kur key, every real kur rebuilds.
2389 # $ctx :: The JSONUnix context, handed to _authorize. May be undef
2390 # when enable_auth is off.
2391 #
2392 # Returns a hash ref of { kurs => { name => per kur result } }, each result
2393 # being { re_init => 1 } on success or { error => '...' } for a kur that
2394 # could not be reached or whose rebuild failed.
2395 #
2396 # Dies with a plain string when args.kur names no registered kur, or with
2397 # _authorize's { error, code } hash ref on a refusal.
2398 #
2399 # my $result = $self->_cmd_re_init( { 'args' => { 'kur' => 'sshd' } }, $ctx );
2400 # # { kurs => { sshd => { re_init => 1 } } }
2401 0 ▶sub _cmd_re_init {
Subroutine _cmd_re_init: not called CC=4 SCAR=30.0
2402 0 my ( $self, $request, $ctx ) = @_;
2403  
2404 0 my $args = $request->{args};
2405  
2406 0 my @targets;
2407 0 ▶ if ( defined($args) && defined( $args->{kur} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args and defined $args->{'kur'}) { } 0 0 0
Condition0%0/3
defined $args and defined $args->{"kur"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"kur"}
defined $args defined $args->{"kur"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"kur"}
ABresult
0X0
100
111
2408 # as with checkpoint, authorization is against the requested name so
2409 # a fan_out grant covers the fanned command, and it comes before the
2410 # existence check so kur names cannot be enumerated
2411 0 $self->_authorize( $ctx, $args->{kur} );
2412 0 ▶ if ( !defined( $self->{kurs}{ $args->{kur} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$args->{"kur"}}) 0 0 0
2413 0 die( 'No such kur instance, "' . $args->{kur} . '"' );
2414 }
2415 0 @targets = $self->_expand_kur_targets( $args->{kur} );
2416 } else {
2417 0 @targets = $self->_real_kur_names;
2418 0 $self->_authorize( $ctx, @targets );
2419 }
2420  
2421 0 return { 'kurs' => $self->_fan_out( \@targets, 're_init' ) };
2422 } ## end sub _cmd_re_init
2423  
2424 # Handles the clear_retries command... fans it out the same way checkpoint
2425 # does, passing along the optional args.ip or args.cidr naming a single owed
2426 # unban to forget rather than the lot.
2427 #
2428 # What is being forgotten is book keeping only. When a ban's sentence runs
2429 # out but the backend refuses the unban, the kur drops it from its ban book
2430 # and keeps owing the firewall the removal, retrying with a backoff. This
2431 # forgets that debt. Nothing is sent to the firewall, so a rule that really
2432 # is still in place is left with nothing tracking it... which is why the CLI
2433 # help is emphatic about checking first.
2434 #
2435 # The address is validated and canonicalized here as well as kur side, so
2436 # garbage is bounced once rather than by every kur it would have been fanned
2437 # to, and what goes out is the form the retry tablets are actually keyed by.
2438 #
2439 # Authorization and targeting are checkpoint's again.
2440 #
2441 # Args...
2442 #
2443 # $request :: Required. The decoded request hash ref. args is optional
2444 # and may carry any of... kur, naming one kur or gate rather
2445 # than all of them; ip, a single IPv4 or IPv6 address whose
2446 # debt to forget; cidr, the range equivalent. ip and cidr are
2447 # mutually exclusive. With neither, every debt the targeted
2448 # kurs carry is forgotten.
2449 # $ctx :: The JSONUnix context, handed to _authorize. May be undef
2450 # when enable_auth is off.
2451 #
2452 # Returns a hash ref of { kurs => { name => per kur result } }, each result
2453 # being { cleared => N, cleared_ip => N, cleared_cidr => N } counting what
2454 # that kur actually forgot, or { error => '...' } for one that could not be
2455 # reached. Forgetting something that was not owed is not an error... it simply
2456 # counts zero.
2457 #
2458 # Dies with a plain string when both args.ip and args.cidr are given, when
2459 # either will not normalize, or when args.kur names no registered kur.
2460 # Authorization failures die with _authorize's { error, code } hash ref.
2461 #
2462 # my $result = $self->_cmd_clear_retries( {}, $ctx ); # every debt, every kur
2463 #
2464 # my $result = $self->_cmd_clear_retries(
2465 # { 'args' => { 'kur' => 'sshd', 'ip' => '1.2.3.4' } }, $ctx );
2466 # # { kurs => { sshd => { cleared => 1, cleared_ip => 1, cleared_cidr => 0 } } }
2467 0 ▶sub _cmd_clear_retries {
Subroutine _cmd_clear_retries: not called CC=11 SCAR=48.8
2468 0 my ( $self, $request, $ctx ) = @_;
2469  
2470 0 ▶ my $args = defined( $request->{args} ) ? $request->{args} : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $request->{'args'} ? : 0 0 0
2471  
2472 0 ▶ if ( defined( $args->{ip} ) && defined( $args->{cidr} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"ip"} and defined $args->{"cidr"}) 0 0 0
Condition0%0/3
defined $args->{"ip"} and defined $args->{"cidr"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args->{"ip"} and defined $args->{"cidr"}
defined $args->{"ip"} defined $args->{"cidr"}
Truth table0%0/3
A and B
A= defined $args->{"ip"}B= defined $args->{"cidr"}
ABresult
0X0
100
111
2473 0 die('only one of args.ip and args.cidr may be given');
2474 }
2475  
2476 # validated and canonicalized here as well as kur side, so garbage is
2477 # bounced once rather than by each kur it would have been fanned out to,
2478 # and what is fanned out is the form the retry tablets are keyed by
2479 0 my $fan_args = {};
2480 0 ▶ if ( defined( $args->{ip} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"ip"}) 0 0 0
2481 0 my $ip = normalize_ip( $args->{ip} );
2482 0 ▶ if ( !defined($ip) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ip) 0 0 0
2483 0 die( '"' . $args->{ip} . '" does not appear to be an IPv4 or IPv6 IP' );
2484 }
2485 0 $fan_args->{ip} = $ip;
2486 }
2487 0 ▶ if ( defined( $args->{cidr} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"cidr"}) 0 0 0
2488 0 my $cidr = normalize_cidr( $args->{cidr} );
2489 0 ▶ if ( !defined($cidr) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cidr) 0 0 0
2490 0 die( '"' . $args->{cidr} . '" does not appear to be an IPv4 or IPv6 CIDR' );
2491 }
2492 0 $fan_args->{cidr} = $cidr;
2493 }
2494  
2495 0 my @targets;
2496 0 ▶ if ( defined( $args->{kur} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{'kur'}) { } 0 0 0
2497 # as with checkpoint, authorization is against the requested name so
2498 # a fan_out grant covers the fanned command, and it comes before the
2499 # existence check so kur names cannot be enumerated
2500 0 $self->_authorize( $ctx, $args->{kur} );
2501 0 ▶ if ( !defined( $self->{kurs}{ $args->{kur} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"kurs"}{$args->{"kur"}}) 0 0 0
2502 0 die( 'No such kur instance, "' . $args->{kur} . '"' );
2503 }
2504 0 @targets = $self->_expand_kur_targets( $args->{kur} );
2505 } else {
2506 0 @targets = $self->_real_kur_names;
2507 0 $self->_authorize( $ctx, @targets );
2508 }
2509  
2510 0 ▶ return { 'kurs' => $self->_fan_out( \@targets, 'clear_retries', %{$fan_args} ? $fan_args : undef ) };
Branch: 1 branch
BranchTrueFalseTotal
%{$fan_args;} ? : 0 0 0
2511 } ## end sub _cmd_clear_retries
2512  
2513 # Handles the add_kur command... validates the definition in args.opts the
2514 # same way config load would, registers it under args.name, and has the
2515 # manager session spawn it.
2516 #
2517 # The definition is run through the same _check_kur_def and, for a gate,
2518 # _check_fan_out_members the config path uses, with perror off so a bad
2519 # definition is an error response rather than a dead manager. That parity is
2520 # the point... a kur added at runtime is held to exactly the rules one from
2521 # the config is.
2522 #
2523 # The config file is not rewritten, so a kur added this way is gone at the
2524 # next manager start unless it is also added to the config by hand.
2525 #
2526 # The spawn is posted to the manager session rather than done here, as the
2527 # POE::Wheel::Run has to be created in the session that will watch it, and
2528 # the registry entry is seeded with the same shape config load builds so the
2529 # supervision machinery finds what it expects... a fresh restart count, a
2530 # backoff delay of 1, and enabled set.
2531 #
2532 # Note this takes no context and authorizes nothing of its own... the
2533 # dispatch entry has already run _authorize with no kur names, adding a kur
2534 # being a manager level act.
2535 #
2536 # Args...
2537 #
2538 # $request :: Required. The decoded request hash ref. Must carry args
2539 # holding a name key, the new kur's name as a plain string,
2540 # and an opts key holding its definition hash ref, which
2541 # takes the same keys a config kur hash does... backend or
2542 # fan_out, ports, protocols, prefix, self_heal, ban_time,
2543 # checkpoint, enable_cidr, cidr_silent_drop, options,
2544 # authed_users, authed_groups.
2545 #
2546 # Returns a hash ref of { added => name } once it is registered and the spawn
2547 # posted. That is not a promise the process came up... it is a promise the
2548 # manager will try, status being where to look for whether it did.
2549 #
2550 # Dies with a plain string when args.name is missing, when that name is
2551 # already registered, or with whatever _check_kur_def or
2552 # _check_fan_out_members raised about the definition.
2553 #
2554 # my $result = $self->_cmd_add_kur(
2555 # {
2556 # 'args' => {
2557 # 'name' => 'dns',
2558 # 'opts' => { 'backend' => 'pf', 'ports' => ['53'] },
2559 # }
2560 # }
2561 # );
2562 # # { added => 'dns' }
2563 0 ▶sub _cmd_add_kur {
Subroutine _cmd_add_kur: not called CC=5 SCAR=34.0
2564 0 my ( $self, $request ) = @_;
2565  
2566 0 my $args = $request->{args};
2567 0 ▶ if ( !defined($args) || !defined( $args->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args and defined $args->{"name"}) 0 0 0
Condition0%0/3
defined $args and defined $args->{"name"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"name"}
defined $args defined $args->{"name"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"name"}
ABresult
0X0
100
111
2568 0 die('args.name must be the name for the new kur instance');
2569 }
2570 0 my $name = $args->{name};
2571  
2572 0 ▶ if ( defined( $self->{kurs}{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"kurs"}{$name}) 0 0 0
2573 0 die( 'The kur instance "' . $name . '" already exists' );
2574 }
2575  
2576 0 $self->_check_kur_def( $name, $args->{opts}, 0 );
2577 0 ▶ if ( defined( $args->{opts}{fan_out} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"opts"}{"fan_out"}) 0 0 0
2578 0 $self->_check_fan_out_members( $name, $args->{opts}, 0 );
2579 }
2580  
2581 $self->{kurs}{$name} = {
2582 'opts' => $args->{opts},
2583 0 'wheel' => undef,
2584 'pid' => undef,
2585 'restarts' => 0,
2586 'delay' => 1,
2587 'enabled' => 1,
2588 'spawned' => undef,
2589 };
2590  
2591 0 $poe_kernel->post( 'ereshkigal_manager', 'spawn_kur', $name );
2592  
2593 0 log_drek( 'info', 'added kur "' . $name . '"' );
2594  
2595 0 return { 'added' => $name };
2596 } ## end sub _cmd_add_kur
2597  
2598 # Handles the remove_kur command... refuses while args.name is still a
2599 # fan_out member, otherwise disables it and has the manager session stop and
2600 # drop it.
2601 #
2602 # The gate check is why this is not simply a post. Config load refuses a
2603 # fan_out naming an unknown kur, so removal cannot be allowed to create that
2604 # same dangling state at runtime... every registered kur is scanned for gates
2605 # naming this one, and if any do the removal is refused naming them. Remove
2606 # the gate first, or the member stays.
2607 #
2608 # Setting enabled to 0 before posting matters as well... it is what stops the
2609 # reap handler restarting the kur when the stop it is about to be sent
2610 # actually kills it.
2611 #
2612 # The real work is left to the manager session, as a POE::Wheel::Run must be
2613 # destroyed in the session watching it or its watchers outlive it and keep
2614 # the session alive forever.
2615 #
2616 # The config file is not rewritten, so a kur defined there returns at the
2617 # next manager start.
2618 #
2619 # Note this takes no context and authorizes nothing of its own... the
2620 # dispatch entry has already run _authorize with no kur names.
2621 #
2622 # Args...
2623 #
2624 # $request :: Required. The decoded request hash ref. Must carry args
2625 # holding a name key naming the kur to remove, as a plain
2626 # string.
2627 #
2628 # Returns a hash ref of { removed => name } once it is disabled and the
2629 # removal posted. As with add_kur that is a promise the manager will do it,
2630 # not that the process is already gone.
2631 #
2632 # Dies with a plain string when args.name is missing, names no registered
2633 # kur, or is still a member of one or more gates, which names them.
2634 #
2635 # my $result = $self->_cmd_remove_kur( { 'args' => { 'name' => 'dns' } } );
2636 # # { removed => 'dns' }
2637 0 ▶sub _cmd_remove_kur {
Subroutine _cmd_remove_kur: not called CC=8 SCAR=42.8
2638 0 my ( $self, $request ) = @_;
2639  
2640 0 my $args = $request->{args};
2641 0 ▶ if ( !defined($args) || !defined( $args->{name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args and defined $args->{"name"}) 0 0 0
Condition0%0/3
defined $args and defined $args->{"name"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args and defined $args->{"name"}
defined $args defined $args->{"name"}
Truth table0%0/3
A and B
A= defined $argsB= defined $args->{"name"}
ABresult
0X0
100
111
2642 0 die('args.name must be the name of a kur instance');
2643 }
2644 0 my $name = $args->{name};
2645  
2646 0 my $entry = $self->{kurs}{$name};
2647 0 ▶ if ( !defined($entry) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $entry) 0 0 0
2648 0 die( 'No such kur instance, "' . $name . '"' );
2649 }
2650  
2651 # config load refuses a fan_out naming an unknown kur, so removal cannot
2652 # be allowed to create that same dangling state at runtime... remove the
2653 # gate first, or the member stays
2654 0 my @gates_using;
2655 0 foreach my $other_name ( sort( keys( %{ $self->{kurs} } ) ) ) {
2656 0 my $fan_out = $self->{kurs}{$other_name}{opts}{fan_out};
2657 0 ▶ if ( defined($fan_out) && grep { $_ eq $name } @{$fan_out} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fan_out and grep {$_ eq $name;} @{$fan_out;}) 0 0 0
Condition0%0/3
defined $fan_out and grep {$_ eq $name;} @{$fan_out;}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $fan_out and grep {$_ eq $name;} @{$fan_out;}
defined $fan_out grep {$_ eq $name;} @{$fan_out;}
Truth table0%0/3
A and B
A= defined $fan_outB= grep {$_ eq $name;} @{$fan_out;}
ABresult
0X0
100
111
2658 0 push( @gates_using, $other_name );
2659 }
2660 }
2661 0 ▶ if (@gates_using) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gates_using) 0 0 0
2662 0 die( 'The kur "'
2663 . $name
2664 . '" is a fan_out member of "'
2665 . join( '", "', @gates_using )
2666 . '"... remove the fan_out kur first' );
2667 }
2668  
2669 0 $entry->{enabled} = 0;
2670  
2671 # the actual stop and removal happens in the manager session given the
2672 # wheel has to be destroyed there
2673 0 $poe_kernel->post( 'ereshkigal_manager', 'remove_kur', $name );
2674  
2675 0 return { 'removed' => $name };
2676 } ## end sub _cmd_remove_kur
2677  
2678 =head1 ERROR CODES / ERROR FLAGS
2679  
2680 Error handling is provided by L<Error::Helper>. All errors
2681 are considered fatal.
2682  
2683 =head2 1, configReadFailed
2684  
2685 Failed to read the config file.
2686  
2687 =head2 2, configParseFailed
2688  
2689 Failed to parse the config file as TOML.
2690  
2691 =head2 3, invalidKurDef
2692  
2693 A kur def in the config is invalid... bad name, not a hash, lacking a
2694 backend or a fan_out, having both, an invalid fan_out (not an array of
2695 kur names, an unknown member, or a nested fan_out kur), or an options table
2696 carrying a non-scalar value for anything other than C<interfaces>.
2697  
2698 =head2 4, runBaseDirError
2699  
2700 The run base dir or the kur dir under it could not be created or is not
2701 read/writable.
2702  
2703 =head2 5, badSocketGroup
2704  
2705 Failed to resolve the socket group to a GID.
2706  
2707 =head2 6, invalidBanTime
2708  
2709 ban_time is not a non-negative int of seconds.
2710  
2711 =head2 7, invalidCheckpoint
2712  
2713 checkpoint is not a non-negative int of seconds.
2714  
2715 =head2 8, invalidAuthedList
2716  
2717 authed_users or authed_groups is not an array of strings.
2718  
2719 =head1 AUTHOR
2720  
2721 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
2722  
2723 =head1 BUGS
2724  
2725 Please report any bugs or feature requests via GitHub at
2726 L<https://github.com/LilithSec/Ereshkigal/issues>, or to
2727 C<bug-ereshkigal at rt.cpan.org>.
2728  
2729 =head1 SUPPORT
2730  
2731 You can find documentation for this module with the perldoc command.
2732  
2733 perldoc Ereshkigal
2734  
2735 You can also look for information at:
2736  
2737 =over 4
2738  
2739 =item * GitHub (source and issues)
2740  
2741 L<https://github.com/LilithSec/Ereshkigal>
2742  
2743 =item * RT: CPAN's request tracker
2744  
2745 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Ereshkigal>
2746  
2747 =item * CPAN Ratings
2748  
2749 L<https://cpanratings.perl.org/d/Ereshkigal>
2750  
2751 =item * Search CPAN
2752  
2753 L<https://metacpan.org/release/Ereshkigal>
2754  
2755 =back
2756  
2757 =head1 LICENSE AND COPYRIGHT
2758  
2759 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
2760  
2761 This is free software, licensed under:
2762  
2763 The Artistic License 2.0 (GPL Compatible)
2764  
2765  
2766 =cut
2767  
2768 3 1; # End of Ereshkigal
↑ Summary blib/lib/Ereshkigal/Kur.pm »