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