1 # Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved.
3 # Licensed under the Apache License 2.0 (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";
12 package TLSProxy::Proxy;
18 use TLSProxy::Message;
19 use TLSProxy::ClientHello;
20 use TLSProxy::ServerHello;
21 use TLSProxy::HelloVerifyRequest;
22 use TLSProxy::EncryptedExtensions;
23 use TLSProxy::Certificate;
24 use TLSProxy::CertificateRequest;
25 use TLSProxy::CertificateVerify;
26 use TLSProxy::ServerKeyExchange;
27 use TLSProxy::NewSessionTicket;
34 # IO::Socket::IP is on the core module list, IO::Socket::INET6 isn't.
35 # However, IO::Socket::INET6 is older and is said to be more widely
36 # deployed for the moment, and may have less bugs, so we try the latter
37 # first, then fall back on the core modules. Worst case scenario, we
38 # fall back to IO::Socket::INET, only supports IPv4.
40 require IO::Socket::INET6;
41 my $s = IO::Socket::INET6->new(
50 $IP_factory = sub { IO::Socket::INET6->new(Domain => AF_INET6, @_); };
54 require IO::Socket::IP;
55 my $s = IO::Socket::IP->new(
64 $IP_factory = sub { IO::Socket::IP->new(@_); };
67 $IP_factory = sub { IO::Socket::INET->new(@_); };
74 my $ciphersuite = undef;
82 return init($class, $filter, $execute, $cert, $debug, 0);
91 return init($class, $filter, $execute, $cert, $debug, 1);
105 proxy_addr => $have_IPv6 ? "[::1]" : "127.0.0.1",
106 client_addr => $have_IPv6 ? "[::1]" : "127.0.0.1",
112 sessionfile => undef,
117 client_port => 49152 + int(rand(65535 - 49152)),
126 ciphers => "AES128-SHA",
127 ciphersuitess => "TLS_AES_128_GCM_SHA256",
135 return bless $self, $class;
142 $self->{proxy_sock}->close() if $self->{proxy_sock};
149 $self->{cipherc} = "";
150 $self->{ciphersuitec} = "";
151 $self->{flight} = -1;
152 $self->{direction} = -1;
153 $self->{partial} = ["", ""];
154 $self->{record_list} = [];
155 $self->{message_list} = [];
156 $self->{clientflags} = "";
157 $self->{sessionfile} = undef;
158 $self->{clientpid} = 0;
160 $ciphersuite = undef;
162 TLSProxy::Message->clear();
163 TLSProxy::Record->clear();
171 $self->{ciphers} = "AES128-SHA";
172 $self->{ciphersuitess} = "TLS_AES_128_GCM_SHA256";
173 $self->{serverflags} = "";
174 $self->{serverconnects} = 1;
175 $self->{serverpid} = 0;
195 sub connect_to_server
198 my $servaddr = $self->{server_addr};
200 $servaddr =~ s/[\[\]]//g; # Remove [ and ]
202 my $sock = $IP_factory->(PeerAddr => $servaddr,
203 PeerPort => $self->{server_port},
204 Proto => $self->{isdtls} ? 'udp' : 'tcp');
205 if (!defined($sock)) {
207 kill(3, $self->{serverpid});
208 die "unable to connect: $err\n";
211 $self->{server_sock} = $sock;
219 # Create the Proxy socket
220 my $proxaddr = $self->{proxy_addr};
221 $proxaddr =~ s/[\[\]]//g; # Remove [ and ]
222 my $clientaddr = $self->{client_addr};
223 $clientaddr =~ s/[\[\]]//g; # Remove [ and ]
227 if ($self->{isdtls}) {
229 LocalHost => $proxaddr,
231 PeerHost => $clientaddr,
232 PeerPort => $self->{client_port},
237 LocalHost => $proxaddr,
244 if (my $sock = $IP_factory->(@proxyargs)) {
245 $self->{proxy_sock} = $sock;
246 $self->{proxy_port} = $sock->sockport();
247 $self->{proxy_addr} = $sock->sockhost();
248 $self->{proxy_addr} =~ s/(.*:.*)/[$1]/;
249 print "Proxy started on port ",
250 "$self->{proxy_addr}:$self->{proxy_port}\n";
251 # use same address for s_server
252 $self->{server_addr} = $self->{proxy_addr};
254 warn "Failed creating proxy socket (".$proxaddr.",0): $!\n";
257 if ($self->{proxy_sock} == 0) {
261 my $execcmd = $self->execute
262 ." s_server -no_comp -engine ossltest -state"
263 #In TLSv1.3 we issue two session tickets. The default session id
264 #callback gets confused because the ossltest engine causes the same
265 #session id to be created twice due to the changed random number
266 #generation. Using "-ext_cache" replaces the default callback with a
267 #different one that doesn't get confused.
269 ." -accept $self->{server_addr}:0"
270 ." -cert ".$self->cert." -cert2 ".$self->cert
271 ." -naccept ".$self->serverconnects;
272 if ($self->{isdtls}) {
273 $execcmd .= " -dtls -max_protocol DTLSv1.2"
274 # TLSProxy does not support message fragmentation. So
275 # set a high mtu and fingers crossed.
278 $execcmd .= " -rev -max_protocol TLSv1.3";
280 if ($self->ciphers ne "") {
281 $execcmd .= " -cipher ".$self->ciphers;
283 if ($self->ciphersuitess ne "") {
284 $execcmd .= " -ciphersuites ".$self->ciphersuitess;
286 if ($self->serverflags ne "") {
287 $execcmd .= " ".$self->serverflags;
290 print STDERR "Server command: $execcmd\n";
293 $pid = IPC::Open2::open2(my $sout, my $sin, $execcmd) or die "Failed to $execcmd: $!\n";
294 $self->{serverpid} = $pid;
296 # Process the output from s_server until we find the ACCEPT line, which
297 # tells us what the accepting address and port are.
300 s/\R$//; # chomp does not work on windows.
301 next unless (/^ACCEPT\s.*:(\d+)$/);
302 $self->{server_port} = $1;
306 if ($self->{server_port} == 0) {
307 # This actually means that s_server exited, because otherwise
308 # we would still searching for ACCEPT...
310 die "no ACCEPT detected in '$execcmd' output: $?\n";
313 print STDERR "Server responds on ",
314 "$self->{server_addr}:$self->{server_port}\n";
316 # Connect right away...
317 $self->connect_to_server();
319 return $self->clientstart;
328 if ($self->execute) {
330 my $execcmd = $self->execute
331 ." s_client -engine ossltest"
332 ." -connect $self->{proxy_addr}:$self->{proxy_port}";
333 if ($self->{isdtls}) {
334 $execcmd .= " -dtls -max_protocol DTLSv1.2"
335 # TLSProxy does not support message fragmentation. So
336 # set a high mtu and fingers crossed.
338 # UDP has no "accept" for sockets which means we need to
339 # know were to send data back to.
340 ." -bind $self->{client_addr}:$self->{client_port}";
342 $execcmd .= " -max_protocol TLSv1.3";
344 if ($self->cipherc ne "") {
345 $execcmd .= " -cipher ".$self->cipherc;
347 if ($self->ciphersuitesc ne "") {
348 $execcmd .= " -ciphersuites ".$self->ciphersuitesc;
350 if ($self->clientflags ne "") {
351 $execcmd .= " ".$self->clientflags;
353 if ($self->clientflags !~ m/-(no)?servername/) {
354 $execcmd .= " -servername localhost";
356 if (defined $self->sessionfile) {
357 $execcmd .= " -ign_eof";
360 print STDERR "Client command: $execcmd\n";
363 open(my $savedout, ">&STDOUT");
364 # If we open pipe with new descriptor, attempt to close it,
365 # explicitly or implicitly, would incur waitpid and effectively
367 if (!($pid = open(STDOUT, "| $execcmd"))) {
369 kill(3, $self->{serverpid});
370 die "Failed to $execcmd: $err\n";
372 $self->{clientpid} = $pid;
374 # queue [magic] input
375 print $self->reneg ? "R" : "test";
377 # this closes client's stdin without waiting for its pid
378 open(STDOUT, ">&", $savedout);
382 # Wait for incoming connection from client
383 my $fdset = IO::Select->new($self->{proxy_sock});
384 if (!$fdset->can_read(60)) {
385 kill(3, $self->{serverpid});
386 die "s_client didn't try to connect\n";
390 if($self->{isdtls}) {
391 $client_sock = $self->{proxy_sock}
392 } elsif (!($client_sock = $self->{proxy_sock}->accept())) {
393 warn "Failed accepting incoming connection: $!\n";
397 print "Connection opened\n";
399 my $server_sock = $self->{server_sock};
402 #Wait for either the server socket or the client socket to become readable
403 $fdset = IO::Select->new($server_sock, $client_sock);
406 local $SIG{PIPE} = "IGNORE";
407 $self->{saw_session_ticket} = undef;
408 while($fdset->count && $ctr < 10) {
409 if (defined($self->{sessionfile})) {
410 # s_client got -ign_eof and won't be exiting voluntarily, so we
411 # look for data *and* session ticket...
412 last if TLSProxy::Message->success()
413 && $self->{saw_session_ticket};
415 if (!(@ready = $fdset->can_read(1))) {
416 last if TLSProxy::Message->success()
417 && $self->{saw_session_ticket};
422 foreach my $hand (@ready) {
423 if ($hand == $server_sock) {
424 if ($server_sock->sysread($indata, 16384)) {
425 if ($indata = $self->process_packet(1, $indata)) {
426 $client_sock->syswrite($indata) or goto END;
430 $fdset->remove($server_sock);
431 $client_sock->shutdown(SHUT_WR);
433 } elsif ($hand == $client_sock) {
434 if ($client_sock->sysread($indata, 16384)) {
435 if ($indata = $self->process_packet(0, $indata)) {
436 $server_sock->syswrite($indata) or goto END;
440 $fdset->remove($client_sock);
441 $server_sock->shutdown(SHUT_WR);
444 kill(3, $self->{serverpid});
445 die "Unexpected handle";
451 kill(3, $self->{serverpid});
452 print "No progress made\n";
457 print "Connection closed\n";
459 $server_sock->close();
460 $self->{server_sock} = undef;
463 #Closing this also kills the child process
464 $client_sock->close();
468 if (--$self->{serverconnects} == 0) {
469 $pid = $self->{serverpid};
470 print "Waiting for s_server process to close: $pid...\n";
471 # it's done already, just collect the exit code [and reap]...
473 die "exit code $? from s_server process\n" if $? != 0;
475 # It's a bit counter-intuitive spot to make next connection to
476 # the s_server. Rationale is that established connection works
477 # as synchronization point, in sense that this way we know that
478 # s_server is actually done with current session...
479 $self->connect_to_server();
481 $pid = $self->{clientpid};
482 print "Waiting for s_client process to close: $pid...\n";
490 my ($self, $server, $packet) = @_;
497 print "Received server packet\n";
499 print "Received client packet\n";
502 if ($self->{direction} != $server) {
503 $self->{flight} = $self->{flight} + 1;
504 $self->{direction} = $server;
507 print "Packet length = ".length($packet)."\n";
508 print "Processing flight ".$self->flight."\n";
510 #Return contains the list of record found in the packet followed by the
511 #list of messages in those records and any partial message
512 my @ret = TLSProxy::Record->get_records($server, $self->flight,
513 $self->{partial}[$server].$packet,
516 $self->{partial}[$server] = $ret[2];
517 push @{$self->{record_list}}, @{$ret[0]};
518 push @{$self->{message_list}}, @{$ret[1]};
522 if (scalar(@{$ret[0]}) == 0 or length($ret[2]) != 0) {
526 #Finished parsing. Call user provided filter here
527 if (defined $self->filter) {
528 $self->filter->($self);
531 #Take a note on NewSessionTicket
532 foreach my $message (reverse @{$self->{message_list}}) {
533 if ($message->{mt} == TLSProxy::Message::MT_NEW_SESSION_TICKET) {
534 $self->{saw_session_ticket} = 1;
539 #Reconstruct the packet
541 foreach my $record (@{$self->record_list}) {
542 $packet .= $record->reconstruct_record($server);
545 print "Forwarded packet length = ".length($packet)."\n\n";
554 return $self->{execute};
559 return $self->{cert};
564 return $self->{debug};
569 return $self->{flight};
574 return $self->{record_list};
579 return $self->{success};
594 return $self->{proxy_addr};
599 return $self->{proxy_port};
604 return $self->{server_addr};
609 return $self->{server_port};
614 return $self->{serverpid};
619 return $self->{clientpid};
622 #Read/write accessors
627 $self->{filter} = shift;
629 return $self->{filter};
635 $self->{cipherc} = shift;
637 return $self->{cipherc};
643 $self->{ciphersuitesc} = shift;
645 return $self->{ciphersuitesc};
651 $self->{ciphers} = shift;
653 return $self->{ciphers};
659 $self->{ciphersuitess} = shift;
661 return $self->{ciphersuitess};
667 $self->{serverflags} = shift;
669 return $self->{serverflags};
675 $self->{clientflags} = shift;
677 return $self->{clientflags};
683 $self->{serverconnects} = shift;
685 return $self->{serverconnects};
687 # This is a bit ugly because the caller is responsible for keeping the records
688 # in sync with the updated message list; simply updating the message list isn't
689 # sufficient to get the proxy to forward the new message.
690 # But it does the trick for the one test (test_sslsessiontick) that needs it.
695 $self->{message_list} = shift;
697 return $self->{message_list};
704 for (my $i = 0; $i < $length; $i++) {
723 $self->{reneg} = shift;
725 return $self->{reneg};
728 #Setting a sessionfile means that the client will not close until the given
729 #file exists. This is useful in TLSv1.3 where otherwise s_client will close
730 #immediately at the end of the handshake, but before the session has been
731 #received from the server. A side effect of this is that s_client never sends
732 #a close_notify, so instead we consider success to be when it sends application
733 #data over the connection.
738 $self->{sessionfile} = shift;
739 TLSProxy::Message->successondata(1);
741 return $self->{sessionfile};
748 $ciphersuite = shift;
756 return $self->{isdtls}; #read-only