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

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