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