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