Proxy.pm 12.8 KB
Newer Older
M
Matt Caswell 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
# Written by Matt Caswell for the OpenSSL project.
# ====================================================================
# Copyright (c) 1998-2015 The OpenSSL Project.  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).

use strict;

package TLSProxy::Proxy;

use File::Spec;
use IO::Socket;
use IO::Select;
use TLSProxy::Record;
use TLSProxy::Message;
use TLSProxy::ClientHello;
M
Matt Caswell 已提交
64 65
use TLSProxy::ServerHello;
use TLSProxy::ServerKeyExchange;
E
Emilia Kasper 已提交
66
use TLSProxy::NewSessionTicket;
M
Matt Caswell 已提交
67

68 69 70
my $have_IPv6 = 0;
my $IP_factory;

M
Matt Caswell 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
sub new
{
    my $class = shift;
    my ($filter,
        $execute,
        $cert,
        $debug) = @_;

    my $self = {
        #Public read/write
        proxy_addr => "localhost",
        proxy_port => 4453,
        server_addr => "localhost",
        server_port => 4443,
        filter => $filter,
M
Matt Caswell 已提交
86 87 88
        serverflags => "",
        clientflags => "",
        serverconnects => 1,
M
Matt Caswell 已提交
89 90 91 92 93

        #Public read
        execute => $execute,
        cert => $cert,
        debug => $debug,
M
Matt Caswell 已提交
94 95
        cipherc => "",
        ciphers => "AES128-SHA",
M
Matt Caswell 已提交
96 97 98 99 100
        flight => 0,
        record_list => [],
        message_list => [],
    };

101 102 103 104 105
    # 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.
106
    eval {
107 108
        require IO::Socket::INET6;
        my $s = IO::Socket::INET6->new(
109 110 111 112 113 114 115 116
            LocalAddr => "::1",
            LocalPort => 0,
            Listen=>1,
            );
        $s or die "\n";
        $s->close();
    };
    if ($@ eq "") {
117
        $IP_factory = sub { IO::Socket::INET6->new(@_); };
118 119 120
        $have_IPv6 = 1;
    } else {
        eval {
121 122
            require IO::Socket::IP;
            my $s = IO::Socket::IP->new(
123 124 125 126 127 128 129 130
                LocalAddr => "::1",
                LocalPort => 0,
                Listen=>1,
                );
            $s or die "\n";
            $s->close();
        };
        if ($@ eq "") {
131
            $IP_factory = sub { IO::Socket::IP->new(@_); };
132 133 134 135 136 137
            $have_IPv6 = 1;
        } else {
            $IP_factory = sub { IO::Socket::INET->new(@_); };
        }
    }

M
Matt Caswell 已提交
138 139 140 141 142 143 144
    return bless $self, $class;
}

sub clear
{
    my $self = shift;

M
Matt Caswell 已提交
145 146
    $self->{cipherc} = "";
    $self->{ciphers} = "AES128-SHA";
M
Matt Caswell 已提交
147 148 149
    $self->{flight} = 0;
    $self->{record_list} = [];
    $self->{message_list} = [];
M
Matt Caswell 已提交
150 151 152
    $self->{serverflags} = "";
    $self->{clientflags} = "";
    $self->{serverconnects} = 1;
M
Matt Caswell 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165

    TLSProxy::Message->clear();
    TLSProxy::Record->clear();
}

sub restart
{
    my $self = shift;

    $self->clear;
    $self->start;
}

M
Matt Caswell 已提交
166 167 168 169 170 171 172 173
sub clientrestart
{
    my $self = shift;

    $self->clear;
    $self->clientstart;
}

M
Matt Caswell 已提交
174 175 176 177 178 179 180
sub start
{
    my ($self) = shift;
    my $pid;

    $pid = fork();
    if ($pid == 0) {
181 182 183 184 185
        if (!$self->debug) {
            open(STDOUT, ">", File::Spec->devnull())
                or die "Failed to redirect stdout: $!";
            open(STDERR, ">&STDOUT");
        }
186
        my $execcmd = $self->execute
187
            ." s_server -no_comp -rev -engine ossltest -accept "
M
Matt Caswell 已提交
188
            .($self->server_port)
M
Matt Caswell 已提交
189
            ." -cert ".$self->cert." -naccept ".$self->serverconnects;
M
Matt Caswell 已提交
190 191 192
        if ($self->ciphers ne "") {
            $execcmd .= " -cipher ".$self->ciphers;
        }
M
Matt Caswell 已提交
193 194 195
        if ($self->serverflags ne "") {
            $execcmd .= " ".$self->serverflags;
        }
M
Matt Caswell 已提交
196
        exec($execcmd);
M
Matt Caswell 已提交
197 198
    }

M
Matt Caswell 已提交
199 200 201 202 203 204
    $self->clientstart;
}

sub clientstart
{
    my ($self) = shift;
M
Matt Caswell 已提交
205 206 207
    my $oldstdout;

    if(!$self->debug) {
R
Richard Levitte 已提交
208 209
        open DEVNULL, ">", File::Spec->devnull();
        $oldstdout = select(DEVNULL);
M
Matt Caswell 已提交
210 211 212
    }

    # Create the Proxy socket
213
    my $proxaddr = $self->proxy_addr;
214 215 216
    $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
    my $proxy_sock = $IP_factory->(
        LocalHost   => $proxaddr,
M
Matt Caswell 已提交
217 218 219
        LocalPort   => $self->proxy_port,
        Proto       => "tcp",
        Listen      => SOMAXCONN,
220
        ReuseAddr   => 1
M
Matt Caswell 已提交
221 222 223 224 225
    );

    if ($proxy_sock) {
        print "Proxy started on port ".$self->proxy_port."\n";
    } else {
226
        die "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
M
Matt Caswell 已提交
227 228 229 230 231
    }

    if ($self->execute) {
        my $pid = fork();
        if ($pid == 0) {
232 233 234 235 236
            if (!$self->debug) {
                open(STDOUT, ">", File::Spec->devnull())
                    or die "Failed to redirect stdout: $!";
                open(STDERR, ">&STDOUT");
            }
237
            my $execcmd = "echo test | ".$self->execute
238
                 ." s_client -engine ossltest -connect "
M
Matt Caswell 已提交
239 240 241 242
                 .($self->proxy_addr).":".($self->proxy_port);
            if ($self->cipherc ne "") {
                $execcmd .= " -cipher ".$self->cipherc;
            }
M
Matt Caswell 已提交
243 244 245
            if ($self->clientflags ne "") {
                $execcmd .= " ".$self->clientflags;
            }
M
Matt Caswell 已提交
246
            exec($execcmd);
M
Matt Caswell 已提交
247 248 249 250
        }
    }

    # Wait for incoming connection from client
251 252
    my $client_sock = $proxy_sock->accept()
        or die "Failed accepting incoming connection: $!\n";
M
Matt Caswell 已提交
253 254 255 256 257 258 259 260 261

    print "Connection opened\n";

    # Now connect to the server
    my $retry = 3;
    my $server_sock;
    #We loop over this a few times because sometimes s_server can take a while
    #to start up
    do {
262 263 264 265
        my $servaddr = $self->server_addr;
        $servaddr =~ s/[\[\]]//g; # Remove [ and ]
        $server_sock = $IP_factory->(
            PeerAddr => $servaddr,
M
Matt Caswell 已提交
266
            PeerPort => $self->server_port,
267
            MultiHomed => 1,
M
Matt Caswell 已提交
268
            Proto => 'tcp'
269
        );
M
Matt Caswell 已提交
270 271 272 273 274 275 276

        $retry--;
        if (!$server_sock) {
            if ($retry) {
                #Sleep for a short while
                select(undef, undef, undef, 0.1);
            } else {
277
                die "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
M
Matt Caswell 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
            }
        }
    } while (!$server_sock);

    my $sel = IO::Select->new($server_sock, $client_sock);
    my $indata;
    my @handles = ($server_sock, $client_sock);

    #Wait for either the server socket or the client socket to become readable
    my @ready;
    while(!(TLSProxy::Message->end) && (@ready = $sel->can_read)) {
        foreach my $hand (@ready) {
            if ($hand == $server_sock) {
                $server_sock->sysread($indata, 16384) or goto END;
                $indata = $self->process_packet(1, $indata);
                $client_sock->syswrite($indata);
            } elsif ($hand == $client_sock) {
                $client_sock->sysread($indata, 16384) or goto END;
                $indata = $self->process_packet(0, $indata);
                $server_sock->syswrite($indata);
            } else {
                print "Err\n";
                goto END;
            }
        }
    }

    END:
    print "Connection closed\n";
    if($server_sock) {
        $server_sock->close();
    }
    if($client_sock) {
        #Closing this also kills the child process
        $client_sock->close();
    }
    if($proxy_sock) {
        $proxy_sock->close();
    }
    if(!$self->debug) {
        select($oldstdout);
    }
}

sub process_packet
{
    my ($self, $server, $packet) = @_;
    my $len_real;
    my $decrypt_len;
    my $data;
    my $recnum;

    if ($server) {
        print "Received server packet\n";
    } else {
        print "Received client packet\n";
    }

    print "Packet length = ".length($packet)."\n";
    print "Processing flight ".$self->flight."\n";

    #Return contains the list of record found in the packet followed by the
    #list of messages in those records
    my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet);
    push @{$self->record_list}, @{$ret[0]};
    push @{$self->{message_list}}, @{$ret[1]};

    print "\n";

    #Finished parsing. Call user provided filter here
M
Matt Caswell 已提交
348 349 350
    if(defined $self->filter) {
        $self->filter->($self);
    }
M
Matt Caswell 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

    #Reconstruct the packet
    $packet = "";
    foreach my $record (@{$self->record_list}) {
        #We only replay the records for the current flight
        if ($record->flight != $self->flight) {
            next;
        }
        $packet .= $record->reconstruct_record();
    }

    $self->{flight} = $self->{flight} + 1;

    print "Forwarded packet length = ".length($packet)."\n\n";

    return $packet;
}

#Read accessors
sub execute
{
    my $self = shift;
    return $self->{execute};
}
sub cert
{
    my $self = shift;
    return $self->{cert};
}
sub debug
{
    my $self = shift;
    return $self->{debug};
}
sub flight
{
    my $self = shift;
    return $self->{flight};
}
sub record_list
{
    my $self = shift;
    return $self->{record_list};
}
sub success
{
    my $self = shift;
    return $self->{success};
}
sub end
{
    my $self = shift;
    return $self->{end};
}
405 406 407 408 409
sub supports_IPv6
{
    my $self = shift;
    return $have_IPv6;
}
M
Matt Caswell 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

#Read/write accessors
sub proxy_addr
{
    my $self = shift;
    if (@_) {
      $self->{proxy_addr} = shift;
    }
    return $self->{proxy_addr};
}
sub proxy_port
{
    my $self = shift;
    if (@_) {
      $self->{proxy_port} = shift;
    }
    return $self->{proxy_port};
}
sub server_addr
{
    my $self = shift;
    if (@_) {
      $self->{server_addr} = shift;
    }
    return $self->{server_addr};
}
sub server_port
{
    my $self = shift;
    if (@_) {
      $self->{server_port} = shift;
    }
    return $self->{server_port};
}
sub filter
{
    my $self = shift;
    if (@_) {
      $self->{filter} = shift;
    }
    return $self->{filter};
}
M
Matt Caswell 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
sub cipherc
{
    my $self = shift;
    if (@_) {
      $self->{cipherc} = shift;
    }
    return $self->{cipherc};
}
sub ciphers
{
    my $self = shift;
    if (@_) {
      $self->{ciphers} = shift;
    }
    return $self->{ciphers};
}
M
Matt Caswell 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
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};
}
492 493 494 495 496 497 498 499 500 501 502 503
# 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};
}
M
Matt Caswell 已提交
504
1;