Print <ABSENT> if a STACK is NULL.
[openssl.git] / util / TLSProxy / Proxy.pm
index c033c29dd7da661d9329702b486968159fea021f..eeb83ed74f88950c1f67dabde9276fe5993a8eda 100644 (file)
@@ -1,57 +1,12 @@
-# Written by Matt Caswell for the OpenSSL project.
-# ====================================================================
-# Copyright (c) 1998-2015 The OpenSSL Project.  All rights reserved.
+# Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
 #
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# 1. Redistributions of source code must retain the above copyright
-#    notice, this list of conditions and the following disclaimer.
-#
-# 2. Redistributions in binary form must reproduce the above copyright
-#    notice, this list of conditions and the following disclaimer in
-#    the documentation and/or other materials provided with the
-#    distribution.
-#
-# 3. All advertising materials mentioning features or use of this
-#    software must display the following acknowledgment:
-#    "This product includes software developed by the OpenSSL Project
-#    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
-#
-# 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
-#    endorse or promote products derived from this software without
-#    prior written permission. For written permission, please contact
-#    openssl-core@openssl.org.
-#
-# 5. Products derived from this software may not be called "OpenSSL"
-#    nor may "OpenSSL" appear in their names without prior written
-#    permission of the OpenSSL Project.
-#
-# 6. Redistributions of any form whatsoever must retain the following
-#    acknowledgment:
-#    "This product includes software developed by the OpenSSL Project
-#    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
-#
-# THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
-# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
-# ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-# OF THE POSSIBILITY OF SUCH DAMAGE.
-# ====================================================================
-#
-# This product includes cryptographic software written by Eric Young
-# (eay@cryptsoft.com).  This product includes software written by Tim
-# Hudson (tjh@cryptsoft.com).
+# Licensed under the OpenSSL license (the "License").  You may not use
+# this file except in compliance with the License.  You can obtain a copy
+# in the file LICENSE in the source distribution or at
+# https://www.openssl.org/source/license.html
 
 use strict;
+use POSIX ":sys_wait_h";
 
 package TLSProxy::Proxy;
 
@@ -63,6 +18,10 @@ use TLSProxy::Message;
 use TLSProxy::ClientHello;
 use TLSProxy::ServerHello;
 use TLSProxy::ServerKeyExchange;
+use TLSProxy::NewSessionTicket;
+
+my $have_IPv6 = 0;
+my $IP_factory;
 
 sub new
 {
@@ -79,39 +38,87 @@ sub new
         server_addr => "localhost",
         server_port => 4443,
         filter => $filter,
+        serverflags => "",
+        clientflags => "",
+        serverconnects => 1,
+        serverpid => 0,
 
         #Public read
         execute => $execute,
         cert => $cert,
         debug => $debug,
-        cipherc => "AES128-SHA",
-        ciphers => "",
+        cipherc => "",
+        ciphers => "AES128-SHA",
         flight => 0,
         record_list => [],
         message_list => [],
+    };
 
-        #Private
-        message_rec_list => []
+    # IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
+    # However, IO::Socket::INET6 is older and is said to be more widely
+    # deployed for the moment, and may have less bugs, so we try the latter
+    # first, then fall back on the code modules.  Worst case scenario, we
+    # fall back to IO::Socket::INET, only supports IPv4.
+    eval {
+        require IO::Socket::INET6;
+        my $s = IO::Socket::INET6->new(
+            LocalAddr => "::1",
+            LocalPort => 0,
+            Listen=>1,
+            );
+        $s or die "\n";
+        $s->close();
     };
+    if ($@ eq "") {
+        $IP_factory = sub { IO::Socket::INET6->new(@_); };
+        $have_IPv6 = 1;
+    } else {
+        eval {
+            require IO::Socket::IP;
+            my $s = IO::Socket::IP->new(
+                LocalAddr => "::1",
+                LocalPort => 0,
+                Listen=>1,
+                );
+            $s or die "\n";
+            $s->close();
+        };
+        if ($@ eq "") {
+            $IP_factory = sub { IO::Socket::IP->new(@_); };
+            $have_IPv6 = 1;
+        } else {
+            $IP_factory = sub { IO::Socket::INET->new(@_); };
+        }
+    }
 
     return bless $self, $class;
 }
 
-sub clear
+sub clearClient
 {
     my $self = shift;
 
-    $self->{cipherc} = "AES128-SHA";
-    $self->{ciphers} = "";
+    $self->{cipherc} = "";
     $self->{flight} = 0;
     $self->{record_list} = [];
     $self->{message_list} = [];
-    $self->{message_rec_list} = [];
+    $self->{clientflags} = "";
 
     TLSProxy::Message->clear();
     TLSProxy::Record->clear();
 }
 
+sub clear
+{
+    my $self = shift;
+
+    $self->clearClient;
+    $self->{ciphers} = "AES128-SHA";
+    $self->{serverflags} = "";
+    $self->{serverconnects} = 1;
+    $self->{serverpid} = 0;
+}
+
 sub restart
 {
     my $self = shift;
@@ -120,6 +127,14 @@ sub restart
     $self->start;
 }
 
+sub clientrestart
+{
+    my $self = shift;
+
+    $self->clear;
+    $self->clientstart;
+}
+
 sub start
 {
     my ($self) = shift;
@@ -127,58 +142,83 @@ sub start
 
     $pid = fork();
     if ($pid == 0) {
-        open(STDOUT, ">", File::Spec->devnull())
-            or die "Failed to redirect stdout";
-        open(STDERR, ">&STDOUT");
-        my $execcmd = $self->execute." s_server -engine ossltest -accept "
+        if (!$self->debug) {
+            open(STDOUT, ">", File::Spec->devnull())
+                or die "Failed to redirect stdout: $!";
+            open(STDERR, ">&STDOUT");
+        }
+        my $execcmd = $self->execute
+            ." s_server -no_comp -rev -engine ossltest -accept "
             .($self->server_port)
-            ." -cert ".$self->cert." -naccept 1";
+            ." -cert ".$self->cert." -naccept ".$self->serverconnects;
         if ($self->ciphers ne "") {
             $execcmd .= " -cipher ".$self->ciphers;
         }
+        if ($self->serverflags ne "") {
+            $execcmd .= " ".$self->serverflags;
+        }
         exec($execcmd);
     }
+    $self->serverpid($pid);
+
+    return $self->clientstart;
+}
 
+sub clientstart
+{
+    my ($self) = shift;
     my $oldstdout;
 
     if(!$self->debug) {
-        $oldstdout = select(File::Spec->devnull());
+        open DEVNULL, ">", File::Spec->devnull();
+        $oldstdout = select(DEVNULL);
     }
 
     # Create the Proxy socket
-    my $proxy_sock = new IO::Socket::INET(
-        LocalHost   => $self->proxy_addr,
+    my $proxaddr = $self->proxy_addr;
+    $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
+    my $proxy_sock = $IP_factory->(
+        LocalHost   => $proxaddr,
         LocalPort   => $self->proxy_port,
         Proto       => "tcp",
         Listen      => SOMAXCONN,
-        Reuse       => 1
+        ReuseAddr   => 1
     );
 
     if ($proxy_sock) {
         print "Proxy started on port ".$self->proxy_port."\n";
     } else {
-        die "Failed creating proxy socket\n";
+        warn "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
+        return 0;
     }
 
     if ($self->execute) {
         my $pid = fork();
         if ($pid == 0) {
-            open(STDOUT, ">", File::Spec->devnull())
-                or die "Failed to redirect stdout";
-            open(STDERR, ">&STDOUT");
-            my $execcmd = $self->execute
+            if (!$self->debug) {
+                open(STDOUT, ">", File::Spec->devnull())
+                    or die "Failed to redirect stdout: $!";
+                open(STDERR, ">&STDOUT");
+            }
+            my $execcmd = "echo test | ".$self->execute
                  ." s_client -engine ossltest -connect "
                  .($self->proxy_addr).":".($self->proxy_port);
             if ($self->cipherc ne "") {
                 $execcmd .= " -cipher ".$self->cipherc;
             }
+            if ($self->clientflags ne "") {
+                $execcmd .= " ".$self->clientflags;
+            }
             exec($execcmd);
         }
     }
 
     # Wait for incoming connection from client
-    my $client_sock = $proxy_sock->accept() 
-        or die "Failed accepting incoming connection\n";
+    my $client_sock;
+    if(!($client_sock = $proxy_sock->accept())) {
+        warn "Failed accepting incoming connection: $!\n";
+        return 0;
+    }
 
     print "Connection opened\n";
 
@@ -188,19 +228,29 @@ sub start
     #We loop over this a few times because sometimes s_server can take a while
     #to start up
     do {
-        $server_sock = new IO::Socket::INET(
-            PeerAddr => $self->server_addr,
-            PeerPort => $self->server_port,
-            Proto => 'tcp'
-        ); 
+        my $servaddr = $self->server_addr;
+        $servaddr =~ s/[\[\]]//g; # Remove [ and ]
+        eval {
+            $server_sock = $IP_factory->(
+                PeerAddr => $servaddr,
+                PeerPort => $self->server_port,
+                MultiHomed => 1,
+                Proto => 'tcp'
+            );
+        };
 
         $retry--;
-        if (!$server_sock) {
+        #Some buggy IP factories can return a defined server_sock that hasn't
+        #actually connected, so we check peerport too
+        if ($@ || !defined($server_sock) || !defined($server_sock->peerport)) {
+            $server_sock->close() if defined($server_sock);
+            undef $server_sock;
             if ($retry) {
                 #Sleep for a short while
                 select(undef, undef, undef, 0.1);
             } else {
-                die "Failed to start up server\n";
+                warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
+                return 0;
             }
         }
     } while (!$server_sock);
@@ -243,9 +293,16 @@ sub start
     if(!$self->debug) {
         select($oldstdout);
     }
+    $self->serverconnects($self->serverconnects - 1);
+    if ($self->serverconnects == 0) {
+        die "serverpid is zero\n" if $self->serverpid == 0;
+        print "Waiting for server process to close: "
+              .$self->serverpid."\n";
+        waitpid( $self->serverpid, 0);
+    }
+    return 1;
 }
 
-
 sub process_packet
 {
     my ($self, $server, $packet) = @_;
@@ -267,13 +324,14 @@ sub process_packet
     #list of messages in those records
     my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet);
     push @{$self->record_list}, @{$ret[0]};
-    $self->{message_rec_list} = $ret[0];
     push @{$self->{message_list}}, @{$ret[1]};
 
     print "\n";
 
     #Finished parsing. Call user provided filter here
-    $self->filter->($self);
+    if(defined $self->filter) {
+        $self->filter->($self);
+    }
 
     #Reconstruct the packet
     $packet = "";
@@ -318,11 +376,6 @@ sub record_list
     my $self = shift;
     return $self->{record_list};
 }
-sub message_list
-{
-    my $self = shift;
-    return $self->{message_list};
-}
 sub success
 {
     my $self = shift;
@@ -333,6 +386,11 @@ sub end
     my $self = shift;
     return $self->{end};
 }
+sub supports_IPv6
+{
+    my $self = shift;
+    return $have_IPv6;
+}
 
 #Read/write accessors
 sub proxy_addr
@@ -391,4 +449,59 @@ sub ciphers
     }
     return $self->{ciphers};
 }
+sub serverflags
+{
+    my $self = shift;
+    if (@_) {
+      $self->{serverflags} = shift;
+    }
+    return $self->{serverflags};
+}
+sub clientflags
+{
+    my $self = shift;
+    if (@_) {
+      $self->{clientflags} = shift;
+    }
+    return $self->{clientflags};
+}
+sub serverconnects
+{
+    my $self = shift;
+    if (@_) {
+      $self->{serverconnects} = shift;
+    }
+    return $self->{serverconnects};
+}
+# This is a bit ugly because the caller is responsible for keeping the records
+# in sync with the updated message list; simply updating the message list isn't
+# sufficient to get the proxy to forward the new message.
+# But it does the trick for the one test (test_sslsessiontick) that needs it.
+sub message_list
+{
+    my $self = shift;
+    if (@_) {
+        $self->{message_list} = shift;
+    }
+    return $self->{message_list};
+}
+sub serverpid
+{
+    my $self = shift;
+    if (@_) {
+      $self->{serverpid} = shift;
+    }
+    return $self->{serverpid};
+}
+
+sub fill_known_data
+{
+    my $length = shift;
+    my $ret = "";
+    for (my $i = 0; $i < $length; $i++) {
+        $ret .= chr($i);
+    }
+    return $ret;
+}
+
 1;