Manuel Wildauers blog

SSH Tunnel as a socks5 proxy

#ssh #socks5 #privacy Share on Twitter

To randomized my ssh tunnels, I use a small script. This script looks at my ~/.ssh/config for hosts with the comment #socks5 after the Host and picks one out. I use autossh to maintain the connection.

AUTOSSH(1): autossh is a program to start a copy of ssh and monitor it, restarting it as necessary should it die or stop passing traffic.

#!/bin/bash

# ssh user config (http://www.openbsd.org/cgi-bin/man.cgi?query=ssh_config)
SSH_CONFIG=~/.ssh/config

# local port
PORT=8888

# export pid to file
export AUTOSSH_PIDFILE=/tmp/proxy.pid

# array with hosts from SSH_CONFIG.
# append "#socks5" at the end of the Host line.
# Example: "Host yourHost #socks5"
eval HOSTS=( $(awk '/^Host(.*?)#socks5$/ {print $2}' ${SSH_CONFIG}) )
N=1
for index in `shuf --input-range=0-$(( ${#HOSTS[*]} - 1 )) | head -${N}`
do
        echo -en "Host: ${HOSTS[$index]} Port: ${PORT}\n"
        # using autossh - Automatically restart SSH sessions and tunnels
        AUTOSSH_DEBUG=1
        AUTOSSH_GATETIME=0
        autossh -M 20000 -N -D ${PORT} ${HOSTS[$index]}
done

I start the script automatic on boot with Supervisor

/etc/supervisor.d/proxy.ini:

command=/path/to/proxy.sh
autostart=true
autorestart=true
startretries=3
user=YOURUSERNAME
stderr_logfile=/var/log/proxy.log
stdout_logfile=/var/log/proxy.log

In i3status i watch the pidfile /tmp/proxy.pid to get a status

run_watch proxy {
	pidfile = "/tmp/proxy.pid"
	format="⬤"
	format_down="⬤"
	color_good = "#4E9A06"
}