db7b19c4a4f3dd8636d72efc032ce2277e103855
[openssl.git] / util / perl / TLSProxy / Proxy.pm
1 # Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
2 #
3 # Licensed under the OpenSSL license (the "License").  You may not use
4 # this file except in compliance with the License.  You can obtain a copy
5 # in the file LICENSE in the source distribution or at
6 # https://www.openssl.org/source/license.html
7
8 use strict;
9 use POSIX ":sys_wait_h";
10
11 package TLSProxy::Proxy;
12
13 use File::Spec;
14 use IO::Socket;
15 use IO::Select;
16 use TLSProxy::Record;
17 use TLSProxy::Message;
18 use TLSProxy::ClientHello;
19 use TLSProxy::ServerHello;
20 use TLSProxy::EncryptedExtensions;
21 use TLSProxy::Certificate;
22 use TLSProxy::CertificateVerify;
23 use TLSProxy::ServerKeyExchange;
24 use TLSProxy::NewSessionTicket;
25 use Time::HiRes qw/usleep/;
26
27 my $have_IPv6 = 0;
28 my $IP_factory;
29
30 my $is_tls13 = 0;
31 my $ciphersuite = undef;
32
33 sub new
34 {
35     my $class = shift;
36     my ($filter,
37         $execute,
38         $cert,
39         $debug) = @_;
40
41     my $self = {
42         #Public read/write
43         proxy_addr => "localhost",
44         proxy_port => 4453,
45         server_addr => "localhost",
46         server_port => 4443,
47         filter => $filter,
48         serverflags => "",
49         clientflags => "",
50         serverconnects => 1,
51         serverpid => 0,
52         clientpid => 0,
53         reneg => 0,
54         sessionfile => undef,
55
56         #Public read
57         execute => $execute,
58         cert => $cert,
59         debug => $debug,
60         cipherc => "",
61         ciphersuitesc => "",
62         ciphers => "AES128-SHA",
63         ciphersuitess => "TLS_AES_128_GCM_SHA256",
64         flight => 0,
65         record_list => [],
66         message_list => [],
67     };
68
69     # IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
70     # However, IO::Socket::INET6 is older and is said to be more widely
71     # deployed for the moment, and may have less bugs, so we try the latter
72     # first, then fall back on the code modules.  Worst case scenario, we
73     # fall back to IO::Socket::INET, only supports IPv4.
74     eval {
75         require IO::Socket::INET6;
76         my $s = IO::Socket::INET6->new(
77             LocalAddr => "::1",
78             LocalPort => 0,
79             Listen=>1,
80             );
81         $s or die "\n";
82         $s->close();
83     };
84     if ($@ eq "") {
85         $IP_factory = sub { IO::Socket::INET6->new(@_); };
86         $have_IPv6 = 1;
87     } else {
88         eval {
89             require IO::Socket::IP;
90             my $s = IO::Socket::IP->new(
91                 LocalAddr => "::1",
92                 LocalPort => 0,
93                 Listen=>1,
94                 );
95             $s or die "\n";
96             $s->close();
97         };
98         if ($@ eq "") {
99             $IP_factory = sub { IO::Socket::IP->new(@_); };
100             $have_IPv6 = 1;
101         } else {
102             $IP_factory = sub { IO::Socket::INET->new(@_); };
103         }
104     }
105
106     # Create the Proxy socket
107     my $proxaddr = $self->{proxy_addr};
108     $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
109     my @proxyargs = (
110         LocalHost   => $proxaddr,
111         LocalPort   => $self->{proxy_port},
112         Proto       => "tcp",
113         Listen      => SOMAXCONN,
114        );
115     push @proxyargs, ReuseAddr => 1
116         unless $^O eq "MSWin32";
117     $self->{proxy_sock} = $IP_factory->(@proxyargs);
118
119     if ($self->{proxy_sock}) {
120         print "Proxy started on port ".$self->{proxy_port}."\n";
121     } else {
122         warn "Failed creating proxy socket (".$proxaddr.",".$self->{proxy_port}."): $!\n";
123     }
124
125     return bless $self, $class;
126 }
127
128 sub DESTROY
129 {
130     my $self = shift;
131
132     $self->{proxy_sock}->close() if $self->{proxy_sock};
133 }
134
135 sub clearClient
136 {
137     my $self = shift;
138
139     $self->{cipherc} = "";
140     $self->{ciphersuitec} = "";
141     $self->{flight} = 0;
142     $self->{record_list} = [];
143     $self->{message_list} = [];
144     $self->{clientflags} = "";
145     $self->{sessionfile} = undef;
146     $self->{clientpid} = 0;
147     $is_tls13 = 0;
148     $ciphersuite = undef;
149
150     TLSProxy::Message->clear();
151     TLSProxy::Record->clear();
152 }
153
154 sub clear
155 {
156     my $self = shift;
157
158     $self->clearClient;
159     $self->{ciphers} = "AES128-SHA";
160     $self->{ciphersuitess} = "TLS_AES_128_GCM_SHA256";
161     $self->{serverflags} = "";
162     $self->{serverconnects} = 1;
163     $self->{serverpid} = 0;
164     $self->{reneg} = 0;
165 }
166
167 sub restart
168 {
169     my $self = shift;
170
171     $self->clear;
172     $self->start;
173 }
174
175 sub clientrestart
176 {
177     my $self = shift;
178
179     $self->clear;
180     $self->clientstart;
181 }
182
183 sub start
184 {
185     my ($self) = shift;
186     my $pid;
187
188     if ($self->{proxy_sock} == 0) {
189         return 0;
190     }
191
192     $pid = fork();
193     if ($pid == 0) {
194         my $execcmd = $self->execute
195             ." s_server -no_comp -rev -engine ossltest -accept "
196             .($self->server_port)
197             ." -cert ".$self->cert." -cert2 ".$self->cert
198             ." -naccept ".$self->serverconnects;
199         unless ($self->supports_IPv6) {
200             $execcmd .= " -4";
201         }
202         if ($self->ciphers ne "") {
203             $execcmd .= " -cipher ".$self->ciphers;
204         }
205         if ($self->ciphersuitess ne "") {
206             $execcmd .= " -ciphersuites ".$self->ciphersuitess;
207         }
208         if ($self->serverflags ne "") {
209             $execcmd .= " ".$self->serverflags;
210         }
211         if ($self->debug) {
212             print STDERR "Server command: $execcmd\n";
213         }
214         exec($execcmd);
215     }
216     $self->serverpid($pid);
217
218     return $self->clientstart;
219 }
220
221 sub clientstart
222 {
223     my ($self) = shift;
224     my $oldstdout;
225
226     if ($self->execute) {
227         my $pid = fork();
228         if ($pid == 0) {
229             my $echostr;
230             if ($self->reneg()) {
231                 $echostr = "R";
232             } else {
233                 $echostr = "test";
234             }
235             my $execcmd = "echo ".$echostr." | ".$self->execute
236                  ." s_client -engine ossltest -connect "
237                  .($self->proxy_addr).":".($self->proxy_port);
238             unless ($self->supports_IPv6) {
239                 $execcmd .= " -4";
240             }
241             if ($self->cipherc ne "") {
242                 $execcmd .= " -cipher ".$self->cipherc;
243             }
244             if ($self->ciphersuitesc ne "") {
245                 $execcmd .= " -ciphersuites ".$self->ciphersuitesc;
246             }
247             if ($self->clientflags ne "") {
248                 $execcmd .= " ".$self->clientflags;
249             }
250             if (defined $self->sessionfile) {
251                 $execcmd .= " -ign_eof";
252             }
253             if ($self->debug) {
254                 print STDERR "Client command: $execcmd\n";
255             }
256             exec($execcmd);
257         }
258         $self->clientpid($pid);
259     }
260
261     # Wait for incoming connection from client
262     my $client_sock;
263     if(!($client_sock = $self->{proxy_sock}->accept())) {
264         warn "Failed accepting incoming connection: $!\n";
265         return 0;
266     }
267
268     print "Connection opened\n";
269
270     # Now connect to the server
271     my $retry = 50;
272     my $server_sock;
273     #We loop over this a few times because sometimes s_server can take a while
274     #to start up
275     do {
276         my $servaddr = $self->server_addr;
277         $servaddr =~ s/[\[\]]//g; # Remove [ and ]
278         eval {
279             $server_sock = $IP_factory->(
280                 PeerAddr => $servaddr,
281                 PeerPort => $self->server_port,
282                 MultiHomed => 1,
283                 Proto => 'tcp'
284             );
285         };
286
287         $retry--;
288         #Some buggy IP factories can return a defined server_sock that hasn't
289         #actually connected, so we check peerport too
290         if ($@ || !defined($server_sock) || !defined($server_sock->peerport)) {
291             $server_sock->close() if defined($server_sock);
292             undef $server_sock;
293             if ($retry) {
294                 #Sleep for a short while
295                 select(undef, undef, undef, 0.1);
296             } else {
297                 warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
298                 return 0;
299             }
300         }
301     } while (!$server_sock);
302
303     my $sel = IO::Select->new($server_sock, $client_sock);
304     my $indata;
305     my @handles = ($server_sock, $client_sock);
306
307     #Wait for either the server socket or the client socket to become readable
308     my @ready;
309     my $ctr = 0;
310     local $SIG{PIPE} = "IGNORE";
311     while(     (!(TLSProxy::Message->end)
312                 || (defined $self->sessionfile()
313                     && (-s $self->sessionfile()) == 0))
314             && $ctr < 10) {
315         if (!(@ready = $sel->can_read(1))) {
316             $ctr++;
317             next;
318         }
319         foreach my $hand (@ready) {
320             if ($hand == $server_sock) {
321                 $server_sock->sysread($indata, 16384) or goto END;
322                 $indata = $self->process_packet(1, $indata);
323                 $client_sock->syswrite($indata);
324                 $ctr = 0;
325             } elsif ($hand == $client_sock) {
326                 $client_sock->sysread($indata, 16384) or goto END;
327                 $indata = $self->process_packet(0, $indata);
328                 $server_sock->syswrite($indata);
329                 $ctr = 0;
330             } else {
331                 die "Unexpected handle";
332             }
333         }
334     }
335
336     die "No progress made" if $ctr >= 10;
337
338     END:
339     print "Connection closed\n";
340     if($server_sock) {
341         $server_sock->close();
342     }
343     if($client_sock) {
344         #Closing this also kills the child process
345         $client_sock->close();
346     }
347     if(!$self->debug) {
348         select($oldstdout);
349     }
350     $self->serverconnects($self->serverconnects - 1);
351     if ($self->serverconnects == 0) {
352         die "serverpid is zero\n" if $self->serverpid == 0;
353         print "Waiting for server process to close: "
354               .$self->serverpid."\n";
355         waitpid( $self->serverpid, 0);
356         die "exit code $? from server process\n" if $? != 0;
357     } else {
358         # Give s_server sufficient time to finish what it was doing
359         usleep(250000);
360     }
361     die "clientpid is zero\n" if $self->clientpid == 0;
362     print "Waiting for client process to close: ".$self->clientpid."\n";
363     waitpid($self->clientpid, 0);
364
365     return 1;
366 }
367
368 sub process_packet
369 {
370     my ($self, $server, $packet) = @_;
371     my $len_real;
372     my $decrypt_len;
373     my $data;
374     my $recnum;
375
376     if ($server) {
377         print "Received server packet\n";
378     } else {
379         print "Received client packet\n";
380     }
381
382     print "Packet length = ".length($packet)."\n";
383     print "Processing flight ".$self->flight."\n";
384
385     #Return contains the list of record found in the packet followed by the
386     #list of messages in those records
387     my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet);
388     push @{$self->record_list}, @{$ret[0]};
389     push @{$self->{message_list}}, @{$ret[1]};
390
391     print "\n";
392
393     #Finished parsing. Call user provided filter here
394     if(defined $self->filter) {
395         $self->filter->($self);
396     }
397
398     #Reconstruct the packet
399     $packet = "";
400     foreach my $record (@{$self->record_list}) {
401         #We only replay the records for the current flight
402         if ($record->flight != $self->flight) {
403             next;
404         }
405         $packet .= $record->reconstruct_record($server);
406     }
407
408     $self->{flight} = $self->{flight} + 1;
409
410     print "Forwarded packet length = ".length($packet)."\n\n";
411
412     return $packet;
413 }
414
415 #Read accessors
416 sub execute
417 {
418     my $self = shift;
419     return $self->{execute};
420 }
421 sub cert
422 {
423     my $self = shift;
424     return $self->{cert};
425 }
426 sub debug
427 {
428     my $self = shift;
429     return $self->{debug};
430 }
431 sub flight
432 {
433     my $self = shift;
434     return $self->{flight};
435 }
436 sub record_list
437 {
438     my $self = shift;
439     return $self->{record_list};
440 }
441 sub success
442 {
443     my $self = shift;
444     return $self->{success};
445 }
446 sub end
447 {
448     my $self = shift;
449     return $self->{end};
450 }
451 sub supports_IPv6
452 {
453     my $self = shift;
454     return $have_IPv6;
455 }
456 sub proxy_addr
457 {
458     my $self = shift;
459     return $self->{proxy_addr};
460 }
461 sub proxy_port
462 {
463     my $self = shift;
464     return $self->{proxy_port};
465 }
466
467 #Read/write accessors
468 sub server_addr
469 {
470     my $self = shift;
471     if (@_) {
472         $self->{server_addr} = shift;
473     }
474     return $self->{server_addr};
475 }
476 sub server_port
477 {
478     my $self = shift;
479     if (@_) {
480         $self->{server_port} = shift;
481     }
482     return $self->{server_port};
483 }
484 sub filter
485 {
486     my $self = shift;
487     if (@_) {
488         $self->{filter} = shift;
489     }
490     return $self->{filter};
491 }
492 sub cipherc
493 {
494     my $self = shift;
495     if (@_) {
496         $self->{cipherc} = shift;
497     }
498     return $self->{cipherc};
499 }
500 sub ciphersuitesc
501 {
502     my $self = shift;
503     if (@_) {
504         $self->{ciphersuitesc} = shift;
505     }
506     return $self->{ciphersuitesc};
507 }
508 sub ciphers
509 {
510     my $self = shift;
511     if (@_) {
512         $self->{ciphers} = shift;
513     }
514     return $self->{ciphers};
515 }
516 sub ciphersuitess
517 {
518     my $self = shift;
519     if (@_) {
520         $self->{ciphersuitess} = shift;
521     }
522     return $self->{ciphersuitess};
523 }
524 sub serverflags
525 {
526     my $self = shift;
527     if (@_) {
528         $self->{serverflags} = shift;
529     }
530     return $self->{serverflags};
531 }
532 sub clientflags
533 {
534     my $self = shift;
535     if (@_) {
536         $self->{clientflags} = shift;
537     }
538     return $self->{clientflags};
539 }
540 sub serverconnects
541 {
542     my $self = shift;
543     if (@_) {
544         $self->{serverconnects} = shift;
545     }
546     return $self->{serverconnects};
547 }
548 # This is a bit ugly because the caller is responsible for keeping the records
549 # in sync with the updated message list; simply updating the message list isn't
550 # sufficient to get the proxy to forward the new message.
551 # But it does the trick for the one test (test_sslsessiontick) that needs it.
552 sub message_list
553 {
554     my $self = shift;
555     if (@_) {
556         $self->{message_list} = shift;
557     }
558     return $self->{message_list};
559 }
560 sub serverpid
561 {
562     my $self = shift;
563     if (@_) {
564         $self->{serverpid} = shift;
565     }
566     return $self->{serverpid};
567 }
568 sub clientpid
569 {
570     my $self = shift;
571     if (@_) {
572         $self->{clientpid} = shift;
573     }
574     return $self->{clientpid};
575 }
576
577 sub fill_known_data
578 {
579     my $length = shift;
580     my $ret = "";
581     for (my $i = 0; $i < $length; $i++) {
582         $ret .= chr($i);
583     }
584     return $ret;
585 }
586
587 sub is_tls13
588 {
589     my $class = shift;
590     if (@_) {
591         $is_tls13 = shift;
592     }
593     return $is_tls13;
594 }
595
596 sub reneg
597 {
598     my $self = shift;
599     if (@_) {
600         $self->{reneg} = shift;
601     }
602     return $self->{reneg};
603 }
604
605 #Setting a sessionfile means that the client will not close until the given
606 #file exists. This is useful in TLSv1.3 where otherwise s_client will close
607 #immediately at the end of the handshake, but before the session has been
608 #received from the server. A side effect of this is that s_client never sends
609 #a close_notify, so instead we consider success to be when it sends application
610 #data over the connection.
611 sub sessionfile
612 {
613     my $self = shift;
614     if (@_) {
615         $self->{sessionfile} = shift;
616         TLSProxy::Message->successondata(1);
617     }
618     return $self->{sessionfile};
619 }
620
621 sub ciphersuite
622 {
623     my $class = shift;
624     if (@_) {
625         $ciphersuite = shift;
626     }
627     return $ciphersuite;
628 }
629
630 1;