Convert existing usage of assert() to ossl_assert() in libssl
[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         if ($self->debug) {
175             print STDERR "Server command: $execcmd\n";
176         }
177         exec($execcmd);
178     }
179     $self->serverpid($pid);
180
181     return $self->clientstart;
182 }
183
184 sub clientstart
185 {
186     my ($self) = shift;
187     my $oldstdout;
188
189     if(!$self->debug) {
190         open DEVNULL, ">", File::Spec->devnull();
191         $oldstdout = select(DEVNULL);
192     }
193
194     # Create the Proxy socket
195     my $proxaddr = $self->proxy_addr;
196     $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
197     my $proxy_sock = $IP_factory->(
198         LocalHost   => $proxaddr,
199         LocalPort   => $self->proxy_port,
200         Proto       => "tcp",
201         Listen      => SOMAXCONN,
202         ReuseAddr   => 1
203     );
204
205     if ($proxy_sock) {
206         print "Proxy started on port ".$self->proxy_port."\n";
207     } else {
208         warn "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
209         return 0;
210     }
211
212     if ($self->execute) {
213         my $pid = fork();
214         if ($pid == 0) {
215             if (!$self->debug) {
216                 open(STDOUT, ">", File::Spec->devnull())
217                     or die "Failed to redirect stdout: $!";
218                 open(STDERR, ">&STDOUT");
219             }
220             my $echostr;
221             if ($self->reneg()) {
222                 $echostr = "R";
223             } else {
224                 $echostr = "test";
225             }
226             my $execcmd = "echo ".$echostr." | ".$self->execute
227                  ." s_client -engine ossltest -connect "
228                  .($self->proxy_addr).":".($self->proxy_port);
229             if ($self->cipherc ne "") {
230                 $execcmd .= " -cipher ".$self->cipherc;
231             }
232             if ($self->clientflags ne "") {
233                 $execcmd .= " ".$self->clientflags;
234             }
235             if (defined $self->sessionfile) {
236                 $execcmd .= " -ign_eof";
237             }
238             if ($self->debug) {
239                 print STDERR "Client command: $execcmd\n";
240             }
241             exec($execcmd);
242         }
243     }
244
245     # Wait for incoming connection from client
246     my $client_sock;
247     if(!($client_sock = $proxy_sock->accept())) {
248         warn "Failed accepting incoming connection: $!\n";
249         return 0;
250     }
251
252     print "Connection opened\n";
253
254     # Now connect to the server
255     my $retry = 3;
256     my $server_sock;
257     #We loop over this a few times because sometimes s_server can take a while
258     #to start up
259     do {
260         my $servaddr = $self->server_addr;
261         $servaddr =~ s/[\[\]]//g; # Remove [ and ]
262         eval {
263             $server_sock = $IP_factory->(
264                 PeerAddr => $servaddr,
265                 PeerPort => $self->server_port,
266                 MultiHomed => 1,
267                 Proto => 'tcp'
268             );
269         };
270
271         $retry--;
272         #Some buggy IP factories can return a defined server_sock that hasn't
273         #actually connected, so we check peerport too
274         if ($@ || !defined($server_sock) || !defined($server_sock->peerport)) {
275             $server_sock->close() if defined($server_sock);
276             undef $server_sock;
277             if ($retry) {
278                 #Sleep for a short while
279                 select(undef, undef, undef, 0.1);
280             } else {
281                 warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
282                 return 0;
283             }
284         }
285     } while (!$server_sock);
286
287     my $sel = IO::Select->new($server_sock, $client_sock);
288     my $indata;
289     my @handles = ($server_sock, $client_sock);
290
291     #Wait for either the server socket or the client socket to become readable
292     my @ready;
293     my $ctr = 0;
294     while(     (!(TLSProxy::Message->end)
295                 || (defined $self->sessionfile()
296                     && (-s $self->sessionfile()) == 0))
297             && $ctr < 10
298             && (@ready = $sel->can_read(1))) {
299         foreach my $hand (@ready) {
300             if ($hand == $server_sock) {
301                 $server_sock->sysread($indata, 16384) or goto END;
302                 $indata = $self->process_packet(1, $indata);
303                 $client_sock->syswrite($indata);
304                 $ctr = 0;
305             } elsif ($hand == $client_sock) {
306                 $client_sock->sysread($indata, 16384) or goto END;
307                 $indata = $self->process_packet(0, $indata);
308                 $server_sock->syswrite($indata);
309                 $ctr = 0;
310             } else {
311                 $ctr++
312             }
313         }
314     }
315
316     die "No progress made" if $ctr >= 10;
317
318     END:
319     print "Connection closed\n";
320     if($server_sock) {
321         $server_sock->close();
322     }
323     if($client_sock) {
324         #Closing this also kills the child process
325         $client_sock->close();
326     }
327     if($proxy_sock) {
328         $proxy_sock->close();
329     }
330     if(!$self->debug) {
331         select($oldstdout);
332     }
333     $self->serverconnects($self->serverconnects - 1);
334     if ($self->serverconnects == 0) {
335         die "serverpid is zero\n" if $self->serverpid == 0;
336         print "Waiting for server process to close: "
337               .$self->serverpid."\n";
338         waitpid( $self->serverpid, 0);
339         die "exit code $? from server process\n" if $? != 0;
340     }
341     return 1;
342 }
343
344 sub process_packet
345 {
346     my ($self, $server, $packet) = @_;
347     my $len_real;
348     my $decrypt_len;
349     my $data;
350     my $recnum;
351
352     if ($server) {
353         print "Received server packet\n";
354     } else {
355         print "Received client packet\n";
356     }
357
358     print "Packet length = ".length($packet)."\n";
359     print "Processing flight ".$self->flight."\n";
360
361     #Return contains the list of record found in the packet followed by the
362     #list of messages in those records
363     my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet);
364     push @{$self->record_list}, @{$ret[0]};
365     push @{$self->{message_list}}, @{$ret[1]};
366
367     print "\n";
368
369     #Finished parsing. Call user provided filter here
370     if(defined $self->filter) {
371         $self->filter->($self);
372     }
373
374     #Reconstruct the packet
375     $packet = "";
376     foreach my $record (@{$self->record_list}) {
377         #We only replay the records for the current flight
378         if ($record->flight != $self->flight) {
379             next;
380         }
381         $packet .= $record->reconstruct_record($server);
382     }
383
384     $self->{flight} = $self->{flight} + 1;
385
386     print "Forwarded packet length = ".length($packet)."\n\n";
387
388     return $packet;
389 }
390
391 #Read accessors
392 sub execute
393 {
394     my $self = shift;
395     return $self->{execute};
396 }
397 sub cert
398 {
399     my $self = shift;
400     return $self->{cert};
401 }
402 sub debug
403 {
404     my $self = shift;
405     return $self->{debug};
406 }
407 sub flight
408 {
409     my $self = shift;
410     return $self->{flight};
411 }
412 sub record_list
413 {
414     my $self = shift;
415     return $self->{record_list};
416 }
417 sub success
418 {
419     my $self = shift;
420     return $self->{success};
421 }
422 sub end
423 {
424     my $self = shift;
425     return $self->{end};
426 }
427 sub supports_IPv6
428 {
429     my $self = shift;
430     return $have_IPv6;
431 }
432
433 #Read/write accessors
434 sub proxy_addr
435 {
436     my $self = shift;
437     if (@_) {
438         $self->{proxy_addr} = shift;
439     }
440     return $self->{proxy_addr};
441 }
442 sub proxy_port
443 {
444     my $self = shift;
445     if (@_) {
446         $self->{proxy_port} = shift;
447     }
448     return $self->{proxy_port};
449 }
450 sub server_addr
451 {
452     my $self = shift;
453     if (@_) {
454         $self->{server_addr} = shift;
455     }
456     return $self->{server_addr};
457 }
458 sub server_port
459 {
460     my $self = shift;
461     if (@_) {
462         $self->{server_port} = shift;
463     }
464     return $self->{server_port};
465 }
466 sub filter
467 {
468     my $self = shift;
469     if (@_) {
470         $self->{filter} = shift;
471     }
472     return $self->{filter};
473 }
474 sub cipherc
475 {
476     my $self = shift;
477     if (@_) {
478         $self->{cipherc} = shift;
479     }
480     return $self->{cipherc};
481 }
482 sub ciphers
483 {
484     my $self = shift;
485     if (@_) {
486         $self->{ciphers} = shift;
487     }
488     return $self->{ciphers};
489 }
490 sub serverflags
491 {
492     my $self = shift;
493     if (@_) {
494         $self->{serverflags} = shift;
495     }
496     return $self->{serverflags};
497 }
498 sub clientflags
499 {
500     my $self = shift;
501     if (@_) {
502         $self->{clientflags} = shift;
503     }
504     return $self->{clientflags};
505 }
506 sub serverconnects
507 {
508     my $self = shift;
509     if (@_) {
510         $self->{serverconnects} = shift;
511     }
512     return $self->{serverconnects};
513 }
514 # This is a bit ugly because the caller is responsible for keeping the records
515 # in sync with the updated message list; simply updating the message list isn't
516 # sufficient to get the proxy to forward the new message.
517 # But it does the trick for the one test (test_sslsessiontick) that needs it.
518 sub message_list
519 {
520     my $self = shift;
521     if (@_) {
522         $self->{message_list} = shift;
523     }
524     return $self->{message_list};
525 }
526 sub serverpid
527 {
528     my $self = shift;
529     if (@_) {
530         $self->{serverpid} = shift;
531     }
532     return $self->{serverpid};
533 }
534
535 sub fill_known_data
536 {
537     my $length = shift;
538     my $ret = "";
539     for (my $i = 0; $i < $length; $i++) {
540         $ret .= chr($i);
541     }
542     return $ret;
543 }
544
545 sub is_tls13
546 {
547     my $class = shift;
548     if (@_) {
549         $is_tls13 = shift;
550     }
551     return $is_tls13;
552 }
553
554 sub reneg
555 {
556     my $self = shift;
557     if (@_) {
558         $self->{reneg} = shift;
559     }
560     return $self->{reneg};
561 }
562
563 #Setting a sessionfile means that the client will not close until the given
564 #file exists. This is useful in TLSv1.3 where otherwise s_client will close
565 #immediately at the end of the handshake, but before the session has been
566 #received from the server. A side effect of this is that s_client never sends
567 #a close_notify, so instead we consider success to be when it sends application
568 #data over the connection.
569 sub sessionfile
570 {
571     my $self = shift;
572     if (@_) {
573         $self->{sessionfile} = shift;
574         TLSProxy::Message->successondata(1);
575     }
576     return $self->{sessionfile};
577 }
578
579 sub ciphersuite
580 {
581     my $class = shift;
582     if (@_) {
583         $ciphersuite = shift;
584     }
585     return $ciphersuite;
586 }
587
588 1;