TLSProxy::Proxy: don't waste time redirecting STDOUT and STDERR
[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         my $execcmd = $self->execute
161             ." s_server -no_comp -rev -engine ossltest -accept "
162             .($self->server_port)
163             ." -cert ".$self->cert." -cert2 ".$self->cert
164             ." -naccept ".$self->serverconnects;
165         unless ($self->supports_IPv6) {
166             $execcmd .= " -4";
167         }
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     # Create the Proxy socket
190     my $proxaddr = $self->proxy_addr;
191     $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
192     my $proxy_sock = $IP_factory->(
193         LocalHost   => $proxaddr,
194         LocalPort   => $self->proxy_port,
195         Proto       => "tcp",
196         Listen      => SOMAXCONN,
197         ReuseAddr   => 1
198     );
199
200     if ($proxy_sock) {
201         print "Proxy started on port ".$self->proxy_port."\n";
202     } else {
203         warn "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
204         return 0;
205     }
206
207     if ($self->execute) {
208         my $pid = fork();
209         if ($pid == 0) {
210             my $echostr;
211             if ($self->reneg()) {
212                 $echostr = "R";
213             } else {
214                 $echostr = "test";
215             }
216             my $execcmd = "echo ".$echostr." | ".$self->execute
217                  ." s_client -engine ossltest -connect "
218                  .($self->proxy_addr).":".($self->proxy_port);
219             unless ($self->supports_IPv6) {
220                 $execcmd .= " -4";
221             }
222             if ($self->cipherc ne "") {
223                 $execcmd .= " -cipher ".$self->cipherc;
224             }
225             if ($self->clientflags ne "") {
226                 $execcmd .= " ".$self->clientflags;
227             }
228             if (defined $self->sessionfile) {
229                 $execcmd .= " -ign_eof";
230             }
231             if ($self->debug) {
232                 print STDERR "Client command: $execcmd\n";
233             }
234             exec($execcmd);
235         }
236         $self->clientpid($pid);
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 = 50;
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     local $SIG{PIPE} = "IGNORE";
289     while(     (!(TLSProxy::Message->end)
290                 || (defined $self->sessionfile()
291                     && (-s $self->sessionfile()) == 0))
292             && $ctr < 10) {
293         if (!(@ready = $sel->can_read(1))) {
294             $ctr++;
295             next;
296         }
297         foreach my $hand (@ready) {
298             if ($hand == $server_sock) {
299                 $server_sock->sysread($indata, 16384) or goto END;
300                 $indata = $self->process_packet(1, $indata);
301                 $client_sock->syswrite($indata);
302                 $ctr = 0;
303             } elsif ($hand == $client_sock) {
304                 $client_sock->sysread($indata, 16384) or goto END;
305                 $indata = $self->process_packet(0, $indata);
306                 $server_sock->syswrite($indata);
307                 $ctr = 0;
308             } else {
309                 die "Unexpected handle";
310             }
311         }
312     }
313
314     die "No progress made" if $ctr >= 10;
315
316     END:
317     print "Connection closed\n";
318     if($server_sock) {
319         $server_sock->close();
320     }
321     if($client_sock) {
322         #Closing this also kills the child process
323         $client_sock->close();
324     }
325     if($proxy_sock) {
326         $proxy_sock->close();
327     }
328     if(!$self->debug) {
329         select($oldstdout);
330     }
331     $self->serverconnects($self->serverconnects - 1);
332     if ($self->serverconnects == 0) {
333         die "serverpid is zero\n" if $self->serverpid == 0;
334         print "Waiting for server process to close: "
335               .$self->serverpid."\n";
336         waitpid( $self->serverpid, 0);
337         die "exit code $? from server process\n" if $? != 0;
338     } else {
339         # Give s_server sufficient time to finish what it was doing
340         usleep(250000);
341     }
342     die "clientpid is zero\n" if $self->clientpid == 0;
343     print "Waiting for client process to close: ".$self->clientpid."\n";
344     waitpid($self->clientpid, 0);
345
346     return 1;
347 }
348
349 sub process_packet
350 {
351     my ($self, $server, $packet) = @_;
352     my $len_real;
353     my $decrypt_len;
354     my $data;
355     my $recnum;
356
357     if ($server) {
358         print "Received server packet\n";
359     } else {
360         print "Received client packet\n";
361     }
362
363     print "Packet length = ".length($packet)."\n";
364     print "Processing flight ".$self->flight."\n";
365
366     #Return contains the list of record found in the packet followed by the
367     #list of messages in those records
368     my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet);
369     push @{$self->record_list}, @{$ret[0]};
370     push @{$self->{message_list}}, @{$ret[1]};
371
372     print "\n";
373
374     #Finished parsing. Call user provided filter here
375     if(defined $self->filter) {
376         $self->filter->($self);
377     }
378
379     #Reconstruct the packet
380     $packet = "";
381     foreach my $record (@{$self->record_list}) {
382         #We only replay the records for the current flight
383         if ($record->flight != $self->flight) {
384             next;
385         }
386         $packet .= $record->reconstruct_record($server);
387     }
388
389     $self->{flight} = $self->{flight} + 1;
390
391     print "Forwarded packet length = ".length($packet)."\n\n";
392
393     return $packet;
394 }
395
396 #Read accessors
397 sub execute
398 {
399     my $self = shift;
400     return $self->{execute};
401 }
402 sub cert
403 {
404     my $self = shift;
405     return $self->{cert};
406 }
407 sub debug
408 {
409     my $self = shift;
410     return $self->{debug};
411 }
412 sub flight
413 {
414     my $self = shift;
415     return $self->{flight};
416 }
417 sub record_list
418 {
419     my $self = shift;
420     return $self->{record_list};
421 }
422 sub success
423 {
424     my $self = shift;
425     return $self->{success};
426 }
427 sub end
428 {
429     my $self = shift;
430     return $self->{end};
431 }
432 sub supports_IPv6
433 {
434     my $self = shift;
435     return $have_IPv6;
436 }
437
438 #Read/write accessors
439 sub proxy_addr
440 {
441     my $self = shift;
442     if (@_) {
443         $self->{proxy_addr} = shift;
444     }
445     return $self->{proxy_addr};
446 }
447 sub proxy_port
448 {
449     my $self = shift;
450     if (@_) {
451         $self->{proxy_port} = shift;
452     }
453     return $self->{proxy_port};
454 }
455 sub server_addr
456 {
457     my $self = shift;
458     if (@_) {
459         $self->{server_addr} = shift;
460     }
461     return $self->{server_addr};
462 }
463 sub server_port
464 {
465     my $self = shift;
466     if (@_) {
467         $self->{server_port} = shift;
468     }
469     return $self->{server_port};
470 }
471 sub filter
472 {
473     my $self = shift;
474     if (@_) {
475         $self->{filter} = shift;
476     }
477     return $self->{filter};
478 }
479 sub cipherc
480 {
481     my $self = shift;
482     if (@_) {
483         $self->{cipherc} = shift;
484     }
485     return $self->{cipherc};
486 }
487 sub ciphers
488 {
489     my $self = shift;
490     if (@_) {
491         $self->{ciphers} = shift;
492     }
493     return $self->{ciphers};
494 }
495 sub serverflags
496 {
497     my $self = shift;
498     if (@_) {
499         $self->{serverflags} = shift;
500     }
501     return $self->{serverflags};
502 }
503 sub clientflags
504 {
505     my $self = shift;
506     if (@_) {
507         $self->{clientflags} = shift;
508     }
509     return $self->{clientflags};
510 }
511 sub serverconnects
512 {
513     my $self = shift;
514     if (@_) {
515         $self->{serverconnects} = shift;
516     }
517     return $self->{serverconnects};
518 }
519 # This is a bit ugly because the caller is responsible for keeping the records
520 # in sync with the updated message list; simply updating the message list isn't
521 # sufficient to get the proxy to forward the new message.
522 # But it does the trick for the one test (test_sslsessiontick) that needs it.
523 sub message_list
524 {
525     my $self = shift;
526     if (@_) {
527         $self->{message_list} = shift;
528     }
529     return $self->{message_list};
530 }
531 sub serverpid
532 {
533     my $self = shift;
534     if (@_) {
535         $self->{serverpid} = shift;
536     }
537     return $self->{serverpid};
538 }
539 sub clientpid
540 {
541     my $self = shift;
542     if (@_) {
543         $self->{clientpid} = shift;
544     }
545     return $self->{clientpid};
546 }
547
548 sub fill_known_data
549 {
550     my $length = shift;
551     my $ret = "";
552     for (my $i = 0; $i < $length; $i++) {
553         $ret .= chr($i);
554     }
555     return $ret;
556 }
557
558 sub is_tls13
559 {
560     my $class = shift;
561     if (@_) {
562         $is_tls13 = shift;
563     }
564     return $is_tls13;
565 }
566
567 sub reneg
568 {
569     my $self = shift;
570     if (@_) {
571         $self->{reneg} = shift;
572     }
573     return $self->{reneg};
574 }
575
576 #Setting a sessionfile means that the client will not close until the given
577 #file exists. This is useful in TLSv1.3 where otherwise s_client will close
578 #immediately at the end of the handshake, but before the session has been
579 #received from the server. A side effect of this is that s_client never sends
580 #a close_notify, so instead we consider success to be when it sends application
581 #data over the connection.
582 sub sessionfile
583 {
584     my $self = shift;
585     if (@_) {
586         $self->{sessionfile} = shift;
587         TLSProxy::Message->successondata(1);
588     }
589     return $self->{sessionfile};
590 }
591
592 sub ciphersuite
593 {
594     my $class = shift;
595     if (@_) {
596         $ciphersuite = shift;
597     }
598     return $ciphersuite;
599 }
600
601 1;