Proxy.pm 12.3 KB
Newer Older
1
# Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
M
Matt Caswell 已提交
2
#
3 4 5 6
# 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
M
Matt Caswell 已提交
7 8

use strict;
M
Matt Caswell 已提交
9
use POSIX ":sys_wait_h";
M
Matt Caswell 已提交
10 11 12 13 14 15 16 17 18

package TLSProxy::Proxy;

use File::Spec;
use IO::Socket;
use IO::Select;
use TLSProxy::Record;
use TLSProxy::Message;
use TLSProxy::ClientHello;
M
Matt Caswell 已提交
19
use TLSProxy::ServerHello;
M
Matt Caswell 已提交
20
use TLSProxy::EncryptedExtensions;
M
Matt Caswell 已提交
21
use TLSProxy::ServerKeyExchange;
E
Emilia Kasper 已提交
22
use TLSProxy::NewSessionTicket;
M
Matt Caswell 已提交
23

24 25 26
my $have_IPv6 = 0;
my $IP_factory;

M
Matt Caswell 已提交
27 28
my $is_tls13 = 0;

M
Matt Caswell 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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 已提交
44 45 46
        serverflags => "",
        clientflags => "",
        serverconnects => 1,
M
Matt Caswell 已提交
47
        serverpid => 0,
M
Matt Caswell 已提交
48
        reneg => 0,
M
Matt Caswell 已提交
49 50 51 52 53

        #Public read
        execute => $execute,
        cert => $cert,
        debug => $debug,
M
Matt Caswell 已提交
54
        cipherc => "",
M
Matt Caswell 已提交
55
        ciphers => "AES128-SHA:TLS13-AES-128-GCM-SHA256",
M
Matt Caswell 已提交
56 57 58 59 60
        flight => 0,
        record_list => [],
        message_list => [],
    };

61 62 63 64 65
    # 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.
66
    eval {
67 68
        require IO::Socket::INET6;
        my $s = IO::Socket::INET6->new(
69 70 71 72 73 74 75 76
            LocalAddr => "::1",
            LocalPort => 0,
            Listen=>1,
            );
        $s or die "\n";
        $s->close();
    };
    if ($@ eq "") {
77
        $IP_factory = sub { IO::Socket::INET6->new(@_); };
78 79 80
        $have_IPv6 = 1;
    } else {
        eval {
81 82
            require IO::Socket::IP;
            my $s = IO::Socket::IP->new(
83 84 85 86 87 88 89 90
                LocalAddr => "::1",
                LocalPort => 0,
                Listen=>1,
                );
            $s or die "\n";
            $s->close();
        };
        if ($@ eq "") {
91
            $IP_factory = sub { IO::Socket::IP->new(@_); };
92 93 94 95 96 97
            $have_IPv6 = 1;
        } else {
            $IP_factory = sub { IO::Socket::INET->new(@_); };
        }
    }

M
Matt Caswell 已提交
98 99 100
    return bless $self, $class;
}

M
Matt Caswell 已提交
101
sub clearClient
M
Matt Caswell 已提交
102 103 104
{
    my $self = shift;

M
Matt Caswell 已提交
105
    $self->{cipherc} = "";
M
Matt Caswell 已提交
106 107 108
    $self->{flight} = 0;
    $self->{record_list} = [];
    $self->{message_list} = [];
M
Matt Caswell 已提交
109
    $self->{clientflags} = "";
M
Matt Caswell 已提交
110
    $is_tls13 = 0;
M
Matt Caswell 已提交
111 112 113 114 115

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

M
Matt Caswell 已提交
116 117 118 119 120
sub clear
{
    my $self = shift;

    $self->clearClient;
M
Matt Caswell 已提交
121
    $self->{ciphers} = "AES128-SHA:TLS13-AES-128-GCM-SHA256";
M
Matt Caswell 已提交
122 123 124
    $self->{serverflags} = "";
    $self->{serverconnects} = 1;
    $self->{serverpid} = 0;
M
Matt Caswell 已提交
125
    $self->{reneg} = 0;
M
Matt Caswell 已提交
126 127
}

M
Matt Caswell 已提交
128 129 130 131 132 133 134 135
sub restart
{
    my $self = shift;

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

M
Matt Caswell 已提交
136 137 138 139 140 141 142 143
sub clientrestart
{
    my $self = shift;

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

M
Matt Caswell 已提交
144 145 146 147 148 149 150
sub start
{
    my ($self) = shift;
    my $pid;

    $pid = fork();
    if ($pid == 0) {
151 152 153 154 155
        if (!$self->debug) {
            open(STDOUT, ">", File::Spec->devnull())
                or die "Failed to redirect stdout: $!";
            open(STDERR, ">&STDOUT");
        }
156
        my $execcmd = $self->execute
M
Matt Caswell 已提交
157
            ." s_server -no_comp -rev -engine ossltest -accept "
M
Matt Caswell 已提交
158
            .($self->server_port)
M
Matt Caswell 已提交
159 160
            ." -cert ".$self->cert." -cert2 ".$self->cert
            ." -naccept ".$self->serverconnects;
M
Matt Caswell 已提交
161 162 163
        if ($self->ciphers ne "") {
            $execcmd .= " -cipher ".$self->ciphers;
        }
M
Matt Caswell 已提交
164 165 166
        if ($self->serverflags ne "") {
            $execcmd .= " ".$self->serverflags;
        }
M
Matt Caswell 已提交
167
        exec($execcmd);
M
Matt Caswell 已提交
168
    }
M
Matt Caswell 已提交
169
    $self->serverpid($pid);
M
Matt Caswell 已提交
170

171
    return $self->clientstart;
M
Matt Caswell 已提交
172 173 174 175 176
}

sub clientstart
{
    my ($self) = shift;
M
Matt Caswell 已提交
177 178 179
    my $oldstdout;

    if(!$self->debug) {
R
Richard Levitte 已提交
180 181
        open DEVNULL, ">", File::Spec->devnull();
        $oldstdout = select(DEVNULL);
M
Matt Caswell 已提交
182 183 184
    }

    # Create the Proxy socket
185
    my $proxaddr = $self->proxy_addr;
186 187 188
    $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
    my $proxy_sock = $IP_factory->(
        LocalHost   => $proxaddr,
M
Matt Caswell 已提交
189 190 191
        LocalPort   => $self->proxy_port,
        Proto       => "tcp",
        Listen      => SOMAXCONN,
192
        ReuseAddr   => 1
M
Matt Caswell 已提交
193 194 195 196 197
    );

    if ($proxy_sock) {
        print "Proxy started on port ".$self->proxy_port."\n";
    } else {
198 199
        warn "Failed creating proxy socket (".$proxaddr.",".$self->proxy_port."): $!\n";
        return 0;
M
Matt Caswell 已提交
200 201 202 203 204
    }

    if ($self->execute) {
        my $pid = fork();
        if ($pid == 0) {
205 206 207 208 209
            if (!$self->debug) {
                open(STDOUT, ">", File::Spec->devnull())
                    or die "Failed to redirect stdout: $!";
                open(STDERR, ">&STDOUT");
            }
M
Matt Caswell 已提交
210 211 212 213 214 215 216
            my $echostr;
            if ($self->reneg()) {
                $echostr = "R";
            } else {
                $echostr = "test";
            }
            my $execcmd = "echo ".$echostr." | ".$self->execute
217
                 ." s_client -engine ossltest -connect "
M
Matt Caswell 已提交
218 219 220 221
                 .($self->proxy_addr).":".($self->proxy_port);
            if ($self->cipherc ne "") {
                $execcmd .= " -cipher ".$self->cipherc;
            }
M
Matt Caswell 已提交
222 223 224
            if ($self->clientflags ne "") {
                $execcmd .= " ".$self->clientflags;
            }
M
Matt Caswell 已提交
225
            exec($execcmd);
M
Matt Caswell 已提交
226 227 228 229
        }
    }

    # Wait for incoming connection from client
230 231 232 233 234
    my $client_sock;
    if(!($client_sock = $proxy_sock->accept())) {
        warn "Failed accepting incoming connection: $!\n";
        return 0;
    }
M
Matt Caswell 已提交
235 236 237 238 239 240 241 242 243

    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 {
244 245
        my $servaddr = $self->server_addr;
        $servaddr =~ s/[\[\]]//g; # Remove [ and ]
246 247 248 249 250 251 252 253
        eval {
            $server_sock = $IP_factory->(
                PeerAddr => $servaddr,
                PeerPort => $self->server_port,
                MultiHomed => 1,
                Proto => 'tcp'
            );
        };
M
Matt Caswell 已提交
254 255

        $retry--;
M
Matt Caswell 已提交
256 257 258
        #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)) {
259 260
            $server_sock->close() if defined($server_sock);
            undef $server_sock;
M
Matt Caswell 已提交
261 262 263 264
            if ($retry) {
                #Sleep for a short while
                select(undef, undef, undef, 0.1);
            } else {
265 266
                warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
                return 0;
M
Matt Caswell 已提交
267 268 269 270 271 272 273 274 275 276 277 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
            }
        }
    } 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);
    }
M
Matt Caswell 已提交
309 310 311 312 313 314 315
    $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);
    }
316
    return 1;
M
Matt Caswell 已提交
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
}

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 已提交
345 346 347
    if(defined $self->filter) {
        $self->filter->($self);
    }
M
Matt Caswell 已提交
348 349 350 351 352 353 354 355

    #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;
        }
356
        $packet .= $record->reconstruct_record($server);
M
Matt Caswell 已提交
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
    }

    $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};
}
402 403 404 405 406
sub supports_IPv6
{
    my $self = shift;
    return $have_IPv6;
}
M
Matt Caswell 已提交
407 408 409 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

#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 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
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 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
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};
}
489 490 491 492 493 494 495 496 497 498 499 500
# 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 已提交
501 502 503 504 505 506 507 508
sub serverpid
{
    my $self = shift;
    if (@_) {
      $self->{serverpid} = shift;
    }
    return $self->{serverpid};
}
D
David Benjamin 已提交
509 510 511 512 513 514 515 516 517 518

sub fill_known_data
{
    my $length = shift;
    my $ret = "";
    for (my $i = 0; $i < $length; $i++) {
        $ret .= chr($i);
    }
    return $ret;
}
M
Matt Caswell 已提交
519

M
Matt Caswell 已提交
520 521 522 523 524 525 526 527
sub is_tls13
{
    my $class = shift;
    if (@_) {
      $is_tls13 = shift;
    }
    return $is_tls13;
}
M
Matt Caswell 已提交
528 529 530 531 532 533 534 535 536 537

sub reneg
{
    my $self = shift;
    if (@_) {
      $self->{reneg} = shift;
    }
    return $self->{reneg};
}

M
Matt Caswell 已提交
538
1;