lib/App/WebPerimeterScan/HTTP.pm

filter: Statementstmt 98.4% 253 / 257 Branchbran 73.9% 71 / 96 Conditioncond 60.2% 50 / 83 MC/DCmcdc 31.3% 16 / 51 Subroutinesub 100% 49 / 49 Podpod 100% 4 / 4 totaltotal 82.0% 443 / 540 CC 81 SCAR 17.9
CC
81
Cov
86%
_read_chunked
16.2
_target
9.6
_read_until
9.5
CRAP 6.0
« lib/App/WebPerimeterScan/Report.pm ↑ Summary lib/App/WebPerimeterScan/I18N.pm »
1 package App::WebPerimeterScan::HTTP;
2  
3 29 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 29 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 29 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # Network failures are results, not exceptions: a refused or reset
8 # connection is what a perimeter scan is looking for. These builtins keep
9 # their ordinary return-value behaviour so the code below can report them.
10 29 ▶no autodie qw(close sysread syswrite);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 29 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 29 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 29 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 29 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 29 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 29 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 29 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
19 29 ▶use Time::HiRes qw(time sleep);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 29 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 29 ▶use App::WebPerimeterScan::I18N ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 29 ▶use parent -norequire, 'App::WebPerimeterScan::I18N';
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 29 our $VERSION = '0.001.0';
26  
27 # Defaults for new(); a plain hash so Object::Configure, or a caller, can
28 # change them for every client created afterwards.
29 29 our %config = (
30 timeout => 10, # seconds for one whole request and response
31 delay => 0.5, # minimum seconds between requests to one host
32 max_size => 2_000_000, # bytes of body kept; the rest is discarded
33 );
34  
35 # Sent on every request. identity: the body is inspected, so no gzip.
36 29 Readonly::Hash my %DEFAULT_HEADERS => (
37 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
38 'Accept-Language' => 'en-GB,en;q=0.9',
39 'Accept-Encoding' => 'identity',
40 'Connection' => 'close',
41 );
42  
43 # The User-Agent names the release, so a site operator reading their logs
44 # can tell which version of the tool sent a request.
45 29 Readonly::Scalar my $AGENT => "webperimeter/$VERSION (authorised perimeter check)";
46  
47 29 Readonly::Scalar my $DEFAULT_METHOD => 'GET';
48 29 Readonly::Hash my %DEFAULT_PORT => (http => 80, https => 443);
49  
50 # A request method is a token; anything else could split the request line.
51 29 Readonly::Scalar my $METHOD_RE => qr/\A[A-Z]+\z/;
52  
53 # Statuses whose responses never carry a body (RFC 9110 6.4.1).
54 29 Readonly::Hash my %NO_BODY_STATUS => (204 => 1, 304 => 1);
55  
56 # A header block larger than this is not a web server we want to parse.
57 29 Readonly::Scalar my $MAX_HEADER_BYTES => 65_536;
58  
59 # One sysread at a time.
60 29 Readonly::Scalar my $READ_SIZE => 16_384;
61  
62 # End of the header block, and one line ending, tolerating bare LF.
63 29 Readonly::Scalar my $HEADER_END => qr/\r?\n\r?\n/;
64 29 Readonly::Scalar my $LINE_END => qr/\r?\n/;
65  
66 =encoding utf8
67  
68 =head1 NAME
69  
70 App::WebPerimeterScan::HTTP - minimal HTTP/1.1 client for perimeter scanning
71  
72 =head1 VERSION
73  
74 Version 0.001.0
75  
76 =head1 SYNOPSIS
77  
78 Fetch a page and check for an error first:
79  
80 use App::WebPerimeterScan::HTTP;
81  
82 my $http = App::WebPerimeterScan::HTTP->new;
83 my $res = $http->fetch('https://example.com/');
84  
85 if($res->{error}) {
86 print "failed: $res->{error}\n";
87 } else {
88 print "$res->{status} $res->{reason}\n";
89 print 'Server: ', $http->header($res, 'Server') // '(none)', "\n";
90 }
91  
92 Read every C<Set-Cookie> header separately:
93  
94 for my $cookie (@{ $res->{set_cookie} || [] }) {
95 print "cookie: $cookie\n";
96 }
97  
98 Send an C<OPTIONS> request with an extra header:
99  
100 my $options = $http->fetch('https://example.com/',
101 method => 'OPTIONS',
102 headers => [ 'Origin: https://evil.example' ],
103 );
104 print $http->header($options, 'Allow') // '', "\n";
105  
106 Follow a redirect yourself, only when the target is in scope:
107  
108 my $first = $http->fetch('http://example.com/');
109 my $next = $http->header($first, 'Location');
110 if(defined $next && $scope->allows(URI->new($next)->host)) {
111 my $second = $http->fetch($next);
112 }
113  
114 =head1 DESCRIPTION
115  
116 This is a small HTTP client made for the scanner. It sends one request and
117 returns the response as a hash reference. It is written for this module,
118 instead of using L<LWP> or L<HTTP::Tiny>, for two reasons:
119  
120 =over 4
121  
122 =item * The scanner must see every C<Set-Cookie> header separately. Those
123 modules join repeated headers with commas, and a cookie's C<Expires> date
124 also contains a comma, so the join cannot be undone.
125  
126 =item * The scanner must see redirects, not follow them. The caller then
127 decides if the next host is in scope.
128  
129 =back
130  
131 The client waits between two requests to the same host (the C<delay>), so
132 that a scan does not overload the server.
133  
134 The client does B<not> check TLS certificates. This is on purpose: a site
135 with an expired or wrong certificate can still be scanned. The certificate
136 is checked, and reported, by L<App::WebPerimeterScan::TLS>. Do not use this
137 client to send anything secret.
138  
139 Network problems are returned, not thrown: when a request fails, the result
140 has an C<error> field and no C<status>. Only a programming mistake (an
141 unknown argument, or a C<method> that is not made only of upper-case
142 letters A to Z) is fatal.
143  
144 =head1 REQUIREMENTS
145  
146 C<IO::Socket::INET> 1.31 and C<IO::Select> 1.17. HTTPS requests also need
147 C<IO::Socket::SSL> 2.000, whose installation needs the OpenSSL headers.
148  
149 =head1 SUBROUTINES/METHODS
150  
151 =head2 new
152  
153 Purpose: create a client.
154  
155 Args: named C<timeout> (seconds per request), C<delay> (seconds between
156 requests to one host), C<max_size> (bytes of body kept), C<agent>
157 (User-Agent). Defaults come from C<%App::WebPerimeterScan::HTTP::config>.
158  
159 Returns: the new object.
160  
161 Side Effects: none; no connection is made until C<fetch>.
162  
163 Usage: C<< my $http = App::WebPerimeterScan::HTTP->new(timeout => 5); >>
164  
165 =head3 EXAMPLE
166  
167 my $http = App::WebPerimeterScan::HTTP->new(delay => 0); # no throttle, for tests
168  
169 =head3 API SPECIFICATION
170  
171 =head4 INPUT
172  
173 {
174 timeout => { type => 'number', min => 0, optional => 1 },
175 delay => { type => 'number', min => 0, optional => 1 },
176 max_size => { type => 'integer', min => 1, optional => 1 },
177 agent => { type => 'string', min => 1, optional => 1 },
178 }
179  
180 =head4 OUTPUT
181  
182 { type => 'object', isa => 'App::WebPerimeterScan::HTTP' }
183  
184 =head3 MESSAGES
185  
186 Message Meaning / resolution
187 ------------------------------- -----------------------------------
188 Parameter 'X' ... (fatal) A value is negative or not a number.
189 Unknown parameter 'X' (fatal) A misspelt argument name.
190  
191 =cut
192  
193 sub new
194 23 ▶{
Subroutine new: called CC=6 SCAR=19.3
Pod documented
195 23 my $class = shift;
196  
197 23 ▶ my $args = validate_strict(
Condition100%2/2
get_params(undef, \@_) // {}
l!l
221
MC/DC100%1/1
get_params(undef, \@_) // {}
get_params(undef, \@_)
Truth table100%2/2
A
A= get_params(undef, \@_)
Aresult
11
00
198 schema => {
199 timeout => { type => 'number', min => 0, optional => 1 },
200 delay => { type => 'number', min => 0, optional => 1 },
201 max_size => { type => 'integer', min => 1, optional => 1 },
202 agent => { type => 'string', min => 1, optional => 1 },
203 },
204 input => get_params(undef, \@_) // {},
205 );
206  
207 return bless {
208 timeout => $args->{timeout} // $config{timeout},
209 delay => $args->{delay} // $config{delay},
210 max_size => $args->{max_size} // $config{max_size},
211 21 ▶ agent => $args->{agent} // $AGENT,
Condition58%7/12
$args->{"timeout"} // $App::WebPerimeterScan::HTTP::config{"timeout"}
l!l&&r!l&&!r
1830
$args->{"delay"} // $App::WebPerimeterScan::HTTP::config{"delay"}
l!l&&r!l&&!r
2010
$args->{"max_size"} // $App::WebPerimeterScan::HTTP::config{"max_size"}
l!l&&r!l&&!r
1470
$args->{"agent"} // $AGENT
l!l&&r!l&&!r
0210
MC/DC0%0/2
$args->{"timeout"} // $App::WebPerimeterScan::HTTP::config{"timeout"}
$args->{"timeout"} $App::WebPerimeterScan::HTTP::config{"timeout"}
MC/DC0%0/2
$args->{"delay"} // $App::WebPerimeterScan::HTTP::config{"delay"}
$args->{"delay"} $App::WebPerimeterScan::HTTP::config{"delay"}
MC/DC0%0/2
$args->{"max_size"} // $App::WebPerimeterScan::HTTP::config{"max_size"}
$args->{"max_size"} $App::WebPerimeterScan::HTTP::config{"max_size"}
MC/DC0%0/2
$args->{"agent"} // $AGENT
$args->{"agent"} $AGENT
Truth table66%2/3
A // B
A= $args->{"timeout"}B= $App::WebPerimeterScan::HTTP::config{"timeout"}
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args->{"delay"}B= $App::WebPerimeterScan::HTTP::config{"delay"}
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args->{"max_size"}B= $App::WebPerimeterScan::HTTP::config{"max_size"}
ABresult
1X1
011
000
Truth table33%1/3
A // B
A= $args->{"agent"}B= $AGENT
ABresult
1X1
011
000
212 last => {}, # host => time of the last request
213 requests => 0,
214 }, $class;
215 }
216  
217 =head2 requests
218  
219 Purpose: the number of requests actually sent (connections that opened).
220  
221 Args: none.
222  
223 Returns: a non-negative integer.
224  
225 Side Effects: none.
226  
227 Usage: C<< printf "Requests: %d\n", $http->requests; >>
228  
229 =head3 EXAMPLE
230  
231 $http->fetch($url);
232 print $http->requests, "\n";
233  
234 =head3 API SPECIFICATION
235  
236 =head4 INPUT
237  
238 {}
239  
240 =head4 OUTPUT
241  
242 { type => 'integer', min => 0 }
243  
244 =head3 MESSAGES
245  
246 None.
247  
248 =cut
249  
250 sub requests
251 9 ▶{
Subroutine requests: called CC=1 SCAR=0.0
Pod documented
252 9 my ($self) = @_;
253  
254 9 return $self->{requests};
255 }
256  
257 =head2 fetch
258  
259 Purpose: send one request and read the response.
260  
261 Args: C<$url>, then named C<method> (an upper-case token, default C<GET>)
262 and C<headers> (an array reference of C<Name: value> strings; any
263 containing CR or LF are dropped so they cannot inject headers).
264  
265 Returns: a hash reference. On failure it has C<url> and C<error> (a
266 translated message), plus C<host> and C<port> when the URL was usable. On
267 success: C<url>, C<host>, C<port>, C<scheme>, C<status>, C<reason>,
268 C<http_version>, C<headers> (lower-case name =E<gt> array of values, in
269 order), C<set_cookie>, C<body>, C<truncated>, C<content_type>,
270 C<raw_headers> and C<elapsed>.
271  
272 Side Effects: network traffic; may sleep to honour C<delay>; increments
273 C<requests> when a connection opens.
274  
275 Usage: C<< my $res = $http->fetch($url, method => 'OPTIONS'); >>
276  
277 =head3 EXAMPLE
278  
279 my $res = $http->fetch('https://example.com/',
280 headers => [ 'Origin: https://ws-probe.invalid' ]);
281 if($res->{error}) {
282 print "failed: $res->{error}\n";
283 } else {
284 print "$res->{status} ", scalar @{ $res->{set_cookie} }, " cookie(s)\n";
285 }
286  
287 =head3 API SPECIFICATION
288  
289 =head4 INPUT
290  
291 {
292 url => { type => 'string', min => 1, position => 0 },
293 method => { type => 'string', matches => qr/\A[A-Z]+\z/, optional => 1 },
294 headers => { type => 'arrayref', optional => 1 },
295 }
296  
297 =head4 OUTPUT
298  
299 { type => 'hashref' } # see Returns; 'error' present on failure
300  
301 =head3 MESSAGES
302  
303 These are returned in C<error>, not thrown:
304  
305 Message Meaning / resolution
306 ---------------------------- ---------------------------------------
307 invalid URL The URL did not parse.
308 unsupported scheme 'S' Only http and https are fetched.
309 URL has no host The URL has no authority part.
310 connect failed: E TCP or TLS connect failed; E says why.
311 request write failed The connection closed or timed out
312 while sending.
313 no response headers Nothing usable arrived before timeout.
314 malformed status line The reply was not HTTP/1.x.
315  
316 =head3 PSEUDOCODE
317  
318 parse the URL; return an error for anything but http(s) with a host
319 wait until the per-host delay has passed
320 connect (TLS without verification for https); return an error on failure
321 write the request line, Host, User-Agent, fixed and extra headers
322 read until the blank line; parse the status line and headers
323 read the body by Content-Length, chunked encoding or to EOF
324 return the parsed response
325  
326 =cut
327  
328 sub fetch
329 60 ▶{
Subroutine fetch: called CC=5 SCAR=16.1
Pod documented
330 60 my ($self, $url, @rest) = @_;
331  
332 60 ▶ my $opt = validate_strict(
Condition100%2/2
get_params(undef, \@rest) // {}
l!l
1644
MC/DC100%1/1
get_params(undef, \@rest) // {}
get_params(undef, \@rest)
Truth table100%2/2
A
A= get_params(undef, \@rest)
Aresult
11
00
333 schema => {
334 method => { type => 'string', matches => $METHOD_RE, optional => 1 },
335 headers => { type => 'arrayref', optional => 1 },
336 },
337 input => get_params(undef, \@rest) // {},
338 );
339 59 ▶ my $method = $opt->{method} // $DEFAULT_METHOD;
Condition66%2/3
$opt->{"method"} // $DEFAULT_METHOD
l!l&&r!l&&!r
8510
MC/DC0%0/2
$opt->{"method"} // $DEFAULT_METHOD
$opt->{"method"} $DEFAULT_METHOD
Truth table66%2/3
A // B
A= $opt->{"method"}B= $DEFAULT_METHOD
ABresult
1X1
011
000
340  
341 59 my $target = _target($url);
342 59 ▶ return $target if $target->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"error"} 4 55 59
343  
344 55 $self->_throttle($target->{host});
345  
346 55 my $started = time;
347 55 my $sock = $self->_connect($target);
348 55 ▶ return _failure($target, 'http.connect_failed', { error => _connect_error($target) })
Branch: 1 branch
BranchTrueFalseTotal
unless $sock 4 51 55
349 unless $sock;
350  
351 # The timeout covers the exchange; the connect had its own.
352 51 $self->{requests}++;
353 51 my $deadline = time + $self->{timeout};
354  
355 51 my $response = $self->_exchange($sock, $target, $method, $opt->{headers}, $deadline);
356 51 close $sock;
357  
358 51 $response->{elapsed} = time - $started;
359  
360 51 return $response;
361 }
362  
363 =head2 header
364  
365 Purpose: the last value of a response header, without dealing in array
366 references.
367  
368 Args: C<$response> (from C<fetch>) and C<$name> (any case).
369  
370 Returns: the value, or C<undef> if the header is absent.
371  
372 Side Effects: none.
373  
374 Usage: C<< my $server = $http->header($res, 'Server'); >>
375  
376 =head3 EXAMPLE
377  
378 my $type = $http->header($res, 'Content-Type') // 'none';
379  
380 =head3 API SPECIFICATION
381  
382 =head4 INPUT
383  
384 {
385 response => { type => 'hashref', position => 0 },
386 name => { type => 'string', min => 1, position => 1 },
387 }
388  
389 =head4 OUTPUT
390  
391 { type => 'string', optional => 1 }
392  
393 =head3 MESSAGES
394  
395 None.
396  
397 =cut
398  
399 sub header
400 2 ▶{
Subroutine header: called CC=2 SCAR=6.9
Pod documented
401 2 my ($self, $response, $name) = @_;
402  
403 2 my $values = $response->{headers}{ lc $name };
404  
405 2 ▶ return $values ? $values->[-1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$values ? : 1 1 2
406 }
407  
408 # _target
409 # Purpose: split a URL into what a request needs.
410 # Entry: $url is any string.
411 # Exit: hashref of url, scheme, host, port, path, host_header; or a
412 # failure hashref with 'error'.
413 # Side effects: none.
414 59 ▶sub _target :Private
Subroutine _target: called CC=9 SCAR=22.6
415 {
416 59 my ($url) = @_;
417  
418 59 my $uri = eval { URI->new($url) };
419 59 ▶ return _failure({ url => $url }, 'http.invalid_url') unless $uri && $uri->scheme;
Branch: 1 branch
BranchTrueFalseTotal
unless $uri and $uri->scheme 1 58 59
Condition66%2/3
$uri and $uri->scheme
!ll&&!rl&&r
0158
MC/DC50%1/2
$uri and $uri->scheme
$uri $uri->scheme
Truth table66%2/3
A and B
A= $uriB= $uri->scheme
ABresult
0X0
100
111
420  
421 58 my $scheme = lc $uri->scheme;
422 return _failure({ url => $url }, 'http.unsupported_scheme', { scheme => $scheme })
423 58 ▶ unless exists $DEFAULT_PORT{$scheme};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $DEFAULT_PORT{$scheme} 2 56 58
424  
425 56 my $host = $uri->host;
426 56 ▶ return _failure({ url => $url }, 'http.no_host') unless defined $host && length $host;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host and length $host 1 55 56
Condition66%2/3
defined $host and length $host
!ll&&!rl&&r
0155
MC/DC50%1/2
defined $host and length $host
defined $host length $host
Truth table66%2/3
A and B
A= defined $hostB= length $host
ABresult
0X0
100
111
427  
428 55 ▶ my $port = $uri->port || $DEFAULT_PORT{$scheme};
Condition33%1/3
$uri->port || $DEFAULT_PORT{$scheme}
l!l&&r!l&&!r
5500
MC/DC0%0/2
$uri->port || $DEFAULT_PORT{$scheme}
$uri->port $DEFAULT_PORT{$scheme}
Truth table33%1/3
A || B
A= $uri->portB= $DEFAULT_PORT{$scheme}
ABresult
1X1
011
000
429  
430 # path_query is empty for "http://host"; the request line needs "/".
431 55 my $path = $uri->path_query;
432 55 ▶ $path = "/$path" unless $path =~ m{\A/};
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ m[\A/] 0 55 55
433  
434 return {
435 url => $url,
436 scheme => $scheme,
437 host => $host,
438 port => $port + 0,
439 path => $path,
440 55 ▶ host_header => $port == $DEFAULT_PORT{$scheme} ? $host : "$host:$port",
Branch: 1 branch
BranchTrueFalseTotal
$port == $DEFAULT_PORT{$scheme} ? : 0 55 55
441 };
442 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
443  
444 # _failure
445 # Purpose: a response hash describing an error.
446 # Entry: $context has at least 'url'; $key is a catalogue key.
447 # Exit: hashref with url, error and host/port when known.
448 # Side effects: none.
449 9 ▶sub _failure :Private
Subroutine _failure: called CC=2 SCAR=6.9
450 {
451 9 my ($context, $key, $args) = @_;
452  
453 9 my %failure = (url => $context->{url}, error => __PACKAGE__->i18n($key, $args));
454 9 $failure{$_} = $context->{$_} for grep { defined $context->{$_} } qw(host port);
455  
456 9 return \%failure;
457 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
458  
459 # _connect_error
460 # Purpose: why a connect failed.
461 # Entry: called straight after a failed _connect for $target.
462 # Exit: a non-empty string.
463 # Side effects: none.
464 4 ▶sub _connect_error :Private
Subroutine _connect_error: called CC=4 SCAR=16.1
465 {
466 4 my ($target) = @_;
467  
468 # Only an https connect can have a TLS error. For plain http,
469 # SSL_ERROR still holds whatever the last TLS failure was - on another
470 # host, minutes ago - and reporting it here was misleading.
471 4 ▶ my $tls_error = $target->{scheme} eq 'https' ? $IO::Socket::SSL::SSL_ERROR : undef;
Branch: 1 branch
BranchTrueFalseTotal
$target->{'scheme'} eq 'https' ? : 0 4 4
472  
473 4 ▶ return (defined $tls_error && length $tls_error) ? $tls_error : "$!";
Branch: 1 branch
BranchTrueFalseTotal
defined $tls_error && length $tls_error ? : 0 4 4
Condition33%1/3
defined $tls_error and length $tls_error
!ll&&!rl&&r
400
MC/DC0%0/2
defined $tls_error and length $tls_error
defined $tls_error length $tls_error
Truth table33%1/3
A and B
A= defined $tls_errorB= length $tls_error
ABresult
0X0
100
111
474 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
475  
476 # _exchange
477 # Purpose: send the request on an open socket and parse the reply.
478 # Entry: $sock is connected; $deadline is an absolute time.
479 # Exit: a response hashref (with 'error' on failure).
480 # Side effects: socket I/O. Does not close the socket.
481 51 ▶sub _exchange :Private
Subroutine _exchange: called CC=6 SCAR=18.0
482 {
483 51 my ($self, $sock, $target, $method, $extra, $deadline) = @_;
484  
485 51 my $request = $self->_request_text($target, $method, $extra);
486 51 ▶ return _failure($target, 'http.write_failed')
Branch: 1 branch
BranchTrueFalseTotal
unless _write_all($sock, $request, $deadline) 0 51 51
487 unless _write_all($sock, $request, $deadline);
488  
489 51 my ($head, $buffer) = $self->_read_head($sock, $deadline);
490 51 ▶ return _failure($target, 'http.no_headers') unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 51 51
491  
492 51 my $parsed = _parse_head($head);
493 51 ▶ return _failure($target, 'http.malformed_status') unless $parsed;
Branch: 1 branch
BranchTrueFalseTotal
unless $parsed 1 50 51
494  
495 50 my ($body, $truncated) = @{ $self->_read_body($sock, $deadline, \$buffer, $method, $parsed) };
496 50 my $headers = $parsed->{headers};
497  
498 return {
499 url => $target->{url},
500 host => lc $target->{host},
501 port => $target->{port},
502 scheme => $target->{scheme},
503 status => $parsed->{status},
504 reason => $parsed->{reason},
505 http_version => $parsed->{http_version},
506 headers => $headers,
507 set_cookie => $headers->{'set-cookie'} || [],
508 body => $body,
509 truncated => $truncated,
510 50 ▶ content_type => $headers->{'content-type'} ? $headers->{'content-type'}[0] : '',
Branch: 1 branch
BranchTrueFalseTotal
$headers->{'content-type'} ? : 23 27 50
Condition100%2/2
$headers->{'set-cookie'} || []
l!l
743
MC/DC100%1/1
$headers->{'set-cookie'} || []
$headers->{'set-cookie'}
Truth table100%2/2
A
A= $headers->{'set-cookie'}
Aresult
11
00
511 # The header block as it arrived, for reports that have to show it.
512 raw_headers => $head,
513 };
514 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
515  
516 # _request_text
517 # Purpose: the bytes of one HTTP/1.1 request.
518 # Entry: $method matches $METHOD_RE; $extra is an arrayref or undef.
519 # Exit: the request string, ending in a blank line.
520 # Side effects: none.
521 51 ▶sub _request_text :Private
Subroutine _request_text: called CC=3 SCAR=11.0
522 {
523 51 my ($self, $target, $method, $extra) = @_;
524  
525 my @lines = (
526 "$method $target->{path} HTTP/1.1",
527 "Host: $target->{host_header}",
528 "User-Agent: $self->{agent}",
529 204 map({ "$_: $DEFAULT_HEADERS{$_}" } sort keys %DEFAULT_HEADERS),
530 # A caller-supplied header with a line break could smuggle a
531 # second header or a second request, so it is dropped.
532 51 ▶ grep({ defined && !/[\r\n]/ } @{ $extra || [] }),
Condition80%4/5
defined $_ && !/[\r\n]/
!ll&&!rl&&r
017
$extra || []
l!l
744
MC/DC50%1/2
defined $_ && !/[\r\n]/
defined $_ !/[\r\n]/
MC/DC100%1/1
$extra || []
$extra
Truth table66%2/3
A && not(B)
A= defined $_B= !/[\r\n]/
ABresult
0X0
100
111
Truth table100%2/2
A
A= $extra
Aresult
11
00
533 );
534  
535 51 return join("\r\n", @lines) . "\r\n\r\n";
536 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
537  
538 # _read_head
539 # Purpose: read up to the end of the header block.
540 # Entry: $sock is readable; $deadline is absolute.
541 # Exit: (head, rest-of-buffer); head is undef on timeout, EOF or an
542 # oversized block.
543 # Side effects: socket reads.
544 51 ▶sub _read_head :Private
Subroutine _read_head: called CC=5 SCAR=16.7
545 {
546 51 my ($self, $sock, $deadline) = @_;
547  
548 51 my $buffer = '';
549 51 ▶ while($buffer !~ $HEADER_END) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($buffer =~ /$HEADER_END/) 51 51 102
550 51 ▶ return (undef, $buffer) if length($buffer) > $MAX_HEADER_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
if length $buffer > $MAX_HEADER_BYTES 0 51 51
551  
552 51 my $chunk = _read($sock, $deadline);
553 51 ▶ return (undef, $buffer) unless defined $chunk && length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk and length $chunk 0 51 51
Condition33%1/3
defined $chunk and length $chunk
!ll&&!rl&&r
0051
MC/DC0%0/2
defined $chunk and length $chunk
defined $chunk length $chunk
Truth table33%1/3
A and B
A= defined $chunkB= length $chunk
ABresult
0X0
100
111
554 51 $buffer .= $chunk;
555 }
556  
557 51 return split $HEADER_END, $buffer, 2;
558 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
559  
560 # _parse_head
561 # Purpose: parse a status line and header fields.
562 # Entry: $head is the header block without the terminating blank line.
563 # Exit: hashref of http_version, status, reason, headers; undef if
564 # the status line is not HTTP/1.x.
565 # Side effects: none.
566 53 ▶sub _parse_head :Private
Subroutine _parse_head: called CC=7 SCAR=19.5
567 {
568 53 my ($head) = @_;
569  
570 53 my @lines = split $LINE_END, $head;
571 53 ▶ my $status_line = shift(@lines) // '';
Condition50%1/2
shift @lines // ""
l!l
530
MC/DC0%0/1
shift @lines // ""
shift @lines
Truth table50%1/2
A
A= shift @lines
Aresult
11
00
572 53 my ($http_version, $status, $reason) = $status_line =~ m{\A(HTTP/\d\.\d)\s+(\d{3})\s*(.*)\z};
573 53 ▶ return unless defined $status;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status 2 51 53
574  
575 51 my (%headers, $last_name);
576 51 for my $line (@lines) {
577 # obs-fold: a continuation line belongs to the previous header.
578 155 ▶ if($line =~ /\A[ \t]+(.+)\z/ && defined $last_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A[ \t]+(.+)\z/ and defined $last_name) 1 154 155
Condition66%2/3
$line =~ /\A[ \t]+(.+)\z/ and defined $last_name
!ll&&!rl&&r
15401
MC/DC50%1/2
$line =~ /\A[ \t]+(.+)\z/ and defined $last_name
$line =~ /\A[ \t]+(.+)\z/ defined $last_name
Truth table66%2/3
A and B
A= $line =~ /\A[ \t]+(.+)\z/B= defined $last_name
ABresult
0X0
100
111
579 1 $headers{$last_name}[-1] .= " $1";
580 1 next;
581 }
582 # Copy the captures before the substitution below: a successful s///
583 # resets $2, which once lost the value of "Name : value" headers.
584 154 ▶ my ($name, $value) = $line =~ /\A([^:]+):[ \t]*(.*)\z/ or next;
Branch: 1 branch
BranchTrueFalseTotal
() = $line =~ /\A([^:]+):[ \t]*(.*)\z/ or next 153 1 154
585 153 ($name = lc $name) =~ s/[ \t]+\z//;
586 153 push @{ $headers{$name} }, $value;
587 153 $last_name = $name;
588 }
589  
590 return {
591 51 http_version => $http_version,
592 status => $status + 0,
593 reason => $reason,
594 headers => \%headers,
595 };
596 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
597  
598 # _read_body
599 # Purpose: read the body the way the headers describe it.
600 # Entry: $buffer_ref holds bytes already read past the header block.
601 # Exit: arrayref [body, truncated flag].
602 # Side effects: socket reads; consumes $$buffer_ref.
603 50 ▶sub _read_body :Private
Subroutine _read_body: called CC=9 SCAR=22.0
604 {
605 50 my ($self, $sock, $deadline, $buffer_ref, $method, $parsed) = @_;
606  
607 50 my $status = $parsed->{status};
608 50 my $headers = $parsed->{headers};
609  
610 # HEAD, 1xx, 204 and 304 never have a body, whatever the headers say.
611 50 ▶ return [ '', 0 ] if $method eq 'HEAD' || $status < 200 || $NO_BODY_STATUS{$status};
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "HEAD" or $status < 200 or $NO_BODY_STATUS{$status} 4 46 50
Condition83%5/6
$method eq "HEAD" or $status < 200 or $NO_BODY_STATUS{$status}
l!l&&r!l&&!r
1346
$method eq "HEAD" or $status < 200
l!l&&r!l&&!r
1049
MC/DC66%2/3
$method eq "HEAD" or $status < 200 or $NO_BODY_STATUS{$status}
$method eq "HEAD" $status < 200 $NO_BODY_STATUS{$status}
Truth table75%3/4
A or B or C
A= $method eq "HEAD"B= $status < 200C= $NO_BODY_STATUS{$status}
ABCresult
1XX1
01X1
0011
0000
612  
613 46 ▶ my $encoding = lc join ',', @{ $headers->{'transfer-encoding'} || [] };
Condition100%2/2
$headers->{'transfer-encoding'} || []
l!l
145
MC/DC100%1/1
$headers->{'transfer-encoding'} || []
$headers->{'transfer-encoding'}
Truth table100%2/2
A
A= $headers->{'transfer-encoding'}
Aresult
11
00
614 46 ▶ return $self->_read_chunked($sock, $deadline, $buffer_ref) if $encoding =~ /chunked/;
Branch: 1 branch
BranchTrueFalseTotal
if $encoding =~ /chunked/ 1 45 46
615  
616 45 ▶ my $length = $headers->{'content-length'} ? $headers->{'content-length'}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$headers->{'content-length'} ? : 44 1 45
617 45 ▶ return $self->_read_until($sock, $deadline, $buffer_ref, $length)
Branch: 1 branch
BranchTrueFalseTotal
if defined $length and $length =~ /\A\d+\z/ 44 1 45
Condition66%2/3
defined $length and $length =~ /\A\d+\z/
!ll&&!rl&&r
1044
MC/DC50%1/2
defined $length and $length =~ /\A\d+\z/
defined $length $length =~ /\A\d+\z/
Truth table66%2/3
A and B
A= defined $lengthB= $length =~ /\A\d+\z/
ABresult
0X0
100
111
618 if defined $length && $length =~ /\A\d+\z/;
619  
620 1 return $self->_read_until($sock, $deadline, $buffer_ref, undef);
621 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
622  
623 # _connect
624 # Purpose: open a TCP or TLS connection.
625 # Entry: $target from _target.
626 # Exit: the socket, or undef on failure ($! / SSL_ERROR set).
627 # Side effects: network connection.
628 55 ▶sub _connect :Private
Subroutine _connect: called CC=2 SCAR=7.0
629 {
630 55 my ($self, $target) = @_;
631  
632 my %common = (
633 PeerPort => $target->{port},
634 Timeout => $self->{timeout},
635 55 );
636  
637 # Verification failures are reported by App::WebPerimeterScan::TLS;
638 # here the response is still wanted so the other checks can run.
639 return IO::Socket::SSL->new(
640 %common,
641 PeerHost => $target->{host},
642 SSL_hostname => $target->{host},
643 SSL_verify_mode => SSL_VERIFY_NONE,
644 55 ▶ ) if $target->{scheme} eq 'https';
Branch: 1 branch
BranchTrueFalseTotal
if $target->{"scheme"} eq "https" 0 55 55
645  
646 55 return IO::Socket::INET->new(%common, PeerAddr => $target->{host}, Proto => 'tcp');
647 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
648  
649 # _throttle
650 # Purpose: keep at least 'delay' seconds between requests to one host.
651 # Entry: $host is the request's host.
652 # Exit: $self.
653 # Side effects: may sleep; records the time of this request.
654 55 ▶sub _throttle :Private
Subroutine _throttle: called CC=4 SCAR=13.9
655 {
656 55 my ($self, $host) = @_;
657  
658 55 my $last = $self->{last}{$host};
659 55 ▶ if($self->{delay} > 0 && defined $last) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"delay"} > 0 and defined $last) 1 54 55
Condition100%3/3
$self->{"delay"} > 0 and defined $last
!ll&&!rl&&r
5311
MC/DC100%2/2
$self->{"delay"} > 0 and defined $last
$self->{"delay"} > 0 defined $last
Truth table100%3/3
A and B
A= $self->{"delay"} > 0B= defined $last
ABresult
0X0
100
111
660 1 my $wait = $last + $self->{delay} - time;
661 1 ▶ sleep($wait) if $wait > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $wait > 0 1 0 1
662 }
663 55 $self->{last}{$host} = time;
664  
665 55 return $self;
666 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
667  
668 # _read
669 # Purpose: one bounded read.
670 # Entry: $sock open; $deadline absolute.
671 # Exit: the bytes read ('' at EOF), or undef on timeout or error.
672 # Side effects: socket read.
673 52 ▶sub _read :Private
Subroutine _read: called CC=4 SCAR=14.8
674 {
675 52 my ($sock, $deadline) = @_;
676  
677 52 my $wait = $deadline - time;
678 52 my $buffer;
679  
680 # undef stands for "nothing more will come": timed out or failed.
681 52 ▶ if($wait > 0 && IO::Select->new($sock)->can_read($wait)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wait > 0 and "IO::Select"->new($sock)->can_read($wait)) 52 0 52
Condition33%1/3
$wait > 0 and "IO::Select"->new($sock)->can_read($wait)
!ll&&!rl&&r
0052
MC/DC0%0/2
$wait > 0 and "IO::Select"->new($sock)->can_read($wait)
$wait > 0 "IO::Select"->new($sock)->can_read($wait)
Truth table33%1/3
A and B
A= $wait > 0B= "IO::Select"->new($sock)->can_read($wait)
ABresult
0X0
100
111
682 52 $buffer = '';
683 52 ▶ $buffer = undef unless defined sysread($sock, $buffer, $READ_SIZE);
Branch: 1 branch
BranchTrueFalseTotal
unless defined sysread($sock, $buffer, $READ_SIZE) 0 52 52
684 }
685  
686 52 return $buffer;
687 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
688  
689 # _write_all
690 # Purpose: write a whole string, waiting for the socket as needed.
691 # Entry: $sock open; $deadline absolute.
692 # Exit: 1 when everything was written, 0 on timeout or error.
693 # Side effects: socket writes.
694 51 ▶sub _write_all :Private
Subroutine _write_all: called CC=5 SCAR=16.6
695 {
696 51 my ($sock, $data, $deadline) = @_;
697  
698 51 my $offset = 0;
699 51 my $select = IO::Select->new($sock);
700  
701 51 ▶ while($offset < length $data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < length $data) 51 51 102
702 51 my $wait = $deadline - time;
703 51 ▶ return 0 if $wait <= 0 || !$select->can_write($wait);
Branch: 1 branch
BranchTrueFalseTotal
if $wait <= 0 or not $select->can_write($wait) 0 51 51
Condition33%1/3
$wait <= 0 or not $select->can_write($wait)
l!l&&r!l&&!r
0051
MC/DC0%0/2
$wait <= 0 or not $select->can_write($wait)
$wait <= 0 not $select->can_write($wait)
Truth table33%1/3
A or not(B)
A= $wait <= 0B= not $select->can_write($wait)
ABresult
1X1
011
000
704  
705 51 my $written = syswrite($sock, $data, length($data) - $offset, $offset);
706 51 ▶ return 0 unless defined $written;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $written 0 51 51
707 51 $offset += $written;
708 }
709  
710 51 return 1;
711 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
712  
713 # _read_until
714 # Purpose: read a body of known length, or to EOF when $length is undef,
715 # keeping at most max_size bytes.
716 # Entry: $buffer_ref holds bytes already read.
717 # Exit: arrayref [body, truncated flag].
718 # Side effects: socket reads; grows $$buffer_ref.
719 45 ▶sub _read_until :Private
Subroutine _read_until: called CC=9 SCAR=22.5
720 {
721 45 my ($self, $sock, $deadline, $buffer_ref, $length) = @_;
722  
723 45 my $max = $self->{max_size};
724 45 ▶ my $want = defined $length && $length < $max ? $length : $max;
Branch: 1 branch
BranchTrueFalseTotal
defined $length && $length < $max ? : 43 2 45
Condition100%3/3
defined $length and $length < $max
!ll&&!rl&&r
1143
MC/DC100%2/2
defined $length and $length < $max
defined $length $length < $max
Truth table100%3/3
A and B
A= defined $lengthB= $length < $max
ABresult
0X0
100
111
725  
726 45 ▶ while(length($$buffer_ref) < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$buffer_ref < $want) 1 44 45
727 1 my $chunk = _read($sock, $deadline);
728 1 ▶ last unless defined $chunk && length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk and length $chunk 1 0 1
Condition33%1/3
defined $chunk and length $chunk
!ll&&!rl&&r
010
MC/DC0%0/2
defined $chunk and length $chunk
defined $chunk length $chunk
Truth table33%1/3
A and B
A= defined $chunkB= length $chunk
ABresult
0X0
100
111
729 0 $$buffer_ref .= $chunk;
730 }
731  
732 # Truncated means bytes were left behind: a declared length beyond the
733 # cap, or an unbounded body that reached it.
734 45 ▶ my $truncated = defined $length ? ($length > $max ? 1 : 0) : (length($$buffer_ref) >= $max ? 1 : 0);
Branch: 3 branches
BranchTrueFalseTotal
defined $length ? : 44 1 45
$length > $max ? : 1 43 44
length $$buffer_ref >= $max ? : 0 1 1
735  
736 45 return [ substr($$buffer_ref, 0, $want), $truncated ];
737 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
738  
739 # _read_line
740 # Purpose: one CRLF- or LF-terminated line, for chunked framing.
741 # Entry: $buffer_ref holds bytes already read.
742 # Exit: the line without its terminator, or undef on EOF/timeout.
743 # Side effects: socket reads; removes the line from $$buffer_ref.
744 5 ▶sub _read_line :Private
Subroutine _read_line: called CC=5 SCAR=19.4
745 {
746 5 my ($sock, $deadline, $buffer_ref) = @_;
747  
748 # Keep reading until a line ending arrives or the peer stops sending;
749 # a partial line at EOF does not match below and so yields undef.
750 5 my $chunk = '';
751 5 ▶ $$buffer_ref .= $chunk
Branch: 1 branch
BranchTrueFalseTotal
not $$buffer_ref =~ /$LINE_END/ and defined($chunk = _read($sock, $deadline)) and length $chunk and do { $$buffer_ref .= $chunk } 0 5 5
Condition33%2/6
not $$buffer_ref =~ /$LINE_END/ and defined($chunk = _read($sock, $deadline)) and length $chunk
!ll&&!rl&&r
500
not $$buffer_ref =~ /$LINE_END/ and defined($chunk = _read($sock, $deadline))
!ll&&!rl&&r
500
MC/DC0%0/3
not $$buffer_ref =~ /$LINE_END/ and defined($chunk = _read($sock, $deadline)) and length $chunk
not $$buffer_ref =~ /$LINE_END/ defined($chunk = _read($sock, $deadline)) length $chunk
Truth table25%1/4
not(A) and B and C
A= not $$buffer_ref =~ /$LINE_END/B= defined($chunk = _read($sock, $deadline))C= length $chunk
ABCresult
0XX0
10X0
1100
1111
752 while $$buffer_ref !~ $LINE_END
753 && defined($chunk = _read($sock, $deadline)) && length $chunk;
754  
755 5 ▶ return $$buffer_ref =~ s/\A(.*?)$LINE_END//s ? $1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$$buffer_ref =~ s/\A(.*?)$LINE_END//s ? : 5 0 5
756 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
757  
758 # _read_chunked
759 # Purpose: decode a chunked body (RFC 9112 7.1), keeping max_size bytes.
760 # Entry: $buffer_ref holds bytes already read past the headers.
761 # Exit: arrayref [body, truncated flag].
762 # Side effects: socket reads; consumes $$buffer_ref.
763 #
764 # Each chunk is "<hex size>[;ext]\r\n<data>\r\n"; a zero size ends the body
765 # and is followed by optional trailers and a blank line. Anything that does
766 # not parse ends the body early rather than guessing.
767 1 ▶sub _read_chunked :Private
Subroutine _read_chunked: called CC=11 SCAR=27.8
768 {
769 1 my ($self, $sock, $deadline, $buffer_ref) = @_;
770  
771 1 my $body = '';
772 1 ▶ while(defined(my $line = _read_line($sock, $deadline, $buffer_ref))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = _read_line($sock, $deadline, $buffer_ref))) 3 0 3
773 3 $line =~ s/;.*//; # chunk extensions are ignored
774 3 $line =~ s/\s+//g;
775 3 ▶ last unless $line =~ /\A[0-9a-fA-F]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\A[0-9a-fA-F]+\z/ 0 3 3
776  
777 3 my $size = hex $line;
778 3 ▶ if($size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($size == 0) 1 2 3
779 # Trailers, up to the blank line, are read and discarded.
780 1 ▶ 1 while length(_read_line($sock, $deadline, $buffer_ref) // '');
Branch: 1 branch
BranchTrueFalseTotal
length(_read_line($sock, $deadline, $buffer_ref) // "") and do { '???' } 1 1 2
Condition50%1/2
_read_line($sock, $deadline, $buffer_ref) // ""
l!l
20
MC/DC0%0/1
_read_line($sock, $deadline, $buffer_ref) // ""
_read_line($sock, $deadline, $buffer_ref)
Truth table50%1/2
A
A= _read_line($sock, $deadline, $buffer_ref)
Aresult
11
00
781 1 last;
782 }
783  
784 # The data plus its CRLF.
785 2 ▶ while(length($$buffer_ref) < $size + 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$buffer_ref < $size + 2) 0 2 2
786 0 my $chunk = _read($sock, $deadline);
787 0 ▶ last unless defined $chunk && length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk and length $chunk 0 0 0
Condition0%0/3
defined $chunk and length $chunk
!ll&&!rl&&r
000
MC/DC0%0/2
defined $chunk and length $chunk
defined $chunk length $chunk
Truth table0%0/3
A and B
A= defined $chunkB= length $chunk
ABresult
0X0
100
111
788 0 $$buffer_ref .= $chunk;
789 }
790 2 ▶ last if length($$buffer_ref) < $size;
Branch: 1 branch
BranchTrueFalseTotal
if length $$buffer_ref < $size 0 2 2
791  
792 2 $body .= substr($$buffer_ref, 0, $size, '');
793 2 $$buffer_ref =~ s/\A$LINE_END//;
794  
795 2 ▶ return [ substr($body, 0, $self->{max_size}), 1 ] if length($body) > $self->{max_size};
Branch: 1 branch
BranchTrueFalseTotal
if length $body > $self->{"max_size"} 0 2 2
796 }
797  
798 1 return [ $body, 0 ];
799 29 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
800  
801 29 1;
802  
803 __END__
« lib/App/WebPerimeterScan/Report.pm ↑ Summary lib/App/WebPerimeterScan/I18N.pm »