Inspect/L7/HTTP/Request/InspectChain.pm untested

filter: Statementstmt 0.0% 0 / 408 Branchbran 0.0% 0 / 172 Conditioncond 0.0% 0 / 110 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 756 CC 87 SCAR 52.7
CC
87
Cov
0%
_rpbody_uncompress_gzip
756.0
in_response_body
132.0
in_request_body
110.0
CRAP 195.4
1 ############################################################################
2 # deep inspection into HTTP response
3 # umcompresses, updates response header and provides hooks to manipulate
4 # request and response header and body
5 ############################################################################
6  
7 use strict;
8 use warnings;
9 package Net::Inspect::L7::HTTP::Request::InspectChain;
10 use base 'Net::Inspect::Flow';
11 use fields qw(conn meta rqhdr rphdr hooks info);
12 use Hash::Util 'lock_keys';
13 use Carp;
14 use HTTP::Request;
15 use HTTP::Response;
16 use Compress::Raw::Zlib;
17 use Net::Inspect::Debug qw(debug trace $DEBUG);
18 use Scalar::Util 'weaken';
19  
20 my ($can_brotli,$ce_rx);
21 BEGIN {
22 if (eval { require IO::Uncompress::Brotli; 1 }) {
23 $can_brotli = 1;
24 $ce_rx = qr{(?:x-)(?<ce> gzip|deflate) | (?<ce> br)}xi;
25 } else {
26 $can_brotli = 0;
27 $ce_rx = qr{(?:x-)(?<ce> gzip|deflate)}xi;
28 }
29 }
30  
31 ############################################################################
32 # creation of object, adding hooks etc
33 ############################################################################
34  
35 # initialize or clone hooks on creation
36 sub new {
37 my $class = shift;
38 my $self = $class->SUPER::new(@_);
39 my %hooks;
40 if ( ! ref($class)) {
41 %hooks = (
42 request_header => undef,
43 request_body => undef,
44 response_header => undef,
45 response_body => undef,
46 chunk_header => undef,
47 chunk_trailer => undef,
48 );
49 } else {
50 # clone hooks
51 while ( my ($k,$v) = each %{ $class->{hooks} } ) {
52 if ( ! $v ) {
53 $hooks{$k} = $v
54 } else {
55 $hooks{$k} = [ map { [ @$_ ] } @$v ];
56 }
57 }
58 }
59  
60 lock_keys(%hooks);
61 $self->{hooks} = \%hooks;
62 return $self;
63 }
64  
65 # create new request, set conn to connection of request so we can
66 # better react when fatal
67 {
68 sub new_request {
69 my ($self,$meta,$conn) = @_;
70 my $obj = $self->new;
71 if ($obj->{upper_flow}) {
72 $obj->{upper_flow} = $obj->{upper_flow}->new_request($meta)
73 or return;
74 }
75 weaken($obj->{conn} = $conn);
76 $obj->{meta} = $meta;
77 return $obj;
78 }
79 }
80  
81 # forward fatal to connection
82 sub fatal {
83 my ($self,$reason,$dir,$time) = @_;
84 return $self->{conn}->fatal($self->{meta}{reqid}.' '.$reason,$dir,$time);
85 }
86  
87 sub xdebug {
88 $DEBUG or return;
89 my $self = shift;
90 my $msg = shift;
91 $msg = "$$.$self->{conn}{connid}.$self->{meta}{reqid} $msg";
92 unshift @_,$msg;
93 goto &debug;
94 }
95  
96 sub xtrace {
97 my $self = shift;
98 my $msg = shift;
99 $msg = "$$.$self->{conn}{connid}.$self->{meta}{reqid} $msg";
100 unshift @_,$msg;
101 goto &trace;
102 }
103  
104 # for logging
105 sub id {
106 my $self = shift;
107 return "$$.$self->{conn}{connid}.$self->{meta}{reqid}";
108 }
109  
110 # add inspection hook
111 my %predefined_hooks = (
112 'uncompress_ce' => {
113 request_header => \&_rqhdr_uncompress_ce,
114 response_header => \&_rphdr_uncompress_ce,
115 response_body => undef, # reserve place
116 },
117 'uncompress_te' => {
118 response_header => \&_rphdr_uncompress_te,
119 response_body => undef, # reserve place
120 },
121 'unchunk' => {
122 response_header => \&_rphdr_unchunk,
123 chunk_header => undef,
124 chunk_trailer => undef,
125 },
126 );
127 sub add_hooks {
128 my ($self,@hooks) = @_;
129 my ($pos,%wpos,%opt);
130 for( my $i=0;$i<@hooks;$i++) {
131 my ($hook,$name);
132 if ( ref($hooks[$i]) ) {
133 $hook = $hooks[$i];
134 } elsif ( $hooks[$i] =~ m{^(\d+)$} ) {
135 $pos = $1;
136 %wpos = ();
137 next;
138 } elsif ( $hooks[$i] =~ m{^-[\w_-]+$} ) {
139 # option with value
140 $opt{$hooks[$i]} = $hooks[$i+1];
141 $i++;
142 next;
143 } else {
144 $hook = $predefined_hooks{$hooks[$i]}
145 or croak "no predefined hook $hooks[$i]";
146 $name = $hooks[$i]
147 }
148 $name ||= $hook->{name};
149 while (my ($where,$cb) = each %$hook) {
150 $where eq 'name' and next;
151 my @c = caller(0);
152 my $h = $self->{hooks}{$where}||= [];
153 if ( ! defined $wpos{$where} ) {
154 $wpos{$where} = defined($pos) && $pos < @$h ? $pos : @$h;
155 }
156 splice(@$h,$wpos{$where},0, [
157 $name,
158 '',
159 ! $cb ? undef: (ref($cb) eq 'CODE') ? $cb : @$cb,
160 %opt,
161 ]);
162 $wpos{$where}++;
163 }
164 }
165 }
166  
167 sub update_hook {
168 my ($self,$name,$hook,%opt) = @_;
169 while (my ($where,$cb) = each %$hook) {
170 $where eq 'name' and next;
171 my $wh = $self->{hooks}{$where} or next;
172 my $found;
173 for(@$wh) {
174 $_->[0] eq $name or next;
175 @$_ = (
176 $name,
177 $_->[1],
178 ! $cb ? undef : (ref($cb) eq 'CODE') ? $cb : @$cb,
179 %opt,
180 );
181 $found = 1;
182 last;
183 }
184 die "no hook $name found for $where" if ! $found;
185 }
186 }
187  
188  
189 ############################################################################
190 # helper for hooks
191 ############################################################################
192  
193 # returns request header as HTTP::Request
194 # can also be used to set header
195 sub request_header {
196 my $self = shift;
197 $self->{rqhdr} = shift if @_;
198 my $hdr = $self->{rqhdr} or croak("no request header known");
199 if ( ! ref($hdr)) {
200 $hdr = eval { HTTP::Request->parse($hdr) }
201 or return $self->fatal("cannot parse HTTP header: $@");
202 $self->{rqhdr} = $hdr;
203 }
204 return $hdr;
205 }
206  
207 # returns response header as HTTP::Response
208 # can also be used to set header
209 sub response_header {
210 my $self = shift;
211 $self->{rphdr} = shift if @_;
212 my $hdr = $self->{rphdr} or croak("no response header known");
213 if ( ! ref($hdr)) {
214 $hdr = eval { HTTP::Response->parse($hdr) }
215 or return $self->fatal("cannot parse HTTP header: $@");
216 $self->{rphdr} = $hdr;
217 }
218 return $hdr;
219 }
220  
221 ############################################################################
222 # redefined in_* methods which apply hooks before calling original method
223 ############################################################################
224  
225 sub in_data {
226 my ($self,$dir,$data,$eof,$time) = @_;
227 # will ignore all SSL, Websockets... stuff for now
228 return length($data);
229 }
230  
231 sub in_request_header {
232 my ($self,$data,$time) = @_;
233 $self->{rqhdr} = $data;
234 if ( my $hooks = $self->{hooks}{request_header} ) {
235 # hooks might be dynamically added inside a previous hook
236 for(my $i=0;$i<@$hooks;$i++) {
237 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
238 $sub or next;
239 my $changed = $sub->($self,\$data,$time,@arg);
240 defined $changed or return;
241 $self->{rqhdr} = $data if $changed; # re-parse
242 }
243 }
244 return $self->{upper_flow}->in_request_header($data,$time)
245 if $self->{upper_flow};
246 return 1;
247 }
248  
249 sub in_response_header {
250 my ($self,$data,$time) = @_;
251 $self->{rphdr} = $data;
252 if ( my $hooks = $self->{hooks}{response_header} ) {
253 # hooks might be dynamically added inside a previous hook
254 for(my $i=0;$i<@$hooks;$i++) {
255 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
256 $sub or next;
257 my $changed = $sub->($self,\$data,$time,@arg);
258 defined $changed or return;
259 $self->{rphdr} = $data if $changed; # re-parse
260 }
261 }
262 return $self->{upper_flow}->in_response_header($data,$time)
263 if $self->{upper_flow};
264 return 1;
265 }
266  
267 sub in_request_body {
268 my ($self,$data,$eof,$time) = @_;
269 croak "gaps not supported in_request_body" if ref($data);
270 my $bytes = length($data);
271 my $hooks = $self->{hooks}{request_body};
272 my $lasthook;
273 if ( $hooks ) {
274 $self->xdebug("got hooks");
275 # hooks might be dynamically added inside a previous hook
276 my $ref = \$data;
277 for(my $i=0;$i<@$hooks;$i++) {
278 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
279 $sub or next;
280 my $processed = $sub->($self,$ref,$eof,$time,@arg);
281 $bytes -= length($$ref) if $i == 0;
282 defined $processed or return;
283 $hooks->[$i][1].= $processed;
284 $ref = \$hooks->[$i][1];
285 $lasthook = $i;
286 }
287 $data = $$ref if defined $lasthook;
288 } else {
289 $self->xdebug("no hooks");
290 }
291 my $n = $self->{upper_flow} ?
292 $self->{upper_flow}->in_request_body($data,$eof,$time) : -1;
293 if ( defined $lasthook ) {
294 if (!$n) {
295 } elsif ($n<0) {
296 $hooks->[$lasthook][1] = '';
297 } else {
298 substr($hooks->[$lasthook][1],0,$n,'');
299 }
300 if ( $eof && grep { $_->[1] ne '' } @$hooks ) {
301 die "out-buffer in hook not empty at in_request_body(eof)";
302 }
303 return $bytes;
304 }
305 return $n;
306 }
307  
308 sub in_response_body {
309 my ($self,$data,$eof,$time) = @_;
310 croak "gaps not supported in_response_body" if ref($data);
311 my $bytes = length($data);
312 my $hooks = $self->{hooks}{response_body};
313 my $lasthook;
314 if ( $hooks ) {
315 # hooks might be dynamically added inside a previous hook
316 my $ref = \$data;
317 for(my $i=0;$i<@$hooks;$i++) {
318 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
319 $sub or next;
320 my $processed = $sub->($self,$ref,$eof,$time,@arg);
321 $bytes -= length($$ref) if $i == 0;
322 defined $processed or return;
323 $hooks->[$i][1].= $processed;
324 $ref = \$hooks->[$i][1];
325 $lasthook = $i;
326 }
327 $data = $$ref if defined $lasthook;
328 }
329 my $n = $self->{upper_flow} ?
330 $self->{upper_flow}->in_response_body($data,$eof,$time) : -1;
331 if ( defined $lasthook ) {
332 if (!$n) {
333 } elsif ($n<0) {
334 $hooks->[$lasthook][1] = '';
335 } else {
336 substr($hooks->[$lasthook][1],0,$n,'') if $n;
337 }
338 if ( $eof && grep { $_->[1] ne '' } @$hooks ) {
339 die "out-buffer in hook not empty at in_response_body(eof)".Dumper($self); use Data::Dumper;
340 }
341 return $bytes;
342 }
343 return $n;
344 }
345  
346 sub in_chunk_header {
347 my ($self,$dir,$data,$time) = @_;
348 my $bytes = length($data);
349 if ( my $hooks = $self->{hooks}{chunk_header} ) {
350 # hooks might be dynamically added inside a previous hook
351 for(my $i=0;$i<@$hooks;$i++) {
352 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
353 $sub or next;
354 defined $sub->($self,$dir,\$data,$time,@arg) or return;
355 $data eq '' and return $bytes;
356 }
357 }
358 $self->{upper_flow}->in_chunk_header($dir,$data,$time)
359 if $self->{upper_flow};
360 return $bytes;
361 }
362  
363 sub in_chunk_trailer {
364 my ($self,$dir,$data,$time) = @_;
365 my $bytes = length($data);
366 if ( my $hooks = $self->{hooks}{chunk_trailer} ) {
367 # hooks might be dynamically added inside a previous hook
368 for(my $i=0;$i<@$hooks;$i++) {
369 my (undef,undef,$sub,@arg) = @{ $hooks->[$i] };
370 $sub or next;
371 defined $sub->($self,$dir,\$data,$time,@arg) or return;
372 $data eq '' and return $bytes;
373 }
374 }
375 $self->{upper_flow}->in_chunk_trailer($dir,$data,$time)
376 if $self->{upper_flow};
377 return $bytes;
378 }
379  
380 ############################################################################
381 # Builtin named hooks
382 ############################################################################
383 ############################################################################
384 # 'unchunk' hook
385 # removes 'chunked' from response header and ignores chunk framing
386 ############################################################################
387 sub _rphdr_unchunk {
388 my ($self,$hdr_ref,$time,%opt) = @_;
389 my $hdr = $self->response_header;
390  
391 # remove chunked from Transfer-Encoding
392 my $ote = my $te = $hdr->header('Transfer-Encoding') or return 0;
393 $te =~s{\s*\bchunked\b\s*}{}i or return 0;
394 if ( $te ne '' ) {
395 $hdr->header('Transfer-Encoding' => $te);
396 } else {
397 $hdr->remove_header('Transfer-Encoding');
398 }
399 if ( my $prefix = $opt{'-original-header-prefix'} ) {
400 $hdr->push_header( $prefix.'Transfer-Encoding' => $ote)
401 }
402  
403 $$hdr_ref = $hdr->as_string;
404  
405 my $ignore = sub {
406 my ($self,$dir,$data_ref) = @_;
407 $$data_ref = '';
408 return 1;
409 };
410 $self->update_hook('unchunk',{
411 chunk_trailer => $ignore,
412 chunk_header => $ignore,
413 });
414  
415 $self->{info}{chunked}++;
416 return 1;
417 }
418  
419 ############################################################################
420 # 'uncompress_ce' and 'uncompress_te' hooks
421 # Handling of compressed content
422 # the hook _rphdr_uncompress_* is added to respone_header and if it finds
423 # a matching content-encoding/transfer_encoding it will remove it and add
424 # _rpbody_uncompress_* as a hook for response_body
425 # To make sure we can decompress we have to either prohibit range requests
426 # or prohibit compression if Range request occured.
427 # This is done in _rqhdr_uncompress_ce
428 #
429 # We might actually have the content compressed twice: transfer-encoding
430 # and content-encoding. Does not make much sense, but there are a lot of
431 # nonsense responses out there
432 #
433 # Browser handling of transfer-encoding: gzip etc is ambiguous,
434 # they mostly ignore the header (MSIE, Chrome, FF) but some support it
435 # (Opera, rekonq, konqueror)
436 ############################################################################
437 sub _rphdr_uncompress_ce {
438 my ($self,$hdr_ref,$time,%opt) = @_;
439 my $hdr = $self->response_header;
440 my $oce = my $ce = $hdr->header('Content-Encoding') or return 0;
441 my $lce = $ce =~s{\s*\b$ce_rx\b\s*}{} && lc($+{ce}) or return 0;
442 $self->{info}{"ce_$lce"}++;
443 if (my $sub = UNIVERSAL::can(__PACKAGE__,'_rpbody_uncompress_'.$lce)) {
444 $self->update_hook('uncompress_ce',{
445 response_body => [$sub,{ typ => $lce }]
446 });
447 } else {
448 croak("no handler to $lce content-encoding");
449 }
450  
451 if ( $hdr->header('Content-Range')) {
452 # should not happen, we blocked it!
453 $self->fatal('got content-range header with compression',1,$time);
454 return;
455 }
456 if ( $ce ne '' ) {
457 $hdr->header('Content-Encoding' => $ce);
458 } else {
459 $hdr->remove_header('Content-Encoding');
460 }
461 my $prefix = $opt{'-original-header-prefix'};
462 $hdr->push_header( $prefix.'Content-Encoding' => $oce) if $prefix;
463  
464 # Content-length changes so it needs to be removed
465 if ( my @l = $hdr->remove_header('Content-length') and $prefix) {
466 $hdr->push_header( $prefix.'Content-Length' => $_) for @l;
467 }
468  
469 # the MD5 over the content changes too
470 if ( my @m = $hdr->remove_header('Content-MD5') and $prefix ) {
471 $hdr->push_header( $prefix.'Content-MD5' => $_) for @m;
472 }
473  
474 # update header string
475 $$hdr_ref = $hdr->as_string;
476  
477 return 1;
478 }
479  
480 sub _rphdr_uncompress_te {
481 my ($self,$hdr_ref,$time,%opt) = @_;
482 my $hdr = $self->response_header;
483 my $ote = my $te = $hdr->header('Transfer-Encoding') or return 0;
484 my $lce = $te =~s{\s*\b$ce_rx\b\s*}{} && lc($+{ce}) or return 0;
485 $self->{info}{"te_$lce"}++;
486 if (my $sub = UNIVERSAL::can('_rpbody_uncompress_'.$lce)) {
487 $self->update_hook('uncompress_te',{
488 response_body => [$sub,{ typ => $lce }]
489 });
490 } else {
491 croak("no handler to $lce transfer-encoding");
492 }
493 if ( $te ne '' ) {
494 $hdr->header('Transfer-Encoding' => $te);
495 } else {
496 $hdr->remove_header('Transfer-Encoding');
497 }
498  
499 my $prefix = $opt{'-original-header-prefix'};
500 $hdr->push_header( $prefix.'Transfer-Encoding' => $ote) if $prefix;
501  
502 # Content-length changes so it needs to be removed
503 if ( my @l = $hdr->remove_header('Content-length') and $prefix) {
504 $hdr->push_header( $prefix.'Content-Length' => $_) for @l;
505 }
506  
507 # update header string
508 $$hdr_ref = $hdr->as_string;
509 return 1;
510 }
511  
512 sub _rqhdr_uncompress_ce {
513 my ($self,$hdr_ref) = @_;
514 my $hdr = $self->request_header;
515 $hdr->header('Range') or return 0;
516 # on range header remove compression from supported content-encodings
517 # unfortunatly some server switch on compression anyways because of
518 # user-agent :(
519 $hdr->header('Accept-Encoding' => 'identity');
520 $$hdr_ref = $hdr->as_string;
521 return 1;
522 }
523  
524 sub _rpbody_uncompress_gzip {
525 my ($self,$data_ref,$eof,$time,$zlib) = @_;
526 if ( ! $zlib->{inflate} ) {
527 # initialisation
528  
529 my $wb;
530 if ( $zlib->{typ} eq 'gzip' ) {
531 # remove GZip header first
532 my $len = length($$data_ref);
533 my $hdr = 10; # minimum header length
534 return $eof ? undef: '' if $len < $hdr;
535  
536 my ($magic,$method,$flags) = unpack( 'vCC',$$data_ref );
537 if ( $magic != 0x8b1f or $method != Z_DEFLATED or $flags & 0xe0 ) {
538 trace("error decoding content-encoding gzip - bad gzip header");
539 $zlib->{inflate} =
540 Net::Inspect::L7::HTTP::Request::InspectChain::_IgnoreBadGzip->new;
541 goto bad_gzip;
542 }
543 if ( $flags & 4 ) {
544 # skip extra
545 return 0 if $len < ( $hdr+=2 );
546 $hdr+= unpack( 'x10v',$$data_ref );
547 return $eof ? undef: '' if $len < $hdr;
548 }
549 if ( $flags & 8 ) {
550 # skip file name
551 my $o = index( $$data_ref,"\0",$hdr );
552 return $eof ? undef: '' if $o == -1; # file name end not found
553 $hdr = $o+1;
554 }
555 if ( $flags & 16 ) {
556 # skip comment
557 my $o = index( $$data_ref,"\0",$hdr );
558 return $eof ? undef: '' if $o == -1; # comment end not found
559 $hdr = $o+1;
560 }
561 if ( $flags & 2 ) {
562 # skip CRC
563 return $eof ? undef: '' if $len < ( $hdr+=2 );
564 }
565 # remove header
566 substr( $$data_ref,0,$hdr,'' );
567 $self->xdebug( "removed gzip header of $hdr bytes" );
568  
569 $zlib->{gzip_csum} = 8; # 8 byte adler32 at end
570 $wb = -MAX_WBITS(); # see Compress::Raw::Zlib
571  
572 } else {
573 # deflate
574 # lets see if it looks like a zlib header
575 # check for CM=8, CMID<=7 in first byte and valid FCHECK in
576 # seconds byte
577 return $eof ? undef: '' if length($$data_ref)<2;
578  
579 my $byte = unpack( "C", substr($$data_ref,0,1));
580 if (
581 ( $byte & 0b1111 ) == 8 # CM = 8
582 and $byte >> 4 <= 7 # CMID <=7
583 and unpack( 'n',substr($$data_ref,0,2)) % 31 == 0 # valid FCHECK
584 ) {
585 # could be zlib header
586 $self->xdebug( "looks like zlib" );
587 $wb = +MAX_WBITS(); # see Compress::Raw::Zlib
588 } else {
589 # raw deflate
590 $self->xdebug( "no zlib, assume raw deflate" );
591 $wb = -MAX_WBITS(); # see Compress::Raw::Zlib
592 }
593 }
594 $zlib->{inflate} = Compress::Raw::Zlib::Inflate->new(
595 -WindowBits => $wb,
596 -AppendOutput => 1,
597 -ConsumeInput => 1
598 ) or die "cannot create inflation stream";
599  
600 bad_gzip:
601 1;
602 }
603  
604 return '' if $$data_ref eq '';
605  
606 my $data = '';
607 my $stat = $zlib->{inflate}->inflate( $data_ref,\$data );
608 if ( $stat == Z_STREAM_END ) {
609 if ( $zlib->{gzip_csum} ) {
610 # TODO - check checksum?
611 return '' if length($$data_ref)<8;
612 substr($$data_ref,0,8,'');
613 $zlib->{gzip_csum} = 0;
614 }
615 } elsif ( $stat != Z_OK ) {
616 $self->fatal("bad status $stat while inflating stream",1,$time);
617 return;
618 }
619 return $data
620 }
621 *_rpbody_uncompress_deflate = \&_rpbody_uncompress_gzip;
622  
623 {
624 # fake inflater to handle invalid gzip as plain text
625 # some server send Content-type: gzip with plain data when confronted
626 # with a request for identity :(
627 package Net::Inspect::L7::HTTP::Request::InspectChain::_IgnoreBadGzip;
628 use Compress::Raw::Zlib;
629 sub new { return bless {},shift };
630 sub inflate {
631 my ($self,$in,$out) = @_;
632 return Z_STREAM_END if $$in eq '';
633 $$out .= $$in;
634 $$in = '';
635 return Z_OK;
636 }
637 }
638  
639  
640 sub _rpbody_uncompress_br {
641 my ($self,$data_ref,$eof,$time,$state) = @_;
642 my $br = $state->{br} ||= IO::Uncompress::Brotli->create;
643 my $data = $br->decompress($$data_ref);
644 $$data_ref = '';
645 return $data;
646 }
647  
648  
649  
650 1;
651 __END__