Proxy.pm 14.1 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;
21
use TLSProxy::Certificate;
22
use TLSProxy::CertificateVerify;
M
Matt Caswell 已提交
23
use TLSProxy::ServerKeyExchange;
E
Emilia Kasper 已提交
24
use TLSProxy::NewSessionTicket;
M
Matt Caswell 已提交
25
use Time::HiRes qw/usleep/;
M
Matt Caswell 已提交
26

27 28 29
my $have_IPv6 = 0;
my $IP_factory;

M
Matt Caswell 已提交
30
my $is_tls13 = 0;
31
my $ciphersuite = undef;
M
Matt Caswell 已提交
32

M
Matt Caswell 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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 已提交
48 49 50
        serverflags => "",
        clientflags => "",
        serverconnects => 1,
M
Matt Caswell 已提交
51
        serverpid => 0,
M
Matt Caswell 已提交
52
        clientpid => 0,
M
Matt Caswell 已提交
53
        reneg => 0,
54
        sessionfile => undef,
M
Matt Caswell 已提交
55 56 57 58 59

        #Public read
        execute => $execute,
        cert => $cert,
        debug => $debug,
M
Matt Caswell 已提交
60
        cipherc => "",
M
Matt Caswell 已提交
61
        ciphers => "AES128-SHA:TLS13-AES-128-GCM-SHA256",
M
Matt Caswell 已提交
62 63 64 65 66
        flight => 0,
        record_list => [],
        message_list => [],
    };

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

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    # Create the Proxy socket
    my $proxaddr = $self->{proxy_addr};
    $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
    my @proxyargs = (
        LocalHost   => $proxaddr,
        LocalPort   => $self->{proxy_port},
        Proto       => "tcp",
        Listen      => SOMAXCONN,
       );
    push @proxyargs, ReuseAddr => 1
        unless $^O eq "MSWin32";
    $self->{proxy_sock} = $IP_factory->(@proxyargs);

    if ($self->{proxy_sock}) {
        print "Proxy started on port ".$self->{proxy_port}."\n";
    } else {
        warn "Failed creating proxy socket (".$proxaddr.",".$self->{proxy_port}."): $!\n";
    }

M
Matt Caswell 已提交
123 124 125
    return bless $self, $class;
}

126 127 128 129 130 131 132
sub DESTROY
{
    my $self = shift;

    $self->{proxy_sock}->close() if $self->{proxy_sock};
}

M
Matt Caswell 已提交
133
sub clearClient
M
Matt Caswell 已提交
134 135 136
{
    my $self = shift;

M
Matt Caswell 已提交
137
    $self->{cipherc} = "";
M
Matt Caswell 已提交
138 139 140
    $self->{flight} = 0;
    $self->{record_list} = [];
    $self->{message_list} = [];
M
Matt Caswell 已提交
141
    $self->{clientflags} = "";
142
    $self->{sessionfile} = undef;
M
Matt Caswell 已提交
143
    $self->{clientpid} = 0;
M
Matt Caswell 已提交
144
    $is_tls13 = 0;
145
    $ciphersuite = undef;
M
Matt Caswell 已提交
146 147 148 149 150

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

M
Matt Caswell 已提交
151 152 153 154 155
sub clear
{
    my $self = shift;

    $self->clearClient;
M
Matt Caswell 已提交
156
    $self->{ciphers} = "AES128-SHA:TLS13-AES-128-GCM-SHA256";
M
Matt Caswell 已提交
157 158 159
    $self->{serverflags} = "";
    $self->{serverconnects} = 1;
    $self->{serverpid} = 0;
M
Matt Caswell 已提交
160
    $self->{reneg} = 0;
M
Matt Caswell 已提交
161 162
}

M
Matt Caswell 已提交
163 164 165 166 167 168 169 170
sub restart
{
    my $self = shift;

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

M
Matt Caswell 已提交
171 172 173 174 175 176 177 178
sub clientrestart
{
    my $self = shift;

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

M
Matt Caswell 已提交
179 180 181 182 183
sub start
{
    my ($self) = shift;
    my $pid;

184 185 186 187
    if ($self->{proxy_sock} == 0) {
        return 0;
    }

M
Matt Caswell 已提交
188 189
    $pid = fork();
    if ($pid == 0) {
190
        my $execcmd = $self->execute
M
Matt Caswell 已提交
191
            ." s_server -no_comp -rev -engine ossltest -accept "
M
Matt Caswell 已提交
192
            .($self->server_port)
M
Matt Caswell 已提交
193 194
            ." -cert ".$self->cert." -cert2 ".$self->cert
            ." -naccept ".$self->serverconnects;
195 196 197
        unless ($self->supports_IPv6) {
            $execcmd .= " -4";
        }
M
Matt Caswell 已提交
198 199 200
        if ($self->ciphers ne "") {
            $execcmd .= " -cipher ".$self->ciphers;
        }
M
Matt Caswell 已提交
201 202 203
        if ($self->serverflags ne "") {
            $execcmd .= " ".$self->serverflags;
        }
204 205 206
        if ($self->debug) {
            print STDERR "Server command: $execcmd\n";
        }
M
Matt Caswell 已提交
207
        exec($execcmd);
M
Matt Caswell 已提交
208
    }
M
Matt Caswell 已提交
209
    $self->serverpid($pid);
M
Matt Caswell 已提交
210

211
    return $self->clientstart;
M
Matt Caswell 已提交
212 213 214 215 216
}

sub clientstart
{
    my ($self) = shift;
M
Matt Caswell 已提交
217 218 219 220 221
    my $oldstdout;

    if ($self->execute) {
        my $pid = fork();
        if ($pid == 0) {
M
Matt Caswell 已提交
222 223 224 225 226 227 228
            my $echostr;
            if ($self->reneg()) {
                $echostr = "R";
            } else {
                $echostr = "test";
            }
            my $execcmd = "echo ".$echostr." | ".$self->execute
229
                 ." s_client -engine ossltest -connect "
M
Matt Caswell 已提交
230
                 .($self->proxy_addr).":".($self->proxy_port);
231 232 233
            unless ($self->supports_IPv6) {
                $execcmd .= " -4";
            }
M
Matt Caswell 已提交
234 235 236
            if ($self->cipherc ne "") {
                $execcmd .= " -cipher ".$self->cipherc;
            }
M
Matt Caswell 已提交
237 238 239
            if ($self->clientflags ne "") {
                $execcmd .= " ".$self->clientflags;
            }
240 241 242
            if (defined $self->sessionfile) {
                $execcmd .= " -ign_eof";
            }
243 244 245
            if ($self->debug) {
                print STDERR "Client command: $execcmd\n";
            }
M
Matt Caswell 已提交
246
            exec($execcmd);
M
Matt Caswell 已提交
247
        }
M
Matt Caswell 已提交
248
        $self->clientpid($pid);
M
Matt Caswell 已提交
249 250 251
    }

    # Wait for incoming connection from client
252
    my $client_sock;
253
    if(!($client_sock = $self->{proxy_sock}->accept())) {
254 255 256
        warn "Failed accepting incoming connection: $!\n";
        return 0;
    }
M
Matt Caswell 已提交
257 258 259 260

    print "Connection opened\n";

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

        $retry--;
M
Matt Caswell 已提交
278 279 280
        #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)) {
281 282
            $server_sock->close() if defined($server_sock);
            undef $server_sock;
M
Matt Caswell 已提交
283 284 285 286
            if ($retry) {
                #Sleep for a short while
                select(undef, undef, undef, 0.1);
            } else {
287 288
                warn "Failed to start up server (".$servaddr.",".$self->server_port."): $!\n";
                return 0;
M
Matt Caswell 已提交
289 290 291 292 293 294 295 296 297 298
            }
        }
    } 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;
299
    my $ctr = 0;
300
    local $SIG{PIPE} = "IGNORE";
301 302 303
    while(     (!(TLSProxy::Message->end)
                || (defined $self->sessionfile()
                    && (-s $self->sessionfile()) == 0))
304 305 306 307 308
            && $ctr < 10) {
        if (!(@ready = $sel->can_read(1))) {
            $ctr++;
            next;
        }
M
Matt Caswell 已提交
309 310 311 312 313
        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);
314
                $ctr = 0;
M
Matt Caswell 已提交
315 316 317 318
            } elsif ($hand == $client_sock) {
                $client_sock->sysread($indata, 16384) or goto END;
                $indata = $self->process_packet(0, $indata);
                $server_sock->syswrite($indata);
319
                $ctr = 0;
M
Matt Caswell 已提交
320
            } else {
321
                die "Unexpected handle";
M
Matt Caswell 已提交
322 323 324 325
            }
        }
    }

326
    die "No progress made" if $ctr >= 10;
327

M
Matt Caswell 已提交
328 329 330 331 332 333 334 335 336 337 338 339
    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(!$self->debug) {
        select($oldstdout);
    }
M
Matt Caswell 已提交
340 341 342 343 344 345
    $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);
346
        die "exit code $? from server process\n" if $? != 0;
M
Matt Caswell 已提交
347 348 349
    } else {
        # Give s_server sufficient time to finish what it was doing
        usleep(250000);
M
Matt Caswell 已提交
350
    }
M
Matt Caswell 已提交
351 352 353 354
    die "clientpid is zero\n" if $self->clientpid == 0;
    print "Waiting for client process to close: ".$self->clientpid."\n";
    waitpid($self->clientpid, 0);

355
    return 1;
M
Matt Caswell 已提交
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
}

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 已提交
384 385 386
    if(defined $self->filter) {
        $self->filter->($self);
    }
M
Matt Caswell 已提交
387 388 389 390 391 392 393 394

    #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;
        }
395
        $packet .= $record->reconstruct_record($server);
M
Matt Caswell 已提交
396 397 398 399 400 401 402 403 404 405 406 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
    }

    $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};
}
441 442 443 444 445
sub supports_IPv6
{
    my $self = shift;
    return $have_IPv6;
}
M
Matt Caswell 已提交
446 447 448 449 450 451 452 453 454 455
sub proxy_addr
{
    my $self = shift;
    return $self->{proxy_addr};
}
sub proxy_port
{
    my $self = shift;
    return $self->{proxy_port};
}
456 457

#Read/write accessors
M
Matt Caswell 已提交
458 459 460 461
sub server_addr
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
462
        $self->{server_addr} = shift;
M
Matt Caswell 已提交
463 464 465 466 467 468 469
    }
    return $self->{server_addr};
}
sub server_port
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
470
        $self->{server_port} = shift;
M
Matt Caswell 已提交
471 472 473 474 475 476 477
    }
    return $self->{server_port};
}
sub filter
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
478
        $self->{filter} = shift;
M
Matt Caswell 已提交
479 480 481
    }
    return $self->{filter};
}
M
Matt Caswell 已提交
482 483 484 485
sub cipherc
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
486
        $self->{cipherc} = shift;
M
Matt Caswell 已提交
487 488 489 490 491 492 493
    }
    return $self->{cipherc};
}
sub ciphers
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
494
        $self->{ciphers} = shift;
M
Matt Caswell 已提交
495 496 497
    }
    return $self->{ciphers};
}
M
Matt Caswell 已提交
498 499 500 501
sub serverflags
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
502
        $self->{serverflags} = shift;
M
Matt Caswell 已提交
503 504 505 506 507 508 509
    }
    return $self->{serverflags};
}
sub clientflags
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
510
        $self->{clientflags} = shift;
M
Matt Caswell 已提交
511 512 513 514 515 516 517
    }
    return $self->{clientflags};
}
sub serverconnects
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
518
        $self->{serverconnects} = shift;
M
Matt Caswell 已提交
519 520 521
    }
    return $self->{serverconnects};
}
522 523 524 525 526 527 528 529 530 531 532 533
# 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 已提交
534 535 536 537
sub serverpid
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
538
        $self->{serverpid} = shift;
M
Matt Caswell 已提交
539 540 541
    }
    return $self->{serverpid};
}
M
Matt Caswell 已提交
542 543 544 545 546 547 548 549
sub clientpid
{
    my $self = shift;
    if (@_) {
        $self->{clientpid} = shift;
    }
    return $self->{clientpid};
}
D
David Benjamin 已提交
550 551 552 553 554 555 556 557 558 559

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

M
Matt Caswell 已提交
561 562 563 564
sub is_tls13
{
    my $class = shift;
    if (@_) {
M
Matt Caswell 已提交
565
        $is_tls13 = shift;
M
Matt Caswell 已提交
566 567 568
    }
    return $is_tls13;
}
M
Matt Caswell 已提交
569 570 571 572 573

sub reneg
{
    my $self = shift;
    if (@_) {
M
Matt Caswell 已提交
574
        $self->{reneg} = shift;
M
Matt Caswell 已提交
575 576 577 578
    }
    return $self->{reneg};
}

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
#Setting a sessionfile means that the client will not close until the given
#file exists. This is useful in TLSv1.3 where otherwise s_client will close
#immediately at the end of the handshake, but before the session has been
#received from the server. A side effect of this is that s_client never sends
#a close_notify, so instead we consider success to be when it sends application
#data over the connection.
sub sessionfile
{
    my $self = shift;
    if (@_) {
        $self->{sessionfile} = shift;
        TLSProxy::Message->successondata(1);
    }
    return $self->{sessionfile};
}

595 596 597 598 599 600 601 602 603
sub ciphersuite
{
    my $class = shift;
    if (@_) {
        $ciphersuite = shift;
    }
    return $ciphersuite;
}

M
Matt Caswell 已提交
604
1;