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