Tag Archives: ssh

SSH SOCKS Proxy Control

One of the many amazing features with SSH is various forms of traffic forwarding. You can forward ports (local or remote) and even setup a network tunnel with -w, and you can also use SSH to setup a SOCKS proxy for you. This creates an HTTP/S proxy server on your local machine which directs web traffic through a remote machine when the proxy is configured in your browser/system.

This is incredibly useful for accessing general web content for example on an otherwise firewalled network. It has the added bonus of encrypting traffic from you to the remote system if you were worried about local snoopers or outgoing firewalls.

To start a SOCKS proxy is easy: ssh -D PORT username@remotehost

This will start a proxy which can be accessed via PORT on localhost and connect through to the remotehost as username. Various other options can be used as well so the most common connection is:

ssh -D PORT -f -C -q -N username@remotehost

Here: -D as before says start the proxy on this port, -f means fork (run in the background), -C compress traffic (usually beneficial), -q quiet mode (nothing to the user), and -N means I don’t want to run a command just make the connection.

This is the command I commonly used to connect to different sites. To make things easier I had a number of scripts in my bin directory which had the values coded in. Opening became easy but closing the connection would require looking through a process list and stopping the right ssh process.

Given that I only wanted to run this in userspace (not system-wide or as part of startup etc) but I did want to be able to easily bring the link up and down without using a tty (so running in the background) I put together a quick bash script inspired by the old init.d services:

#!/bin/bash

SERVER=some.remote.server
USERNAME=username
PORT=8123

function vpn_pid(){
  echo $(ps aux | grep "ssh" | grep " -D" | grep "${PORT}" | awk '{print $2}')
}

case $1 in

up)
  echo "Starting VPN as ${USERNAME}@${SERVER}"
  ssh -D ${PORT} -f -C -q -N ${USERNAME}@${SERVER}
  echo "VPN Started"
  ;;
down)
  echo "Stopping VPN"
  PID=$(vpn_pid)
  if [ -z "$PID" ]
  then
    echo "SOCKS VPN does not appear to be running"
  else
    echo "Killing PID ${PID}"
    kill ${PID}
    echo "Kill signal sent"
  fi
  ;;
status)
  PID=$(vpn_pid)
  if [ -z "$PID" ]
  then
     echo "SOCKS VPN does not appear to be running"
  else
     echo "SOCKS VPN appears to be running, pid=${PID}"
  fi
  ;;
*)
  echo "Usage vpn up|down|status";
  ;;
esac

This script, imaginatively called vpn (even though yes I know it’s not actually a VPN) lets me start, check, and stop the proxy very easily.

Posted here just because!