d778d0e70da7c81a7b36ffcdd391827eb6c0d97a
[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::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         ciphers => "AES128-SHA:TLS13-AES-128-GCM-SHA256",
62         flight => 0,
63         record_list => [],
64         message_list => [],
65     };
66
67     # IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
68     # However, IO::Socket::INET6 is older and is said to be more widely
69     # deployed for the moment, and may have less bugs, so we try the latter
70     # first, then fall back on the code modules.  Worst case scenario, we
71     # fall back to IO::Socket::INET, only supports IPv4.
72     eval {
73         require IO::Socket::INET6;
74         my $s = IO::Socket::INET6->new(
75             LocalAddr => "::1",
76             LocalPort => 0,
77             Listen=>1,
78             );
79         $s or die "\n";
80         $s->close();
81     };
82     if ($@ eq "") {
83         $IP_factory = sub { IO::Socket::INET6->new(@_); };
84         $have_IPv6 = 1;
85     } else {
86         eval {
87             require IO::Socket::IP;
88             my $s = IO::Socket::IP->new(
89                 LocalAddr => "::1",
90                 LocalPort => 0,
91                 Listen=>1,
92                 );
93             $s or die "\n";
94             $s->close();
95         };
96         if ($@ eq "") {
97             $IP_factory = sub { IO::Socket::IP->new(@_); };
98             $have_IPv6 = 1;
99         } else {
100             $IP_factory = sub { IO::Socket::INET->new(@_); };
101         }
102     }
103
104     return bless $self, $class;
105 }
106
107 sub clearClient
108 {
109     my $self = shift;
110
111     $self->{cipherc} = "";
112     $self->{flight} = 0;
113     $self->{record_list} = [];
114     $self->{message_list} = [];
115     $self->{clientflags} = "";
116     $self->{sessionfile} = undef;
117     $self->{clientpid} = 0;
118     $is_tls13 = 0;
119     $ciphersuite = undef;
120
121     TLSProxy::Message->clear();
122     TLSProxy::Record->clear();
123 }
124
125 sub clear
126 {
127     my $self = shift;
128
129     $self->clearClient;
130     $self->{ciphers} = "AES128-SHA:TLS13-AES-128-GCM-SHA256";
131     $self->{serverflags} = "";
132     $self->{serverconnects} = 1;
133     $self->{serverpid} = 0;
134     $self->{reneg} = 0;
135 }
136
137 sub restart
138 {
139     my $self = shift;
140
141     $self->clear;
142     $self->start;
143 }
144
145 sub clientrestart
146 {
147     my $self = shift;
148
149     $self->clear;
150     $self->clientstart;
151 }
152
153 sub start
154 {
155     my ($self) = shift;
156     my $pid;
157
158     $pid = fork();
159     if ($pid == 0) {
160         if (!$self->debug) {
161             open(STDOUT, ">", File::Spec->devnull())
162                 or die "Failed to redirect stdout: $!";
163             open(STDERR, ">&STDOUT");
164         }
165         my $execcmd = $self->execute
166             ." s_server -no_comp -rev -engine ossltest -accept "
167             .($self->server_port)
168             ." -cert ".$self->cert." -cert2 ".$self->cert
169             ." -naccept ".$self->serverconnects;
170         if ($self->ciphers ne "") {
171             $execcmd .= " -cipher ".$self->ciphers;
172         }
173         if ($self->serverflags ne "") {
174             $execcmd .= " ".$self->serverflags;
175         }
176         if ($self->debug) {
177             print STDERR "Server command: $execcmd\n";
178         }
179         exec($execcmd);
180     }
181     $self->serverpid($pid);
182
183     return $self->clientstart;
184 }
185
186 sub clientstart
187 {
188     my ($self) = shift;
189     my $oldstdout;
190
191     if(!$self->debug) {
192         open DEVNULL, ">", File::Spec->devnull();
193         $oldstdout = select(DEVNULL);
194     }
195
196     # Create the Proxy socket
197     my $proxaddr = $self->proxy_addr;
198     $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
199     my $proxy_sock = $IP_factory->(
200         LocalHost   => $proxaddr,
201         LocalPort   => $self->proxy_port,
202         Proto       => "tcp",
203         Listen      => SOMAXCONN,
204         ReuseAddr   => 1
205     );
206
207     if ($proxy_sock) {
208         print "Proxy started on port ".$self->proxy_port."\n";
209     } else {
210         warn "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
211         return 0;
212     }
213
214     if ($self->execute) {
215         my $pid = fork();
216         if ($pid == 0) {
217             if (!$self->debug) {
218                 open(STDOUT, ">", File::Spec->devnull())
219                     or die "Failed to redirect stdout: $!";
220                 open(STDERR, ">&STDOUT");
221             }
222             my $echostr;
223             if ($self->reneg()) {
224                 $echostr = "R";
225             } else {
226                 $echostr = "test";
227             }
228             my $execcmd = "echo ".$echostr." | ".$self->execute
229                  ." s_client -engine ossltest -connect "
230                  .($self->proxy_addr).":".($self->proxy_port);
231             if ($self->cipherc ne "") {
232                 $execcmd .= " -cipher ".$self->cipherc;
233             }
234             if ($self->clientflags ne "") {
235                 $execcmd .= " ".$self->clientflags;
236             }
237             if (defined $self->sessionfile) {
238                 $execcmd .= " -ign_eof";
239             }
240             if ($self->debug) {
241                 print STDERR "Client command: $execcmd\n";
242             }
243             exec($execcmd);
244         }
245         $self->clientpid($pid);
246     }
247
248     # Wait for incoming connection from client
249     my $client_sock;
250     if(!($client_sock = $proxy_sock->accept())) {
251         warn "Failed accepting incoming connection: $!\n";
252         return 0;
253     }
254
255     print "Connection opened\n";
256
257     # Now connect to the server
258     my $retry = 50;
259     my $server_sock;
260     #We loop over this a few times because sometimes s_server can take a while
261     #to start up
262     do {
263         my $servaddr = $self->server_addr;
264         $servaddr =~ s/[\[\]]//g; # Remove [ and ]
265         eval {
266             $server_sock = $IP_factory->(
267                 PeerAddr => $servaddr,
268                 PeerPort => $self->server_port,
269                 MultiHomed => 1,
270                 Proto => 'tcp'
271             );
272         };
273
274         $retry--;
275         #Some buggy IP factories can return a defined server_sock that hasn't
276         #actually connected, so we check peerport too
277         if ($@ || !defined($server_sock) || !defined($server_sock->peerport)) {
278             $server_sock->close() if defined($server_sock);
279             undef $server_sock;
280             if ($retry) {
281                 #Sleep for a short while
282                 select(undef, undef, undef, 0.1);
283             } else {
284                 warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
285                 return 0;
286             }
287         }
288     } while (!$server_sock);
289
290     my $sel = IO::Select->new($server_sock, $client_sock);
291     my $indata;
292     my @handles = ($server_sock, $client_sock);
293
294     #Wait for either the server socket or the client socket to become readable
295     my @ready;
296     my $ctr = 0;
297     local $SIG{PIPE} = "IGNORE";
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;