1 # Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
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
9 use POSIX ":sys_wait_h";
11 package TLSProxy::Proxy;
17 use TLSProxy::Message;
18 use TLSProxy::ClientHello;
19 use TLSProxy::ServerHello;
20 use TLSProxy::EncryptedExtensions;
21 use TLSProxy::Certificate;
22 use TLSProxy::CertificateVerify;
23 use TLSProxy::ServerKeyExchange;
24 use TLSProxy::NewSessionTicket;
31 # IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
32 # However, IO::Socket::INET6 is older and is said to be more widely
33 # deployed for the moment, and may have less bugs, so we try the latter
34 # first, then fall back on the core modules. Worst case scenario, we
35 # fall back to IO::Socket::INET, only supports IPv4.
37 require IO::Socket::INET6;
38 my $s = IO::Socket::INET6->new(
47 $IP_factory = sub { IO::Socket::INET6->new(@_); };
51 require IO::Socket::IP;
52 my $s = IO::Socket::IP->new(
61 $IP_factory = sub { IO::Socket::IP->new(@_); };
64 $IP_factory = sub { IO::Socket::INET->new(@_); };
71 my $ciphersuite = undef;
83 proxy_addr => $have_IPv6 ? "[::1]" : "127.0.0.1",
101 ciphers => "AES128-SHA",
102 ciphersuitess => "TLS_AES_128_GCM_SHA256",
110 # Create the Proxy socket
111 my $proxaddr = $self->{proxy_addr};
112 $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
114 LocalHost => $proxaddr,
120 if (my $sock = $IP_factory->(@proxyargs)) {
121 $self->{proxy_sock} = $sock;
122 $self->{proxy_port} = $sock->sockport();
123 $self->{proxy_addr} = $sock->sockhost();
124 $self->{proxy_addr} =~ s/(.*:.*)/[$1]/;
125 print "Proxy started on port ",
126 "$self->{proxy_addr}:$self->{proxy_port}\n";
127 # use same address for s_server
128 $self->{server_addr} = $self->{proxy_addr};
130 warn "Failed creating proxy socket (".$proxaddr.",0): $!\n";
133 return bless $self, $class;
140 $self->{proxy_sock}->close() if $self->{proxy_sock};
147 $self->{cipherc} = "";
148 $self->{ciphersuitec} = "";
149 $self->{flight} = -1;
150 $self->{direction} = -1;
151 $self->{partial} = ["", ""];
152 $self->{record_list} = [];
153 $self->{message_list} = [];
154 $self->{clientflags} = "";
155 $self->{sessionfile} = undef;
156 $self->{clientpid} = 0;
158 $ciphersuite = undef;
160 TLSProxy::Message->clear();
161 TLSProxy::Record->clear();
169 $self->{ciphers} = "AES128-SHA";
170 $self->{ciphersuitess} = "TLS_AES_128_GCM_SHA256";
171 $self->{serverflags} = "";
172 $self->{serverconnects} = 1;
173 $self->{serverpid} = 0;
193 sub connect_to_server
196 my $servaddr = $self->{server_addr};
198 $servaddr =~ s/[\[\]]//g; # Remove [ and ]
200 my $sock = $IP_factory->(PeerAddr => $servaddr,
201 PeerPort => $self->{server_port},
203 if (!defined($sock)) {
205 kill(3, $self->{real_serverpid});
206 die "unable to connect: $err\n";
209 $self->{server_sock} = $sock;
217 if ($self->{proxy_sock} == 0) {
221 my $execcmd = $self->execute
222 ." s_server -max_protocol TLSv1.3 -no_comp -rev -engine ossltest"
223 ." -accept $self->{server_addr}:0"
224 ." -cert ".$self->cert." -cert2 ".$self->cert
225 ." -naccept ".$self->serverconnects;
226 if ($self->ciphers ne "") {
227 $execcmd .= " -cipher ".$self->ciphers;
229 if ($self->ciphersuitess ne "") {
230 $execcmd .= " -ciphersuites ".$self->ciphersuitess;
232 if ($self->serverflags ne "") {
233 $execcmd .= " ".$self->serverflags;
236 print STDERR "Server command: $execcmd\n";
239 open(my $savedin, "<&STDIN");
241 # Temporarily replace STDIN so that sink process can inherit it...
242 $pid = open(STDIN, "$execcmd |") or die "Failed to $execcmd: $!\n";
243 $self->{real_serverpid} = $pid;
245 # Process the output from s_server until we find the ACCEPT line, which
246 # tells us what the accepting address and port are.
249 s/\R$//; # Better chomp
250 next unless (/^ACCEPT\s.*:(\d+)$/);
251 $self->{server_port} = $1;
255 if ($self->{server_port} == 0) {
256 # This actually means that s_server exited, because otherwise
257 # we would still searching for ACCEPT...
259 die "no ACCEPT detected in '$execcmd' output: $?\n";
262 # Just make sure everything else is simply printed [as separate lines].
263 # The sub process simply inherits our STD* and will keep consuming
264 # server's output and printing it as long as there is anything there,
268 if (eval { require Win32::Process; 1; }) {
269 if (Win32::Process::Create(my $h, $^X, "perl -ne print", 0, 0, ".")) {
270 $pid = $h->GetProcessID();
271 $self->{proc_handle} = $h; # hold handle till next round [or exit]
273 $error = Win32::FormatMessage(Win32::GetLastError());
276 if (defined($pid = fork)) {
277 $pid or exec("$^X -ne print") or exit($!);
283 # Change back to original stdin
284 open(STDIN, "<&", $savedin);
287 if (!defined($pid)) {
288 kill(3, $self->{real_serverpid});
289 die "Failed to capture s_server's output: $error\n";
292 $self->{serverpid} = $pid;
294 print STDERR "Server responds on ",
295 "$self->{server_addr}:$self->{server_port}\n";
297 # Connect right away...
298 $self->connect_to_server();
300 return $self->clientstart;
307 if ($self->execute) {
309 my $execcmd = $self->execute
310 ." s_client -max_protocol TLSv1.3 -engine ossltest"
311 ." -connect $self->{proxy_addr}:$self->{proxy_port}";
312 if ($self->cipherc ne "") {
313 $execcmd .= " -cipher ".$self->cipherc;
315 if ($self->ciphersuitesc ne "") {
316 $execcmd .= " -ciphersuites ".$self->ciphersuitesc;
318 if ($self->clientflags ne "") {
319 $execcmd .= " ".$self->clientflags;
321 if ($self->clientflags !~ m/-(no)?servername/) {
322 $execcmd .= " -servername localhost";
324 if (defined $self->sessionfile) {
325 $execcmd .= " -ign_eof";
328 print STDERR "Client command: $execcmd\n";
331 open(my $savedout, ">&STDOUT");
332 # If we open pipe with new descriptor, attempt to close it,
333 # explicitly or implicitly, would incur waitpid and effectively
335 if (!($pid = open(STDOUT, "| $execcmd"))) {
337 kill(3, $self->{real_serverpid});
338 die "Failed to $execcmd: $err\n";
340 $self->{clientpid} = $pid;
342 # queue [magic] input
343 print $self->reneg ? "R" : "test";
345 # this closes client's stdin without waiting for its pid
346 open(STDOUT, ">&", $savedout);
350 # Wait for incoming connection from client
351 my $fdset = IO::Select->new($self->{proxy_sock});
352 if (!$fdset->can_read(1)) {
353 kill(3, $self->{real_serverpid});
354 die "s_client didn't try to connect\n";
358 if(!($client_sock = $self->{proxy_sock}->accept())) {
359 warn "Failed accepting incoming connection: $!\n";
363 print "Connection opened\n";
365 my $server_sock = $self->{server_sock};
368 #Wait for either the server socket or the client socket to become readable
369 $fdset = IO::Select->new($server_sock, $client_sock);
372 local $SIG{PIPE} = "IGNORE";
373 $self->{saw_session_ticket} = undef;
374 while($fdset->count && $ctr < 10) {
375 if (defined($self->{sessionfile})) {
376 # s_client got -ign_eof and won't be exiting voluntarily, so we
377 # look for data *and* session ticket...
378 last if TLSProxy::Message->success()
379 && $self->{saw_session_ticket};
381 if (!(@ready = $fdset->can_read(1))) {
385 foreach my $hand (@ready) {
386 if ($hand == $server_sock) {
387 if ($server_sock->sysread($indata, 16384)) {
388 if ($indata = $self->process_packet(1, $indata)) {
389 $client_sock->syswrite($indata) or goto END;
393 $fdset->remove($server_sock);
394 $client_sock->shutdown(SHUT_WR);
396 } elsif ($hand == $client_sock) {
397 if ($client_sock->sysread($indata, 16384)) {
398 if ($indata = $self->process_packet(0, $indata)) {
399 $server_sock->syswrite($indata) or goto END;
403 $fdset->remove($client_sock);
404 $server_sock->shutdown(SHUT_WR);
407 kill(3, $self->{real_serverpid});
408 die "Unexpected handle";
414 kill(3, $self->{real_serverpid});
415 die "No progress made";
419 print "Connection closed\n";
421 $server_sock->close();
422 $self->{server_sock} = undef;
425 #Closing this also kills the child process
426 $client_sock->close();
430 if (--$self->{serverconnects} == 0) {
431 $pid = $self->{serverpid};
432 print "Waiting for 'perl -ne print' process to close: $pid...\n";
433 $pid = waitpid($pid, 0);
435 die "exit code $? from 'perl -ne print' process\n" if $? != 0;
436 } elsif ($pid == 0) {
437 kill(3, $self->{real_serverpid});
438 die "lost control over $self->{serverpid}?";
440 $pid = $self->{real_serverpid};
441 print "Waiting for s_server process to close: $pid...\n";
442 # it's done already, just collect the exit code [and reap]...
444 die "exit code $? from s_server process\n" if $? != 0;
446 # It's a bit counter-intuitive spot to make next connection to
447 # the s_server. Rationale is that established connection works
448 # as syncronization point, in sense that this way we know that
449 # s_server is actually done with current session...
450 $self->connect_to_server();
452 $pid = $self->{clientpid};
453 print "Waiting for s_client process to close: $pid...\n";
461 my ($self, $server, $packet) = @_;
468 print "Received server packet\n";
470 print "Received client packet\n";
473 if ($self->{direction} != $server) {
474 $self->{flight} = $self->{flight} + 1;
475 $self->{direction} = $server;
478 print "Packet length = ".length($packet)."\n";
479 print "Processing flight ".$self->flight."\n";
481 #Return contains the list of record found in the packet followed by the
482 #list of messages in those records and any partial message
483 my @ret = TLSProxy::Record->get_records($server, $self->flight,
484 $self->{partial}[$server].$packet);
485 $self->{partial}[$server] = $ret[2];
486 push @{$self->{record_list}}, @{$ret[0]};
487 push @{$self->{message_list}}, @{$ret[1]};
491 if (scalar(@{$ret[0]}) == 0 or length($ret[2]) != 0) {
495 #Finished parsing. Call user provided filter here
496 if (defined $self->filter) {
497 $self->filter->($self);
500 #Take a note on NewSessionTicket
501 foreach my $message (reverse @{$self->{message_list}}) {
502 if ($message->{mt} == TLSProxy::Message::MT_NEW_SESSION_TICKET) {
503 $self->{saw_session_ticket} = 1;
508 #Reconstruct the packet
510 foreach my $record (@{$self->record_list}) {
511 $packet .= $record->reconstruct_record($server);
514 print "Forwarded packet length = ".length($packet)."\n\n";
523 return $self->{execute};
528 return $self->{cert};
533 return $self->{debug};
538 return $self->{flight};
543 return $self->{record_list};
548 return $self->{success};
563 return $self->{proxy_addr};
568 return $self->{proxy_port};
573 return $self->{server_addr};
578 return $self->{server_port};
583 return $self->{serverpid};
588 return $self->{clientpid};
591 #Read/write accessors
596 $self->{filter} = shift;
598 return $self->{filter};
604 $self->{cipherc} = shift;
606 return $self->{cipherc};
612 $self->{ciphersuitesc} = shift;
614 return $self->{ciphersuitesc};
620 $self->{ciphers} = shift;
622 return $self->{ciphers};
628 $self->{ciphersuitess} = shift;
630 return $self->{ciphersuitess};
636 $self->{serverflags} = shift;
638 return $self->{serverflags};
644 $self->{clientflags} = shift;
646 return $self->{clientflags};
652 $self->{serverconnects} = shift;
654 return $self->{serverconnects};
656 # This is a bit ugly because the caller is responsible for keeping the records
657 # in sync with the updated message list; simply updating the message list isn't
658 # sufficient to get the proxy to forward the new message.
659 # But it does the trick for the one test (test_sslsessiontick) that needs it.
664 $self->{message_list} = shift;
666 return $self->{message_list};
673 for (my $i = 0; $i < $length; $i++) {
692 $self->{reneg} = shift;
694 return $self->{reneg};
697 #Setting a sessionfile means that the client will not close until the given
698 #file exists. This is useful in TLSv1.3 where otherwise s_client will close
699 #immediately at the end of the handshake, but before the session has been
700 #received from the server. A side effect of this is that s_client never sends
701 #a close_notify, so instead we consider success to be when it sends application
702 #data over the connection.
707 $self->{sessionfile} = shift;
708 TLSProxy::Message->successondata(1);
710 return $self->{sessionfile};
717 $ciphersuite = shift;