Search code examples
perlsslsocks

Using IO::Socket::SSL over an IO::Socket::SOCKS proxy


I'd like to mix SSL and SOCKS sockets. In other words, I want to send TLS encrypted data over a SOCKS proxy and I'd like to use IO::Socket::SSL and IO::Socket::Socks

The only option I can think of is to duplicate IO::Socket::SSL into an IO::Socket::SocksSSL class that inherit from IO::Socket::Socks. That's the only way to have the right order for (eg send). I need first to have the SSL method invoked and then it will invoke the parent (IO::Socket::Socks) send. Same for connect where the SSL connect would invoke the Socks connect and then start the TLS negotiation.

Unfortunately, the IO::Socket::SSL does not have a $SOCKET_CLASS var that would allow a subclass to easily decide what it inherits from, so I to change that one line in SSL.pm and duplicate all the code

I'm probably missing something here


Solution

  • Using a SOCKS proxy for TCP (and thus SSL) essentially means to first create a TCP socket, do some initial SOCKS handshake and then continue to work with the socket like with a normal TCP socket. IO::Socket::Socks->new(...) does this initial SOCKS handshake and returns a normal TCP socket. IO::Socket::SSL->start_SSL($socket,...) then does the TLS handshake on this socket. Combining both essentially does the same as IO::Socket::SSL->new(...), only using a SOCKS proxy instead of a direct connection.

    Thus the code might look something like this:

    use strict;
    use warnings;
    use IO::Socket::Socks;
    use IO::Socket::SSL;
    
    # establish TCP connection to target via SOCKS proxy
    my $cl = IO::Socket::Socks->new(
        ProxyAddr => '127.0.0.1',
        ProxyPort => 1234,
        ConnectAddr => 'whatsmyip.net',
        ConnectPort => 443
    ) or die $!;
    
    # upgrade the TCP socket to TLS
    IO::Socket::SSL->start_SSL($cl,
        # hostname is needed for SNI and certificate validation
        SSL_hostname => 'whatsmyip.net'
    ) or die $SSL_ERROR;
    
    # do a simple HTTP request on it
    print $cl "GET / HTTP/1.0\r\nHost: whatsmyip.net\r\n\r\n";
    print <$cl>;