Monday, October 10, 2011

Tunneling UDP (e.g. Photoshop keyserver) over SSH

It's basically the same as this solution on Vincent Dumouchel's site, but wrapped up in a shell script that will run on a Mac. The theory is to use 'nc' to listen for UDP packets on localhost and forward them through a TCP connection (tunneled by SSH) to the remote host, where 'nc' will then read them off TCP and send them via UDP. Useful in a number of obscure situations.

#!/bin/sh
#
# file:        remote-key.sh
# description: forward UDP traffic to port 19283 (Adobe keysvr) over SSH
#
# Peter Desnoyers, Northeastern University, 2011
#

host=$1
keyserver=$2
port=19283      # Adobe keysrvr

# get rid of the annoying "Terminated" message on shutdown
exec 2<&-   

# lots of gross delays, because (a) we need to start the local 'nc'
# first, so it can be in the background, even though the remote isn't
# there yet to connect to, and (b) because we can't open the FIFO for
# reading until it's been opened for writing, or we'll get an EOF
#
(sleep 3; rm -f /tmp/fifo; mkfifo /tmp/fifo;
    (sleep 1; nc -l -u $port < /tmp/fifo) | nc localhost 6667 > /tmp/fifo) &
local=$!
trap "kill $local; rm -f /tmp/fifo" 0

# we keep the SSH in the foreground so that the remote end can detect
# a broken connection ('cat' will see EOF) and then clean up
# properly. 
#
ssh -L6667:localhost:6667 $host \
    'trap "rm -f /tmp/fifo; killall nc" 1; 
        rm -f /tmp/fifo; killall -q nc; mkfifo /tmp/fifo;
        ((sleep 1; nc -l -p 6667 < /tmp/fifo) | 
  nc -u '$keyserver' '$port' > /tmp/fifo) < /dev/null &
        cat > /dev/null;
        killall nc'