BlockerHelper/backends/akamai.pm

filter: Statementstmt 32.0% 128 / 399 Branchbran 33.3% 50 / 150 Conditioncond 40.0% 18 / 45 MC/DCmcdc 18.5% 5 / 27 Subroutinesub 69.2% 18 / 26 Podpod 100% 13 / 13 totaltotal 35.1% 232 / 660 CC 94 SCAR 37.3
CC
94
Cov
33%
new
73.2
_request
72.0
unban
45.7
CRAP 41.6
« BlockerHelper/backends/shorewall.pm ↑ Summary BlockerHelper/backends/panos.pm »
1 package Net::Firewall::BlockerHelper::backends::akamai;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use base qw( Error::Helper Net::Firewall::BlockerHelper::Util );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Regexp::IPv4 qw($IPv4_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Regexp::IPv6 qw($IPv6_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Net::Firewall::BlockerHelper::backends::akamai - Akamai Network Lists backend for Net::Firewall::BlockerHelper.
13  
14 =head1 VERSION
15  
16 Version 0.2.0
17  
18 =cut
19  
20 1 our $VERSION = '0.2.0';
21  
22 =head1 SYNOPSIS
23  
24 use Net::Firewall::BlockerHelper;
25  
26 my $fw_helper = Net::Firewall::BlockerHelper->new(
27 backend => 'akamai',
28 name => 'ssh',
29 options => {
30 host => 'akab-xxxx.luna.akamaiapis.net',
31 client_token => $client_token,
32 client_secret => $client_secret,
33 access_token => $access_token,
34 network_list_id => $network_list_id,
35 },
36 );
37  
38 $fw_helper->init_backend;
39 $fw_helper->ban( ban => '1.2.3.4' );
40 $fw_helper->unban( ban => '1.2.3.4' );
41  
42 =head1 DESCRIPTION
43  
44 Blocks IPs remotely via the Akamai Network Lists API v2, adding and removing
45 elements of an existing network list. Requests are authenticated using
46 Akamai's EdgeGrid (C<EG1-HMAC-SHA256>) request signing scheme.
47  
48 The network list identified by the C<network_list_id> option must already
49 exist. This backend only manages the membership of that list.
50  
51 Blocking is per IP or CIDR range; ports and protocols are not supported and
52 specifying them is an error.
53  
54 B<Note:> Changes to a network list made via the API do not take effect until
55 the list is activated (staging and/or production). Activation is out of scope
56 for this backend and must be performed separately, either via the Akamai
57 control center or the activation endpoints of the Network Lists API.
58 Similarly, membership in the list does not block anything on its own; the
59 list must actually be used by a security policy, eg as the block list of a
60 IP/Geo firewall rule. Wiring the list into a policy is likewise out of scope
61 for this backend.
62  
63 L<LWP::UserAgent> is only loaded at run time, so it is only required if this
64 backend is actually used. For https, L<LWP::Protocol::https> must be present
65 as well.
66  
67 =head1 METHODS
68  
69 =head2 new
70  
71 Initiates the object.
72  
73 - options :: Backend specific options. See below.
74 - Default :: {}
75  
76 - prefix :: Prefix to use. Must match the regex /^[a-zA-Z0-9]+$/
77 - default :: kur
78  
79 - name :: Name of this specific instance. This must be specified.
80 - default :: undef
81  
82 Ports and protocols are not supported by this backend and specifying either
83 is an error.
84  
85 The options hash accepts the following. The host, client_token,
86 client_secret, access_token, and network_list_id options are all required.
87  
88 - host :: Akamai API hostname, eg akab-xxxx.luna.akamaiapis.net .
89 - Default :: undef
90  
91 - client_token :: EdgeGrid client token.
92 - Default :: undef
93  
94 - client_secret :: EdgeGrid client secret.
95 - Default :: undef
96  
97 - access_token :: EdgeGrid access token.
98 - Default :: undef
99  
100 - network_list_id :: ID of the network list to manage.
101 - Default :: undef
102  
103 - timeout :: HTTP timeout in seconds.
104 - Default :: 30
105  
106 - insecure :: If true, skip TLS certificate verification.
107 - Default :: 0
108  
109 All errors are considered fatal, meaning if new fails it will die.
110  
111 =cut
112  
113 6 ▶sub new {
Subroutine new: called CC=28 SCAR=42.9
Pod documented
114 6 my ( $blank, %opts ) = @_;
115  
116 6 my $self = {
117 perror => undef,
118 error => undef,
119 errorLine => undef,
120 errorFilename => undef,
121 errorString => "",
122 errorExtra => {
123 all_errors_fatal => 1,
124 # all_fatal is what Error::Helper 2.1.0 actually checks; all_errors_fatal
125 # is kept for the name documented in its POD
126 all_fatal => 1,
127 flags => {
128 1 => 'notInited',
129 6 => 'invalidPrefixSpecified',
130 7 => 'invalidName',
131 8 => 'optionsNotHash',
132 9 => 'noBanItem',
133 10 => 'banItemNotIP',
134 12 => 'backendInitError',
135 13 => 'banFailed',
136 14 => 'unbanFailed',
137 15 => 'listFailed',
138 16 => 'reInitFailed',
139 17 => 'teardownFailed',
140 18 => 'alreadyInited',
141 23 => 'initFailed',
142 24 => 'checkFailed',
143 25 => 'flushFailed',
144 26 => 'portsNotSupported',
145 27 => 'protocolsNotSupported',
146 30 => 'hostNotDefined',
147 31 => 'clientTokenNotDefined',
148 32 => 'clientSecretNotDefined',
149 33 => 'accessTokenNotDefined',
150 34 => 'networkListIdNotDefined',
151 35 => 'banCidrFailed',
152 36 => 'unbanCidrFailed',
153 37 => 'cidrItemNotCidr',
154 38 => 'cidrNotSupported',
155 39 => 'listCidrFailed',
156 },
157 fatal_flags => {},
158 perror_not_fatal => 0,
159 },
160 options => {},
161 ports => [],
162 protocols => [],
163 testing => undef,
164 test_data => undef,
165 prefix => 'kur',
166 name => undef,
167 frontend_obj => undef,
168 inited => 0,
169 banned => {},
170 banned_cidr => {},
171 cidr_supported => 1,
172 ua => undef,
173 };
174 6 bless $self;
175  
176 # blocking is per IP; the network list has no concept of ports or protocols
177 6 ▶ if ( defined( $opts{ports} ) && ref( $opts{ports} ) eq 'ARRAY' && defined( $opts{ports}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]) 0 6 6
Condition33%2/6
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
!ll&&!rl&&r
060
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY"
!ll&&!rl&&r
006
MC/DC0%0/3
defined $opts{"ports"} and ref $opts{"ports"} eq "ARRAY" and defined $opts{"ports"}[0]
defined $opts{"ports"} ref $opts{"ports"} eq "ARRAY" defined $opts{"ports"}[0]
Truth table25%1/4
A and B and C
A= defined $opts{"ports"}B= ref $opts{"ports"} eq "ARRAY"C= defined $opts{"ports"}[0]
ABCresult
0XX0
10X0
1100
1111
178 0 $self->{perror} = 1;
179 0 $self->{error} = 26;
180 0 $self->{errorString} = 'the akamai backend blocks whole IPs and does not support ports';
181 0 $self->warn;
182 }
183 6 ▶ if ( defined( $opts{protocols} ) && ref( $opts{protocols} ) eq 'ARRAY' && defined( $opts{protocols}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]) 0 6 6
Condition33%2/6
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
!ll&&!rl&&r
060
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY"
!ll&&!rl&&r
006
MC/DC0%0/3
defined $opts{"protocols"} and ref $opts{"protocols"} eq "ARRAY" and defined $opts{"protocols"}[0]
defined $opts{"protocols"} ref $opts{"protocols"} eq "ARRAY" defined $opts{"protocols"}[0]
Truth table25%1/4
A and B and C
A= defined $opts{"protocols"}B= ref $opts{"protocols"} eq "ARRAY"C= defined $opts{"protocols"}[0]
ABCresult
0XX0
10X0
1100
1111
184 0 $self->{perror} = 1;
185 0 $self->{error} = 27;
186 0 $self->{errorString} = 'the akamai backend blocks whole IPs and does not support protocols';
187 0 $self->warn;
188 }
189  
190 # make sure prefix is sane if defined
191 6 ▶ if ( defined( $opts{prefix} ) && $opts{prefix} !~ /^[a-zA-Z0-9]+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opts{'prefix'} and not $opts{'prefix'} =~ /^[a-zA-Z0-9]+$/) { } 0 6 6
elsif (defined $opts{'prefix'}) { } 6 0 6
Condition33%1/3
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
!ll&&!rl&&r
060
MC/DC0%0/2
defined $opts{"prefix"} and not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
defined $opts{"prefix"} not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
Truth table33%1/3
A and not(B)
A= defined $opts{"prefix"}B= not $opts{"prefix"} =~ /^[a-zA-Z0-9]+$/
ABresult
0X0
100
111
192 0 $self->{perror} = 1;
193 0 $self->{error} = 6;
194 $self->{errorString}
195 0 = '"' . $opts{prefix} . '" is not a valid prefix as it does not match the regex /^[a-zA-Z0-9]+$/';
196 0 $self->warn;
197 } elsif ( defined( $opts{prefix} ) ) {
198 6 $self->{prefix} = $opts{prefix};
199 }
200  
201 # make sure we have a name and that it is valid
202 6 ▶ if ( !defined( $opts{name} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opts{'name'}) { } 0 6 6
elsif (not $opts{'name'} =~ /^[a-zA-Z0-9\-]+$/) { } 0 6 6
203 0 $self->{perror} = 1;
204 0 $self->{error} = 7;
205 0 $self->{errorString} = 'name is undef';
206 0 $self->warn;
207 } elsif ( $opts{name} !~ /^[a-zA-Z0-9\-]+$/ ) {
208 0 $self->{perror} = 1;
209 0 $self->{error} = 7;
210 0 $self->{errorString} = 'name set to "' . $opts{name} . '" which does not match the regexp /^[a-zA-Z0-9\-]+$/';
211 0 $self->warn;
212 }
213 6 $self->{name} = $opts{name};
214  
215 # used internally for testing
216 6 ▶ if ( defined( $opts{testing} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"testing"}) 6 0 6
217 6 $self->{testing} = $opts{testing};
218 }
219 6 ▶ if ( defined( $opts{frontend_obj} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"frontend_obj"}) 6 0 6
220 6 $self->{frontend_obj} = $opts{frontend_obj};
221 }
222  
223 6 ▶ if ( defined( $opts{options} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"options"}) 6 0 6
224 6 ▶ if ( ref( $opts{options} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"options"} ne "HASH") 0 6 6
225 0 $self->{perror} = 1;
226 0 $self->{error} = 8;
227 0 $self->{errorString} = 'ref for options is "' . ref( $opts{options} ) . '" and not HASH';
228 0 $self->warn;
229 }
230 6 $self->{options} = $opts{options};
231 }
232  
233 # required options
234 6 ▶ if ( !defined( $self->{options}{host} ) || $self->{options}{host} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"host"} or $self->{"options"}{"host"} eq "") 1 5 6
Condition66%2/3
not defined $self->{"options"}{"host"} or $self->{"options"}{"host"} eq ""
l!l&&r!l&&!r
105
MC/DC50%1/2
not defined $self->{"options"}{"host"} or $self->{"options"}{"host"} eq ""
not defined $self->{"options"}{"host"} $self->{"options"}{"host"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"host"}B= $self->{"options"}{"host"} eq ""
ABresult
1X1
011
000
235 1 $self->{perror} = 1;
236 1 $self->{error} = 30;
237 1 $self->{errorString} = 'the option host is undef or blank';
238 1 $self->warn;
239 }
240 5 ▶ if ( !defined( $self->{options}{client_token} ) || $self->{options}{client_token} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"client_token"} or $self->{"options"}{"client_token"} eq "") 1 4 5
Condition66%2/3
not defined $self->{"options"}{"client_token"} or $self->{"options"}{"client_token"} eq ""
l!l&&r!l&&!r
104
MC/DC50%1/2
not defined $self->{"options"}{"client_token"} or $self->{"options"}{"client_token"} eq ""
not defined $self->{"options"}{"client_token"} $self->{"options"}{"client_token"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"client_token"}B= $self->{"options"}{"client_token"} eq ""
ABresult
1X1
011
000
241 1 $self->{perror} = 1;
242 1 $self->{error} = 31;
243 1 $self->{errorString} = 'the option client_token is undef or blank';
244 1 $self->warn;
245 }
246 4 ▶ if ( !defined( $self->{options}{client_secret} ) || $self->{options}{client_secret} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"client_secret"} or $self->{"options"}{"client_secret"} eq "") 1 3 4
Condition66%2/3
not defined $self->{"options"}{"client_secret"} or $self->{"options"}{"client_secret"} eq ""
l!l&&r!l&&!r
103
MC/DC50%1/2
not defined $self->{"options"}{"client_secret"} or $self->{"options"}{"client_secret"} eq ""
not defined $self->{"options"}{"client_secret"} $self->{"options"}{"client_secret"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"client_secret"}B= $self->{"options"}{"client_secret"} eq ""
ABresult
1X1
011
000
247 1 $self->{perror} = 1;
248 1 $self->{error} = 32;
249 1 $self->{errorString} = 'the option client_secret is undef or blank';
250 1 $self->warn;
251 }
252 3 ▶ if ( !defined( $self->{options}{access_token} ) || $self->{options}{access_token} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"access_token"} or $self->{"options"}{"access_token"} eq "") 1 2 3
Condition66%2/3
not defined $self->{"options"}{"access_token"} or $self->{"options"}{"access_token"} eq ""
l!l&&r!l&&!r
102
MC/DC50%1/2
not defined $self->{"options"}{"access_token"} or $self->{"options"}{"access_token"} eq ""
not defined $self->{"options"}{"access_token"} $self->{"options"}{"access_token"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"access_token"}B= $self->{"options"}{"access_token"} eq ""
ABresult
1X1
011
000
253 1 $self->{perror} = 1;
254 1 $self->{error} = 33;
255 1 $self->{errorString} = 'the option access_token is undef or blank';
256 1 $self->warn;
257 }
258 2 ▶ if ( !defined( $self->{options}{network_list_id} ) || $self->{options}{network_list_id} eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $self->{"options"}{"network_list_id"} or $self->{"options"}{"network_list_id"} eq "") 1 1 2
Condition66%2/3
not defined $self->{"options"}{"network_list_id"} or $self->{"options"}{"network_list_id"} eq ""
l!l&&r!l&&!r
101
MC/DC50%1/2
not defined $self->{"options"}{"network_list_id"} or $self->{"options"}{"network_list_id"} eq ""
not defined $self->{"options"}{"network_list_id"} $self->{"options"}{"network_list_id"} eq ""
Truth table66%2/3
not(A) or B
A= not defined $self->{"options"}{"network_list_id"}B= $self->{"options"}{"network_list_id"} eq ""
ABresult
1X1
011
000
259 1 $self->{perror} = 1;
260 1 $self->{error} = 34;
261 1 $self->{errorString} = 'the option network_list_id is undef or blank';
262 1 $self->warn;
263 }
264  
265 # defaults
266 1 ▶ $self->{options}{timeout} = 30 if ( !defined( $self->{options}{timeout} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"timeout"} 1 0 1
267 1 ▶ $self->{options}{insecure} = 0 if ( !defined( $self->{options}{insecure} ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"options"}{"insecure"} 1 0 1
268  
269 1 return $self;
270 } ## end sub new
271  
272 # Internal helper. Returns the scheme and host of the Akamai API endpoint,
273 # which every URL is built on.
274 #
275 # The host is the per account API hostname from an EdgeGrid credential set,
276 # something of the akab-....luna.akamaiapis.net form, not a shared endpoint.
277 # The scheme is fixed at https, which EdgeGrid requires and which the request
278 # signing also assumes.
279 #
280 # Takes no arguments; the host comes from the options.
281 #
282 # Returns the base URL as a string, with no trailing slash.
283 #
284 # $self->_base_url; # https://akab-xxx.luna.akamaiapis.net
285 11 ▶sub _base_url {
Subroutine _base_url: called CC=1 SCAR=0.0
286 11 my ($self) = @_;
287  
288 11 return 'https://' . $self->{options}{host};
289 }
290  
291 # Internal helper. Returns the URL of the network list this instance manages.
292 #
293 # This is the object every ban and unban acts on. It is addressed by the
294 # network list id, which is Akamai's own identifier rather than a name the
295 # caller chose, and the list is expected to already exist and be referenced by
296 # a security configuration; this backend does not create it.
297 #
298 # As well as being used directly for reading the list, this is the stem the
299 # append and element URLs are built on.
300 #
301 # Takes no arguments; the network list id comes from the options.
302 #
303 # Returns the URL as a string, with no trailing slash.
304 #
305 # $self->_list_url;
306 # # https://akab-xxx.luna.akamaiapis.net/network-list/v2/network-lists/12345_BLOCKLIST
307 11 ▶sub _list_url {
Subroutine _list_url: called CC=1 SCAR=0.0
308 11 my ($self) = @_;
309  
310 11 return $self->_base_url . '/network-list/v2/network-lists/' . $self->{options}{network_list_id};
311 }
312  
313 # Internal helper. Returns the URL that adds elements to the network list.
314 #
315 # Akamai's network list API is incremental rather than replace-in-full, which
316 # is what makes this backend cheaper than the ones that rewrite an entire
317 # object per ban: appending adds to whatever is already there without needing
318 # to know the current contents.
319 #
320 # Takes no arguments.
321 #
322 # Returns the URL as a string, for a POST whose body carries the elements to
323 # add.
324 #
325 # $self->_append_url;
326 # # https://akab-xxx.luna.akamaiapis.net/network-list/v2/network-lists/12345_BLOCKLIST/append
327 3 ▶sub _append_url {
Subroutine _append_url: called CC=1 SCAR=0.0
328 3 my ($self) = @_;
329  
330 3 return $self->_list_url . '/append';
331 }
332  
333 # Internal helper. Returns the URL that removes one element from the network
334 # list.
335 #
336 # The counterpart of _append_url, and incremental in the same way: the element
337 # to drop is named in the query string, so nothing needs to be read back or
338 # rewritten. Unlike the routeros_api backend there is no id to look up first,
339 # since Akamai addresses elements by their value.
340 #
341 # The element is percent encoded, which matters for IPv6, whose colons would
342 # otherwise sit raw in the query string, and for ranges, whose slash would.
343 #
344 # Args:
345 #
346 # ip - The element to remove, as a plain string. Expected to be an already
347 # validated and lowercased IPv4 or IPv6 address, or a CIDR range;
348 # Akamai network lists hold both and this treats them the same.
349 #
350 # Returns the URL as a string, for a DELETE that carries no body.
351 #
352 # $self->_element_url('10.0.0.1');
353 # # https://akab-xxx.luna.akamaiapis.net/network-list/v2/network-lists/12345_BLOCKLIST/elements?element=10.0.0.1
354 #
355 # $self->_element_url('2001:db8::1');
356 # # .../elements?element=2001%3Adb8%3A%3A1
357 2 ▶sub _element_url {
Subroutine _element_url: called CC=1 SCAR=0.0
358 2 my ( $self, $ip ) = @_;
359  
360 2 return $self->_list_url . '/elements?element=' . $self->_uri_escape($ip);
361 }
362  
363 # Internal helper. Builds the EdgeGrid Authorization header for one request.
364 # This is the most intricate piece of this backend and the reason it cannot
365 # just use HTTP basic auth like the other API backends.
366 #
367 # Akamai signs each request rather than sending a standing credential. The
368 # scheme is EG1-HMAC-SHA256 and works in two stages: a signing key is derived
369 # by HMACing the timestamp with the client secret, and the request itself is
370 # then HMACed with that derived key. Signing the timestamp rather than the
371 # request with the long lived secret is what limits how long any one derived
372 # key is useful for.
373 #
374 # The data to sign is a tab separated canonical form of the request: method,
375 # scheme, host, path with query, an always empty canonicalized headers field
376 # since none are signed here, the content hash, and the partial Authorization
377 # header itself. Getting any field or separator wrong produces a signature the
378 # API rejects with no useful diagnosis, so the ordering here is not
379 # rearrangeable.
380 #
381 # Two details are easy to get wrong and worth knowing about. Digest::SHA
382 # returns base64 without the trailing '=' padding, which EdgeGrid requires, so
383 # every digest is passed through a local padding closure. And the content hash
384 # is only included for POST requests with a non empty body; sending it for a
385 # GET or DELETE would change the signed string and fail.
386 #
387 # The timestamp is UTC in EdgeGrid's own format, and the nonce is four
388 # concatenated random 32 bit values, which is enough to keep replay detection
389 # from tripping on repeated requests.
390 #
391 # Never called in testing mode, since nothing is signed when nothing is sent.
392 #
393 # Args:
394 #
395 # method - The HTTP method the request will use, as a plain string. Upper
396 # cased before signing, and compared against POST to decide
397 # whether a content hash is included.
398 #
399 # url - The full URL the request will go to, as a plain string. The
400 # scheme and host are stripped off to leave the path and query,
401 # which is what gets signed; an empty remainder becomes '/'.
402 #
403 # body - The request body, as a plain string, or undef for requests that
404 # carry none. Only used for POST, where its SHA-256 becomes the
405 # content hash.
406 #
407 # Returns the complete Authorization header value as a string, of the form
408 # 'EG1-HMAC-SHA256 client_token=..;access_token=..;timestamp=..;nonce=..;signature=..'.
409 # Note the value is single use: it embeds a timestamp and nonce, so it must be
410 # rebuilt for every request rather than cached.
411 #
412 # my $auth = $self->_edgegrid_auth( 'GET', $self->_list_url );
413 #
414 # my $auth = $self->_edgegrid_auth( 'POST', $self->_append_url, $body );
415 0 ▶sub _edgegrid_auth {
Subroutine _edgegrid_auth: not called CC=5 SCAR=34.0
416 0 my ( $self, $method, $url, $body ) = @_;
417  
418 0 require Digest::SHA;
419 0 require MIME::Base64;
420 0 require POSIX;
421  
422 # EdgeGrid uses a UTC timestamp of the form yyyyMMddTHH:mm:ss+0000
423 0 my $timestamp = POSIX::strftime( '%Y%m%dT%H:%M:%S+0000', gmtime() );
424  
425 # simple random hex nonce
426 0 my $nonce = sprintf( '%08x%08x%08x%08x',
427 int( rand(0xffffffff) ), int( rand(0xffffffff) ),
428 int( rand(0xffffffff) ), int( rand(0xffffffff) ) );
429  
430 # split the URL into host and path+query
431 0 my $host = $self->{options}{host};
432 0 my $path_and_query = $url;
433 0 $path_and_query =~ s{^https?://[^/]+}{};
434 0 ▶ if ( $path_and_query eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path_and_query eq "") 0 0 0
435 0 $path_and_query = '/';
436 }
437  
438 # base64 helper that pads to a multiple of 4 with '=' as Digest::SHA omits
439 # the padding
440 0 ▶ my $pad = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
441 0 my ($string) = @_;
442 0 ▶ while ( length($string) % 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($string) % 4) 0 0 0
443 0 $string .= '=';
444 }
445 0 return $string;
446 0 };
447  
448 my $auth_header_without_sig
449 = 'EG1-HMAC-SHA256 '
450 . 'client_token='
451 . $self->{options}{client_token} . ';'
452 . 'access_token='
453 0 . $self->{options}{access_token} . ';'
454 . 'timestamp='
455 . $timestamp . ';'
456 . 'nonce='
457 . $nonce . ';';
458  
459 0 my $signing_key = $pad->( Digest::SHA::hmac_sha256_base64( $timestamp, $self->{options}{client_secret} ) );
460  
461 # content hash is only present for POST requests
462 0 my $content_hash = '';
463 0 ▶ if ( uc($method) eq 'POST' && defined($body) && $body ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (uc $method eq "POST" and defined $body and $body ne "") 0 0 0
Condition0%0/6
uc $method eq "POST" and defined $body and $body ne ""
!ll&&!rl&&r
000
uc $method eq "POST" and defined $body
!ll&&!rl&&r
000
MC/DC0%0/3
uc $method eq "POST" and defined $body and $body ne ""
uc $method eq "POST" defined $body $body ne ""
Truth table0%0/4
A and B and C
A= uc $method eq "POST"B= defined $bodyC= $body ne ""
ABCresult
0XX0
10X0
1100
1111
464 0 $content_hash = $pad->( Digest::SHA::sha256_base64($body) );
465 }
466  
467 0 my $data_to_sign = join( "\t",
468 uc($method),
469 'https',
470 $host,
471 $path_and_query,
472 '', # canonicalized headers, none used here
473 $content_hash,
474 $auth_header_without_sig,
475 );
476  
477 0 my $signature = $pad->( Digest::SHA::hmac_sha256_base64( $data_to_sign, $signing_key ) );
478  
479 0 return $auth_header_without_sig . 'signature=' . $signature;
480 } ## end sub _edgegrid_auth
481  
482 # Internal helper. Performs one HTTP request against the Akamai network list
483 # API. Every call this backend makes goes through here.
484 #
485 # The user agent is built on first use and cached on the object, so a run of
486 # requests shares one agent. LWP::UserAgent is loaded with require at that
487 # point rather than at compile time, since only the HTTP backends need it;
488 # failing to load it dies with an explanation naming this backend.
489 #
490 # Authentication is an EdgeGrid signature built per request by
491 # _edgegrid_auth. Unlike the backends using basic auth or a session token,
492 # nothing here can be cached: the header embeds a timestamp and nonce and
493 # covers the method, URL, and body, so it has to be recomputed even for a
494 # repeat of the same call.
495 #
496 # Any HTTP level failure dies rather than setting an error. The callers wrap
497 # this in eval and turn the exception into the appropriate error code, which
498 # is what lets one helper serve paths that report ban, unban, and teardown
499 # failures differently.
500 #
501 # A body that fails to decode as JSON is not fatal; the decode runs inside its
502 # own eval and leaves the result undef.
503 #
504 # Never called in testing mode; those paths record the request instead.
505 #
506 # Args:
507 #
508 # method - The HTTP method, as a plain string: 'GET' to read the list,
509 # 'POST' to append elements, 'DELETE' to remove one.
510 #
511 # url - The full URL to request, as a plain string, from _list_url,
512 # _append_url, or _element_url.
513 #
514 # body - Optional request body, as an already encoded JSON string. undef
515 # for the reads and deletes, which carry everything in the URL.
516 # Note this is also what gets hashed into the signature for a
517 # POST, so it must be the exact bytes sent.
518 #
519 # Returns the decoded response body as whatever structure the JSON held,
520 # normally a hashref, or undef when the response body was empty or did not
521 # parse. Dies on any non success HTTP status.
522 #
523 # my $decoded = $self->_request( 'GET', $self->_list_url );
524 #
525 # # the usual shape at the call sites
526 # eval { $self->_request( 'POST', $self->_append_url, $body ); };
527 # if ($@) { ... raise banFailed ... }
528 0 ▶sub _request {
Subroutine _request: not called CC=8 SCAR=42.8
529 0 my ( $self, $method, $url, $body ) = @_;
530  
531 0 ▶ if ( !defined( $self->{ua} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"ua"}) 0 0 0
532 0 local $@;
533 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require LWP::UserAgent; my(%args) = ("agent", 'Net::Firewall::BlockerHelper/' . $Net::Firewall::BlockerHelper::backends::akamai::VERSION, "timeout", $self->{"options"}{"timeout"}); if ($self->{"options"}{"insecure"}) { $args{"ssl_opts"} = {"verify_hostname", 0, "SSL_verify_mode", 0}; } ; $self->{"ua"} = "LWP::UserAgent"->new(%args); 1 } } or die 'failed to load LWP::UserAgent, which the akamai backend requires... ' . $@ 0 0 0
534 0 require LWP::UserAgent;
535 my %args = (
536 agent => 'Net::Firewall::BlockerHelper/' . $VERSION,
537 timeout => $self->{options}{timeout},
538 0 );
539 0 ▶ if ( $self->{options}{insecure} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"insecure"}) 0 0 0
540 0 $args{ssl_opts} = { verify_hostname => 0, SSL_verify_mode => 0 };
541 }
542 0 $self->{ua} = LWP::UserAgent->new(%args);
543 0 1;
544 } or die( 'failed to load LWP::UserAgent, which the akamai backend requires... ' . $@ );
545 }
546  
547 0 my $auth = $self->_edgegrid_auth( $method, $url, $body );
548  
549 0 my @headers = ( 'Content-Type' => 'application/json', 'Authorization' => $auth );
550  
551 0 require HTTP::Request;
552 0 my $request = HTTP::Request->new( $method, $url, \@headers, $body );
553  
554 0 my $response = $self->{ua}->request($request);
555  
556 0 ▶ if ( !$response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
557 0 my $detail = $response->decoded_content;
558 0 ▶ $detail = defined($detail) ? ( ' body... ' . $detail ) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $detail ? : 0 0 0
559 0 die( $method . ' ' . $url . ' failed... HTTP status... ' . $response->status_line . $detail );
560 }
561  
562 0 my $decoded;
563 0 my $content = $response->decoded_content;
564 0 ▶ if ( defined($content) && $content ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $content and $content ne "") 0 0 0
Condition0%0/3
defined $content and $content ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $content and $content ne ""
defined $content $content ne ""
Truth table0%0/3
A and B
A= defined $contentB= $content ne ""
ABresult
0X0
100
111
565 0 local $@;
566 0 eval { $decoded = $self->_json->decode($content); };
567 }
568  
569 0 return $decoded;
570 } ## end sub _request
571  
572 =head2 init
573  
574 Initiates the backend. Verifies the credentials and endpoint by GETing the
575 network list at C</network-list/v2/network-lists/$network_list_id>. Nothing
576 is created remotely; the list must already exist.
577  
578 Note that for bans to have an effect the list must also be activated and in
579 use by a security policy. See L</DESCRIPTION>.
580  
581 $backend->init;
582  
583 =cut
584  
585 1 ▶sub init {
Subroutine init: called CC=4 SCAR=20.3
Pod documented
586 1 my ( $self, %opts ) = @_;
587  
588 1 $self->errorblank;
589  
590 1 ▶ if ( $self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"inited"}) 0 1 1
591 0 $self->{error} = 18;
592 0 $self->{errorString} = 'backend has already been inited';
593 0 $self->warn;
594 }
595  
596 1 my $url = $self->_list_url;
597  
598 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
599 1 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $url } ];
600 } else {
601 0 local $@;
602 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or do { $self->{"error"} = 23; $self->{"errorString"} = 'init failed. probing the network list endpoint failed... ' . $@; $self->warn } 0 0 0
603 0 $self->{error} = 23;
604 0 $self->{errorString} = 'init failed. probing the network list endpoint failed... ' . $@;
605 0 $self->warn;
606 };
607 }
608  
609 1 $self->{inited} = 1;
610 } ## end sub init
611  
612 =head2 ban
613  
614 Bans an IP. The value of ban is validated as being a IPv4 or IPv6 address
615 and lowercased, then appended to the network list via a POST to the list's
616 C</append> endpoint. Banning an already banned IP is a noop.
617  
618 $backend->ban(ban => $ip);
619  
620 =cut
621  
622 2 ▶sub ban {
Subroutine ban: called CC=10 SCAR=37.2
Pod documented
623 2 my ( $self, %opts ) = @_;
624  
625 2 $self->errorblank;
626  
627 2 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 2 2
628 0 $self->{error} = 1;
629 0 $self->{errorString} = 'backend has not been inited';
630 0 $self->warn;
631 0 return;
632 }
633  
634 2 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 2 2
elsif (ref $opts{'ban'} ne '') { } 0 2 2
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/) { } 0 2 2
635 0 $self->{error} = 9;
636 0 $self->{errorString} = 'Nothing specified for the value ban';
637 0 $self->warn;
638 0 return;
639 } elsif ( ref( $opts{ban} ) ne '' ) {
640 0 $self->{error} = 10;
641 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
642 0 $self->warn;
643 0 return;
644 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition66%2/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
l!l&&r!l&&!r
110
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
Truth table66%2/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
ABresult
1X1
011
000
645 && $opts{ban} !~ /\A$IPv6_re\z/ )
646 {
647 0 $self->{error} = 10;
648 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
649 0 $self->warn;
650 0 return;
651 }
652  
653 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
654 2 $opts{ban} = lc( $opts{ban} );
655  
656 2 ▶ if ( $self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned"}{$opts{"ban"}}) 0 2 2
657 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
658 0 $self->{frontend_obj}->{test_data} = 'already banned';
659 }
660 0 return;
661 }
662  
663 2 my $body = $self->_json->encode( { list => [ $opts{ban} ] } );
664  
665 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 2 0 2
666 2 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_append_url, content => $body } ];
667 } else {
668 0 local $@;
669 0 ▶ eval { $self->_request( 'POST', $self->_append_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_append_url, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
670 0 $self->{error} = 13;
671 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
672 0 $self->warn;
673 0 return;
674 };
675 }
676  
677 2 $self->{banned}{ $opts{ban} } = 1;
678 } ## end sub ban
679  
680 =head2 unban
681  
682 Unbans an IP. The value of ban is validated as being a IPv4 or IPv6 address
683 and lowercased, then removed from the network list via a DELETE of its
684 element at the list's C</elements> endpoint. Unbanning an IP that is not
685 banned is a noop.
686  
687 $backend->unban(ban => $ip);
688  
689 =cut
690  
691 1 ▶sub unban {
Subroutine unban: called CC=10 SCAR=38.2
Pod documented
692 1 my ( $self, %opts ) = @_;
693  
694 1 $self->errorblank;
695  
696 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
697 0 $self->{error} = 1;
698 0 $self->{errorString} = 'backend has not been inited';
699 0 $self->warn;
700 0 return;
701 }
702  
703 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/) { } 0 1 1
704 0 $self->{error} = 9;
705 0 $self->{errorString} = 'Nothing specified for the value ban';
706 0 $self->warn;
707 0 return;
708 } elsif ( ref( $opts{ban} ) ne '' ) {
709 0 $self->{error} = 10;
710 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
711 0 $self->warn;
712 0 return;
713 ▶ } elsif ( $opts{ban} !~ /\A$IPv4_re\z/
Condition33%1/3
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
l!l&&r!l&&!r
100
MC/DC0%0/2
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ || $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
$opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/ $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
Truth table33%1/3
A || B
A= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv4_re\z/B= $opts{'ban'} =~ /\A$Net::Firewall::BlockerHelper::backends::akamai::IPv6_re\z/
ABresult
1X1
011
000
714 && $opts{ban} !~ /\A$IPv6_re\z/ )
715 {
716 0 $self->{error} = 10;
717 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 IP';
718 0 $self->warn;
719 0 return;
720 }
721  
722 # lowercase so the same IPv6 IP in differing cases can't result in duplicate entries
723 1 $opts{ban} = lc( $opts{ban} );
724  
725 1 ▶ if ( !$self->{banned}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned"}{$opts{"ban"}}) 0 1 1
726 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
727 0 $self->{frontend_obj}->{test_data} = 'not banned';
728 }
729 0 return;
730 }
731  
732 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
733 1 $self->{frontend_obj}->{test_data} = [ { method => 'DELETE', url => $self->_element_url( $opts{ban} ) } ];
734 } else {
735 0 local $@;
736 0 ▶ eval { $self->_request( 'DELETE', $self->_element_url( $opts{ban} ) ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("DELETE", $self->_element_url($opts{"ban"})); 1 } } or do { $self->{"error"} = 14; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
737 0 $self->{error} = 14;
738 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
739 0 $self->warn;
740 0 return;
741 };
742 }
743  
744 1 delete( $self->{banned}{ $opts{ban} } );
745 } ## end sub unban
746  
747 =head2 ban_cidr
748  
749 Bans a CIDR range. The value of ban is validated as being a IPv4 or IPv6
750 CIDR and lowercased, then appended to the network list via a POST to the
751 list's C</append> endpoint; Akamai network lists accept a CIDR range as a
752 list element in the same manner as a single address. Banning an already
753 banned range is a noop.
754  
755 $backend->ban_cidr(ban => '1.2.3.0/24');
756  
757 =cut
758  
759 1 ▶sub ban_cidr {
Subroutine ban_cidr: called CC=9 SCAR=36.0
Pod documented
760 1 my ( $self, %opts ) = @_;
761  
762 1 $self->errorblank;
763  
764 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
765 0 $self->{error} = 1;
766 0 $self->{errorString} = 'backend has not been inited';
767 0 $self->warn;
768 0 return;
769 }
770  
771 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 1 1
772 0 $self->{error} = 9;
773 0 $self->{errorString} = 'Nothing specified for the value ban';
774 0 $self->warn;
775 0 return;
776 } elsif ( ref( $opts{ban} ) ne '' ) {
777 0 $self->{error} = 37;
778 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
779 0 $self->warn;
780 0 return;
781 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
782 0 $self->{error} = 37;
783 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
784 0 $self->warn;
785 0 return;
786 }
787  
788 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
789 1 $opts{ban} = lc( $opts{ban} );
790  
791 1 ▶ if ( $self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
792 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
793 0 $self->{frontend_obj}->{test_data} = 'already banned';
794 }
795 0 return;
796 }
797  
798 1 my $body = $self->_json->encode( { list => [ $opts{ban} ] } );
799  
800 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
801 1 $self->{frontend_obj}->{test_data} = [ { method => 'POST', url => $self->_append_url, content => $body } ];
802 } else {
803 0 local $@;
804 0 ▶ eval { $self->_request( 'POST', $self->_append_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_append_url, $body); 1 } } or do { $self->{"error"} = 35; $self->{"errorString"} = 'banning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
805 0 $self->{error} = 35;
806 0 $self->{errorString} = 'banning "' . $opts{ban} . '" failed... ' . $@;
807 0 $self->warn;
808 0 return;
809 };
810 }
811  
812 1 $self->{banned_cidr}{ $opts{ban} } = 1;
813 } ## end sub ban_cidr
814  
815 =head2 unban_cidr
816  
817 Unbans a CIDR range. The value of ban is validated as being a IPv4 or IPv6
818 CIDR and lowercased, then removed from the network list via a DELETE of its
819 element at the list's C</elements> endpoint. Unbanning a range that is not
820 banned is a noop.
821  
822 $backend->unban_cidr(ban => '1.2.3.0/24');
823  
824 =cut
825  
826 1 ▶sub unban_cidr {
Subroutine unban_cidr: called CC=9 SCAR=36.4
Pod documented
827 1 my ( $self, %opts ) = @_;
828  
829 1 $self->errorblank;
830  
831 1 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 1 1
832 0 $self->{error} = 1;
833 0 $self->{errorString} = 'backend has not been inited';
834 0 $self->warn;
835 0 return;
836 }
837  
838 1 ▶ if ( !defined( $opts{ban} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opts{'ban'}) { } 0 1 1
elsif (ref $opts{'ban'} ne '') { } 0 1 1
elsif (not $self->_valid_cidr($opts{'ban'})) { } 0 1 1
839 0 $self->{error} = 9;
840 0 $self->{errorString} = 'Nothing specified for the value ban';
841 0 $self->warn;
842 0 return;
843 } elsif ( ref( $opts{ban} ) ne '' ) {
844 0 $self->{error} = 37;
845 0 $self->{errorString} = 'Bad ref type for ban... ref is "' . ref( $opts{ban} ) . '"';
846 0 $self->warn;
847 0 return;
848 } elsif ( !$self->_valid_cidr( $opts{ban} ) ) {
849 0 $self->{error} = 37;
850 0 $self->{errorString} = 'ban item,"' . $opts{ban} . '", does not appear to be a IPv4 or IPv6 CIDR';
851 0 $self->warn;
852 0 return;
853 }
854  
855 # lowercase so the same IPv6 CIDR in differing cases can't result in duplicate entries
856 1 $opts{ban} = lc( $opts{ban} );
857  
858 1 ▶ if ( !$self->{banned_cidr}{ $opts{ban} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"banned_cidr"}{$opts{"ban"}}) 0 1 1
859 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
860 0 $self->{frontend_obj}->{test_data} = 'not banned';
861 }
862 0 return;
863 }
864  
865 1 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 1 0 1
866 1 $self->{frontend_obj}->{test_data} = [ { method => 'DELETE', url => $self->_element_url( $opts{ban} ) } ];
867 } else {
868 0 local $@;
869 0 ▶ eval { $self->_request( 'DELETE', $self->_element_url( $opts{ban} ) ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("DELETE", $self->_element_url($opts{"ban"})); 1 } } or do { $self->{"error"} = 36; $self->{"errorString"} = 'unbanning "' . $opts{"ban"} . '" failed... ' . $@; $self->warn; return } 0 0 0
870 0 $self->{error} = 36;
871 0 $self->{errorString} = 'unbanning "' . $opts{ban} . '" failed... ' . $@;
872 0 $self->warn;
873 0 return;
874 };
875 }
876  
877 1 delete( $self->{banned_cidr}{ $opts{ban} } );
878 } ## end sub unban_cidr
879  
880 =head2 list_cidr
881  
882 List banned CIDR ranges. Returns an array of the currently banned CIDR
883 ranges from internal state; the network list is not fetched. Single IPs are
884 not included; for those see L</list>.
885  
886 my @banned_cidrs = $backend->list_cidr;
887  
888 =cut
889  
890 2 ▶sub list_cidr {
Subroutine list_cidr: called CC=2 SCAR=7.0
Pod documented
891 2 my ( $self, %opts ) = @_;
892  
893 2 $self->errorblank;
894  
895 2 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 2 0 2
896 2 $self->{frontend_obj}->{test_data} = 'list_cidr';
897 }
898  
899 2 return keys( %{ $self->{banned_cidr} } );
900 }
901  
902 =head2 list
903  
904 List banned IPs. Returns an array of the currently banned single IPs from
905 internal state; the network list is not fetched. CIDR ranges are not
906 included; for those see L</list_cidr>.
907  
908 my @banned = $backend->list;
909  
910 =cut
911  
912 0 ▶sub list {
Subroutine list: not called CC=2 SCAR=17.9
Pod documented
913 0 my ( $self, %opts ) = @_;
914  
915 0 $self->errorblank;
916  
917 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
918 0 $self->{frontend_obj}->{test_data} = 'list';
919 }
920  
921 0 return keys( %{ $self->{banned} } );
922 }
923  
924 =head2 re_init
925  
926 Tears down and re-initiates the backend. teardown is called best effort,
927 then init, after which every previously banned single IP and CIDR range is
928 re-added to the network list via POSTs to the list's C</append> endpoint.
929  
930 $backend->re_init;
931  
932 =cut
933  
934 0 ▶sub re_init {
Subroutine re_init: not called CC=5 SCAR=34.0
Pod documented
935 0 my ( $self, %opts ) = @_;
936  
937 0 $self->errorblank;
938  
939 # teardown is best effort here as a partially or fully wiped setup is
940 # exactly what re_init needs to recover from; init cleans up any remnants
941 {
942 0 local $@;
943 0 eval { $self->teardown; };
944 }
945 0 $self->init;
946  
947 # single IPs and CIDR ranges are both re-added as list elements
948 0 my @to_ban = ( sort( keys( %{ $self->{banned} } ) ), sort( keys( %{ $self->{banned_cidr} } ) ) );
949  
950 0 my @re_init_test_data;
951 0 foreach my $item (@to_ban) {
952 0 my $body = $self->_json->encode( { list => [$item] } );
953  
954 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
955 0 push( @re_init_test_data, { method => 'POST', url => $self->_append_url, content => $body } );
956 } else {
957 0 local $@;
958 0 ▶ eval { $self->_request( 'POST', $self->_append_url, $body ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("POST", $self->_append_url, $body); 1 } } or do { $self->{"error"} = 13; $self->{"errorString"} = 'banning "' . $item . '" failed... ' . $@; $self->warn } 0 0 0
959 0 $self->{error} = 13;
960 0 $self->{errorString} = 'banning "' . $item . '" failed... ' . $@;
961 0 $self->warn;
962 };
963 }
964 } ## end foreach my $item (@to_ban)
965  
966 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
967 0 $self->{frontend_obj}->{test_data} = \@re_init_test_data;
968 }
969  
970 0 $self->{inited} = 1;
971 } ## end sub re_init
972  
973 =head2 teardown
974  
975 Tears down the setup for the backend by DELETEing the element for each
976 currently banned single IP from the network list. Banned CIDR ranges are
977 left in place. The internal list of bans is kept, so a following re_init
978 will re-add them.
979  
980 $backend->teardown;
981  
982 =cut
983  
984 0 ▶sub teardown {
Subroutine teardown: not called CC=5 SCAR=34.0
Pod documented
985 0 my ( $self, %opts ) = @_;
986  
987 0 $self->errorblank;
988  
989 0 $self->{inited} = 0;
990  
991 0 my @requests;
992 0 foreach my $item ( sort( keys( %{ $self->{banned} } ) ) ) {
993 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
994 0 push( @requests, { method => 'DELETE', url => $self->_element_url($item) } );
995 } else {
996 0 local $@;
997 0 ▶ eval { $self->_request( 'DELETE', $self->_element_url($item) ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("DELETE", $self->_element_url($item)); 1 } } or do { $self->{"error"} = 17; $self->{"errorString"} = 'teardown failed removing the element for "' . $item . '"... ' . $@; $self->warn } 0 0 0
998 0 $self->{error} = 17;
999 0 $self->{errorString} = 'teardown failed removing the element for "' . $item . '"... ' . $@;
1000 0 $self->warn;
1001 };
1002 }
1003 } ## end foreach my $item ( sort( keys( %{ $self->{banned...})))
1004  
1005 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1006 0 $self->{frontend_obj}->{test_data} = \@requests;
1007 }
1008 } ## end sub teardown
1009  
1010 =head2 stop
1011  
1012 Alias for L</teardown>, provided for parity with the fail2ban C<actionstop>
1013 concept.
1014  
1015 $backend->stop;
1016  
1017 =cut
1018  
1019 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
1020 0 my ( $self, %opts ) = @_;
1021  
1022 0 return $self->teardown(%opts);
1023 }
1024  
1025 =head2 check
1026  
1027 Verifies the endpoint and credentials are still usable by fetching the
1028 network list. Returns a true value if so and a false value otherwise. This is
1029 the equivalent of fail2ban's C<actioncheck>.
1030  
1031 if ( !$backend->check ) {
1032 $backend->re_init;
1033 }
1034  
1035 =cut
1036  
1037 5 ▶sub check {
Subroutine check: called CC=3 SCAR=14.7
Pod documented
1038 5 my ( $self, %opts ) = @_;
1039  
1040 5 $self->errorblank;
1041  
1042 5 my $url = $self->_list_url;
1043  
1044 5 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 5 0 5
1045 5 $self->{frontend_obj}->{test_data} = [ { method => 'GET', url => $url } ];
1046 5 return 1;
1047 }
1048  
1049 0 local $@;
1050 0 ▶ eval { $self->_request( 'GET', $url ); 1; } or return 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("GET", $url); 1 } } or return 0 0 0 0
1051  
1052 0 return 1;
1053 } ## end sub check
1054  
1055 =head2 flush
1056  
1057 Removes all currently banned IPs and CIDR ranges at once by DELETEing their
1058 elements from the network list and forgetting them. This is the equivalent
1059 of fail2ban's C<actionflush>.
1060  
1061 $backend->flush;
1062  
1063 =cut
1064  
1065 0 ▶sub flush {
Subroutine flush: not called CC=6 SCAR=37.4
Pod documented
1066 0 my ( $self, %opts ) = @_;
1067  
1068 0 $self->errorblank;
1069  
1070 0 ▶ if ( !$self->{inited} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"inited"}) 0 0 0
1071 0 $self->{error} = 1;
1072 0 $self->{errorString} = 'backend has not been inited';
1073 0 $self->warn;
1074 0 return;
1075 }
1076  
1077 0 my @requests;
1078 0 foreach my $item ( sort( keys( %{ $self->{banned} } ) ), sort( keys( %{ $self->{banned_cidr} } ) ) ) {
1079 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'testing'}) { } 0 0 0
1080 0 push( @requests, { method => 'DELETE', url => $self->_element_url($item) } );
1081 } else {
1082 0 local $@;
1083 0 ▶ eval { $self->_request( 'DELETE', $self->_element_url($item) ); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_request("DELETE", $self->_element_url($item)); 1 } } or do { $self->{"error"} = 25; $self->{"errorString"} = 'flush failed removing the element for "' . $item . '"... ' . $@; $self->warn } 0 0 0
1084 0 $self->{error} = 25;
1085 0 $self->{errorString} = 'flush failed removing the element for "' . $item . '"... ' . $@;
1086 0 $self->warn;
1087 };
1088 }
1089 } ## end foreach my $item ( sort( keys( %{ $self...}))...)
1090  
1091 0 ▶ if ( $self->{testing} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"testing"}) 0 0 0
1092 0 $self->{frontend_obj}->{test_data} = \@requests;
1093 }
1094  
1095 0 $self->{banned} = {};
1096 0 $self->{banned_cidr} = {};
1097 } ## end sub flush
1098  
1099 =head1 ERROR CODES / FLAGS
1100  
1101 Error handling is provided by L<Error::Helper>. All
1102 errors are considered fatal.
1103  
1104 =head2 1, notInited
1105  
1106 The backend has not been inited yet.
1107  
1108 =head2 6, invalidPrefixSpecified
1109  
1110 The specified prefix did not match /^[a-zA-Z0-9]+$/.
1111  
1112 =head2 7, invalidName
1113  
1114 The name is either undef or does not match /^[a-zA-Z0-9\-]+$/.
1115  
1116 =head2 8, optionsNotHash
1117  
1118 The item passed to new for options is not a hash.
1119  
1120 =head2 9, noBanItem
1121  
1122 No IP or CIDR range specified to ban or unban.
1123  
1124 =head2 10, banItemNotIP
1125  
1126 The item to ban is not an IP. Either wrong ref type or regexp
1127 test using L<Regexp::IPv4> and L<Regexp::IPv6> failed.
1128  
1129 =head2 12, backendInitError
1130  
1131 Failed to init the backend.
1132  
1133 =head2 13, banFailed
1134  
1135 Failed to ban the item.
1136  
1137 =head2 14, unbanFailed
1138  
1139 Failed to unban the item.
1140  
1141 =head2 15, listFailed
1142  
1143 Failed to get a list of bans.
1144  
1145 =head2 16, reInitFailed
1146  
1147 Failed to re_init the backend.
1148  
1149 =head2 17, teardownFailed
1150  
1151 Failed to teardown the backend.
1152  
1153 =head2 18, alreadyInited
1154  
1155 init called, but the backend has already been inited.
1156  
1157 =head2 23, initFailed
1158  
1159 init failed. Probing the network list endpoint failed.
1160  
1161 =head2 24, checkFailed
1162  
1163 The backend check raised an error.
1164  
1165 =head2 25, flushFailed
1166  
1167 Failed to flush the bans.
1168  
1169 =head2 26, portsNotSupported
1170  
1171 The akamai backend blocks whole IPs and does not support ports.
1172  
1173 =head2 27, protocolsNotSupported
1174  
1175 The akamai backend blocks whole IPs and does not support protocols.
1176  
1177 =head2 30, hostNotDefined
1178  
1179 The option host is undef or blank.
1180  
1181 =head2 31, clientTokenNotDefined
1182  
1183 The option client_token is undef or blank.
1184  
1185 =head2 32, clientSecretNotDefined
1186  
1187 The option client_secret is undef or blank.
1188  
1189 =head2 33, accessTokenNotDefined
1190  
1191 The option access_token is undef or blank.
1192  
1193 =head2 34, networkListIdNotDefined
1194  
1195 The option network_list_id is undef or blank.
1196  
1197 =head2 35, banCidrFailed
1198  
1199 Failed to ban the CIDR range.
1200  
1201 =head2 36, unbanCidrFailed
1202  
1203 Failed to unban the CIDR range.
1204  
1205 =head2 37, cidrItemNotCidr
1206  
1207 The item to ban is not a CIDR range. Either wrong ref type or it is not an
1208 IPv4 or IPv6 address followed by a prefix length valid for its family.
1209  
1210 =head2 38, cidrNotSupported
1211  
1212 The backend does not support CIDR bans.
1213  
1214 =head2 39, listCidrFailed
1215  
1216 Failed to get a list of CIDR bans.
1217  
1218 =head1 AUTHOR
1219  
1220 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.ent> >>
1221  
1222 =head1 BUGS
1223  
1224 Please report any bugs or feature requests to C<bug-net-firewall-blockerhelper at rt.cpan.org>, or through
1225 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-Firewall-BlockerHelper>.
1226  
1227 =head1 LICENSE AND COPYRIGHT
1228  
1229 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1230  
1231 This is free software, licensed under:
1232  
1233 The GNU Lesser General Public License, Version 2.1, February 1999
1234  
1235  
1236 =cut
1237  
1238 1 1; # End of Net::Firewall::BlockerHelper::backends::akamai
« BlockerHelper/backends/shorewall.pm ↑ Summary BlockerHelper/backends/panos.pm »