Thursday, June 26, 2014

How to use Socat to connect to an SSL service over a HTTP proxy

SOCAT is in my opinion one of the best networking / relaying tools out there. Within my corporate network, I need to go through a HTTP proxy to reach the outside. Today I needed to connect to a Freenode IRC channel, using of course the IRC client of choice, IRSSI. Unfortunately, whilst IRSSI supports HTTP proxies, it fails at establishing an SSL connection when using one.

At this point, there are two possible solutions:

  • Connect using a clear-text IRC session over the proxy (which was out of consideration in my case)
  • Relay the server's SSL port to localhost over the proxy (yay)

Socat turned out to be the most easy to setup and worked flawlessly. Here is the setup for this particular example:


All connections to the local port 6666 would then be tunneled through the proxy, and forwarded to the destination server. So if the endpoint service is SSL-enabled, connect to your local port over SSL and the session gets encrypted end to end.

Here is a small Bash script for that purpose.
#!/bin/bash
if [ -z $3 ]; then
 echo "usage: $0 <listenport> <desthost> <destport>"
 exit
fi

LOCALPORT=$1
PROXYHOST=10.0.0.1
PROXYPORT=3128
DESTHOST=$2
DESTPORT=$3

socat TCP4-LISTEN:$LOCALPORT,bind=127.0.0.1 PROXY:$PROXYHOST:$DESTHOST:$DESTPORT,proxyport=$PROXYPORT &

echo SOCAT listening on 127.0.0.1:$LOCALPORT, forwarding to $DESTHOST:$DESTPORT

Note: Should your proxy require authentication, the socat command must be changed to:

socat TCP4-LISTEN:$LOCALPORT,bind=127.0.0.1 PROXY:$PROXYHOST:$DESTHOST:$DESTPORT,proxyport=$PROXYPORT,proxyauth=$PROXYUSER:$PROXYPASS