HTTP_Proxy_IMP.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« HTTP_Proxy_IMP/IMP/Example/changeTarget.pm ↑ Summary HTTP_Proxy_IMP/IMP.pm »
1  
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 package App::HTTP_Proxy_IMP;
6 1 ▶use fields qw(addr impns filter pcapdir mitm_ca capath no_check_certificate);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use App::HTTP_Proxy_IMP::IMP '$IMP_MAX_IN_ANALYZER';
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use App::HTTP_Proxy_IMP::Conn;
10 use App::HTTP_Proxy_IMP::Request;
11 use App::HTTP_Proxy_IMP::Relay;
12 use AnyEvent;
13 use Getopt::Long qw(:config posix_default bundling);
14 use App::HTTP_Proxy_IMP::Debug ();
15 use Net::IMP::Debug qw(debug $DEBUG $DEBUG_RX);
16 use Net::Inspect::Debug qw(%TRACE);
17 use IO::Socket::SSL::Intercept;
18 use IO::Socket::SSL::Utils;
19 use Carp 'croak';
20  
21 our $VERSION = '0.945_001';
22  
23 # try IPv6 using IO::Socket::IP or IO::Socket::INET6
24 # fallback to IPv4 only
25 my $sockclass;
26 BEGIN {
27 for(qw( IO::Socket::IP IO::Socket::INET6 IO::Socket::INET )) {
28 if ( eval "require $_" ) {
29 $sockclass = $_;
30 last;
31 }
32 }
33 $sockclass or die "cannot find usable socket class";
34 }
35  
36  
37 sub new {
38 my ($class,@args) = @_;
39 my $self = fields::new($class);
40 $self->{impns} = [qw(App::HTTP_Proxy_IMP::IMP Net::IMP::HTTP Net::IMP)];
41 %$self = ( %$self, %{ shift(@args) }) if @args && ref($args[0]);
42 $self->getoptions(@args) if @args;
43 return $self;
44 }
45  
46 sub start {
47 my $self = shift;
48 $self = $self->new(@_) or return if ! ref($self); # package->start
49  
50 my $pcapdir = $self->{pcapdir};
51 if ( $pcapdir ) {
52 croak("pcap directory not writeable") unless -d $pcapdir && -w _;
53 eval { require Net::PcapWriter } or croak(
54 "cannot load Net::PcapWriter, which is needed with --pcapdir option");
55 }
56  
57 my $mitm;
58 if ( my $f = $self->{mitm_ca} ) {
59 my $serial = 1;
60 my $cache = {};
61 my $cachedir = "$f.cache";
62 if ( -d $cachedir || mkdir($cachedir,0700)) {
63 for my $f (glob("$cachedir/*.pem")) {
64 -f $f && -r _ && -s _ or next;
65 my $time = (stat(_))[9];
66 my $key = PEM_file2key($f) or next;
67 my $cert = PEM_file2cert($f) or next;
68 my $sn = CERT_asHash($cert)->{serial};
69 $serial = $sn+1 if $sn>=$serial;
70 my ($id) = $f=~m{/([^/]+)\.pem$};
71 $cache->{$id} = {
72 cert => $cert,
73 key => $key,
74 atime => $time,
75 };
76 debug("loaded certificate id=$id from cache");
77 }
78  
79 my $cache_hash = $cache;
80 $cache = sub {
81 my $id = shift;
82 my $e;
83 if ( ! @_ ){ # get
84 $e = $cache_hash->{$id} or return;
85 } else {
86 my ($cert,$key) = @_;
87 $e = $cache_hash->{$id} = {
88 cert => $cert,
89 key => $key,
90 };
91 }
92 my $f = "$cachedir/$id.pem";
93 if ( @_ || ! -f $f and open( my $fh,">",$f )) {
94 debug("save mitm certificate and key to $cachedir/$id.pem");
95 print $fh PEM_cert2string($e->{cert}),
96 PEM_key2string($e->{key})
97 } else {
98 utime(undef,undef,$f);
99 }
100 $e->{atime} = time();
101 return ($e->{cert},$e->{key});
102 };
103 }
104  
105 $mitm = IO::Socket::SSL::Intercept->new(
106 proxy_cert_file => $f,
107 proxy_key_file => $f,
108 cache => $cache,
109 serial => $serial,
110 );
111 }
112  
113 my $imp_factory;
114 my $filter = $self->{filter};
115 if ($filter && @$filter ) {
116 my $ns = $self->{impns};
117 my @mod;
118 for my $f (@$filter) {
119 if ( ref($f) ) {
120 # already factory object
121 push @mod,$f;
122 next;
123 }
124  
125 my $f = $f; # copy
126 my $args = $f =~s{=(.*)}{} && $1;
127  
128 my $found;
129 for my $prefix ('', map { "${_}::" } @$ns) {
130 my $mod = $prefix.$f;
131 if ( eval "require $mod" ) {
132 $found = $mod;
133 last;
134 }
135 }
136 croak("IMP module $f could not be loaded: $@") if ! $found;
137 my %args = $args ? $found->str2cfg($args) :();
138 my @err = $found->validate_cfg(%args);
139 die "bad config for $found: @err" if @err;
140 push @mod, $found->new_factory(%args)
141 }
142 $imp_factory = App::HTTP_Proxy_IMP::IMP->new_factory(@mod);
143 }
144  
145 my $capath = $self->{capath};
146 if ( $self->{no_check_certificate} ) {
147 $capath = undef;
148 } elsif ( ! $capath ) {
149 if ( eval { require Mozilla::CA } ) {
150 $capath = Mozilla::CA::SSL_ca_file();
151 } elsif ( glob("/etc/ssl/certs/*.pem") ) {
152 $capath = "/etc/ssl/certs";
153 } elsif ( -f "/etc/ssl/certs.pem" && -r _ && -s _ ) {
154 $capath = "/etc/ssl/certs.pem";
155 } else {
156 croak "cannot determine CA path, needed for SSL interception"
157 }
158 }
159  
160 # create connection fabric, attach request handling
161 my $req = App::HTTP_Proxy_IMP::Request->new;
162 my $conn = App::HTTP_Proxy_IMP::Conn->new($req,
163 pcapdir => $pcapdir,
164 mitm => $mitm,
165 capath => $capath,
166 imp_factory => $imp_factory
167 );
168  
169 # create listeners
170 my @listen;
171 $self->{addr} = [ $self->{addr} ]
172 if $self->{addr} && ref($self->{addr}) ne 'ARRAY';
173 for my $spec (@{$self->{addr}}) {
174 my ($addr,$upstream) =
175 ref($spec) eq 'ARRAY' ? @$spec:
176 ref($spec) ? ( $spec,undef ):
177 split('=',$spec,2);
178 my $srv;
179 if ( ref($addr)) {
180 # listing socket already
181 $srv = $addr;
182 (my $port,$addr) = AnyEvent::Socket::unpack_sockaddr( getsockname($srv));
183 $addr = AnyEvent::Socket::format_address($addr);
184 $addr = $addr =~m{:} ? "[$addr]:$port" : "$addr:$port";
185 } else {
186 $srv = $sockclass->new(
187 LocalAddr => $addr,
188 Listen => 10,
189 ReuseAddr => 1,
190 ) or croak("cannot listen to $addr: $!");
191 }
192 $spec = [ $addr,$upstream,$srv ];
193 push @listen, AnyEvent->io(
194 fh => $srv,
195 poll => 'r',
196 cb => sub {
197 my $cl = $srv->accept or return;
198 debug("new request from %s:%s on %s",$cl->peerhost,$cl->peerport,$addr);
199 App::HTTP_Proxy_IMP::Relay->new($cl,$upstream,$conn);
200 }
201 );
202 debug("listening on $addr");
203 }
204  
205 # on SIGUSR1 dump state of all relays
206 my $usr1 = AnyEvent->signal( signal => 'USR1', cb => sub {
207 # temporaly enable debugging, even if off
208 my $od = $DEBUG;
209 $DEBUG = 1;
210 debug("-------- active relays ------------------");
211 my @relays = App::HTTP_Proxy_IMP::Relay->relays;
212 debug(" * NO RELAYS") if ! @relays;
213 $_->dump_state for(@relays);
214 debug("-----------------------------------------");
215 $DEBUG = $od;
216 });
217  
218 my $usr2 = AnyEvent->signal( signal => 'USR2', cb => sub {
219 if ( $DEBUG ) {
220 debug("disable debugging");
221 $DEBUG = 0;
222 } else {
223 $DEBUG = 1;
224 debug("enable debugging");
225 }
226 });
227  
228 return 1 if defined wantarray;
229  
230 # enter Mainloop myself
231 AnyEvent->condvar->recv;
232 }
233  
234 sub getoptions {
235 my $self = shift;
236 local @ARGV = @_;
237 GetOptions(
238 'h|help' => sub { usage() },
239 'P|pcapdir=s' => \$self->{pcapdir},
240 'mitm-ca=s' => \$self->{mitm_ca},
241 'capath=s' => \$self->{capath},
242 'no-check-certificate=s' => \$self->{no_check_certificate},
243 'F|filter=s' => sub {
244 if ($_[1] eq '-') {
245 # discard all previously defined
246 @{$self->{filter}} = ();
247 } else {
248 push @{$self->{filter}}, $_[1]
249 }
250 },
251 'imp-ns=s' => sub {
252 if ($_[1] eq '-') {
253 # discard all previously defined
254 @{$self->{impns}} = ();
255 } else {
256 push @{$self->{impns}}, $_[1]
257 }
258 },
259 'd|debug:s' => sub {
260 $DEBUG = 1;
261 if ($_[1]) {
262 my $rx = eval { qr{$_[1]} };
263 croak("invalid regex '$_[1]' for debugging: $@") if ! $rx;
264 $DEBUG_RX = $rx;
265 }
266 },
267 'T|trace=s' => sub {
268 $TRACE{$_} = 1 for split(m/,/,$_[1])
269 },
270 'max-in-analyzer=i' => \$IMP_MAX_IN_ANALYZER,
271 );
272  
273 my @addr = @ARGV;
274 $self->{addr} or @addr or usage("no listener given");
275 $self->{addr} = \@addr;
276 1;
277 }
278  
279  
280 sub usage {
281 my ($msg,$cmd) = @_;
282 $cmd ||= $0;
283 print STDERR "ERROR: $msg\n" if $msg;
284 print STDERR <<USAGE;
285  
286 HTTP proxy, which can inspect and modify requests and responses before
287 forwarding using Net::IMP plugins.
288  
289 $cmd Options* [ip:port|ip:port=upstream_ip:port]+
290 ip:port - listen address(es) for the proxy
291 ip:port=upstream_ip:port - listen adress and upstream proxy
292  
293 Options:
294 -h|--help show usage
295  
296 --mitm-ca ca.pem use given file in PEM format as a Proxy-CA for intercepting
297 SSL connections (e.g. man in the middle). Should include key
298 and cert.
299 --capath P path to file or dir containing CAs, which are used to verify
300 server certificates when intercepting SSL.
301 Tries to use builtin default if not given.
302 --no-check-certificate do not check server certificates when intercepting
303 SSL connections
304  
305 -F|--filter F add named IMP plugin as filter, can be used multiple times
306 with --filter mod=args arguments can be given to the filter
307 --imp-ns N perl module namespace, were it will look for IMP plugins.
308 Can be given multiple times.
309 Plugins outside these namespace need to be given with
310 full name.
311 Defaults to App::HTTP_Proxy_IMP, Net::IMP
312  
313 --max-in-analyzer L set limit, on how many bytes may be send to IMP
314 analyzer w/o getting feedback from analyzer, default 2^20.
315 Set to 0 for unlimited
316
317 # options intended for development and debugging:
318 -P|--pcapdir D save connections as pcap files into D, needs Net::PcapWriter
319 -d|--debug [RX] debug mode, if RX is given restricts debugging to packages
320 matching RX
321 -T|--trace T enable Net::Inspect traces
322  
323 Examples:
324 start proxy at 127.0.0.1:8888 and log all requests to /tmp as pcap files
325 $cmd --filter Net::IMP::SessionLog=dir=/tmp/&format=pcap 127.0.0.1:8888
326 start proxy at 127.0.0.1:8888 and log all form fields
327 $cmd --filter LogFormData 127.0.0.1:8888
328 start proxy at 127.0.0.1:8888 with CSRF protection plugin
329 $cmd --filter CSRFprotect 127.0.0.1:8888
330 start proxy at 127.0.0.1:8888 with CSRF protection plugin, using upstream
331 proxy proxy:8888
332 $cmd --filter CSRFprotect 127.0.0.1:8888=proxy:8888
333  
334 USAGE
335 exit(2);
336 }
337  
338  
339 1;
340 __END__
« HTTP_Proxy_IMP/IMP/Example/changeTarget.pm ↑ Summary HTTP_Proxy_IMP/IMP.pm »