Proxyify application that does not support proxy

I have a legacy application that needs to connect over a proxy such as squid or HAProxy to a service on the internet. In other words I want to use netcat (nc) or something similar to proxy traffic through a proxy using the proxy protocol (or CONNECT method).

I call this how to proxify an application. It can be done using socat.

Lets say I have an application that needs to send mail over a port that is open on a proxy (port TCP 23) but my legacy application (in this case telnet) does not understand how to talk through a proxy.

The below socat command will listen on TCP port 2023, any connection to localhost:2023 will make socat send the CONNECT method to mail.google.com to the proxy my-proxy.local:3128 and send all data over the tunnel to mail.google.com on port 23.

socat TCP4-LISTEN:2023,reuseaddr,fork PROXY:my-proxy.local:mail.google.com:23,proxyport=3128

So now I can use telnet via the proxy to talk to the SMTP server (via the proxy).

brent@DESKTOP:$ telnet 127.0.0.1 2023
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
EHLO 

socat tips

Address already in use

Sometimes you will get the “Address already in use” error. This will happen because the linger time has not expired from the last socket bind, and that can be observed below:

After exiting the socat listen we run it again, netstat shows that bind in TIME_WAIT mode, subsequent bind to this address will fail until linger time has expired. This can be worked around by including the resuseaddr option which will bind with the SO_REUSEADDR. Here is a great stackoverflow explanation.

brent@ubuntu:~$ socat TCP4-LISTEN:2023,fork, STDOUT
I AM CONNECTED TO THIS PORT FROM ANOTHER WINDOW IN TELNET! Hello!
^Cbrent@ubuntu:~$ socat TCP4-LISTEN:2023,fork, STDOUT
2022/01/23 09:03:51 socat[3989] E bind(5, {AF=2 0.0.0.0:2023}, 16): Address already in use
brent@ubuntu:~$ netstat -an | grep TIME_WAIT
tcp        0      0 127.0.0.1:2023          127.0.0.1:36014         TIME_WAIT
socat TCP4-LISTEN:2023,reuseaddr,fork PROXY:my-proxy.local:mail.google.com:23,proxyport=3128

http://www.dest-unreach.org/socat/

Comments

comments powered by Disqus