Tech Tip: More ssh Tunneling

 in

Using ssh tunnelling I can protect services which are not normally protected and/or encrypted against unauthorized access. In this example I show how I set up a secure connection to my IRC proxy, but you can use this same recipe for other things.

I run the following script from my .xinitrc file. It does the following:

  • Checks, using fping, if it can reach my dircproxy host (myhost).
  • Calls autossh to run a persistent forwarding ssh session to the host.
  • Logs suitable messages to syslog using logger.
  • Echos the autossh PID, which can be used to wait.
#!/bin/sh
#
# Starts a tunneled connection to dIRCproxy on port 57000.
#

PROG=`basename $0`

if [ `which fping|wc -l` -eq 0 ]; then
    logger -p user.info $PROG: missing fping
    exit 0
fi
if [ `which autossh|wc -l` -eq 0 ]; then
    logger -p user.info $PROG: missing autossh
    exit 1
fi

fping myost -q
if [ $? -eq 0 ]; then
    autossh -X -N -L 57000:localhost:57000 frankie@myhost </dev/null >/dev/null >&1 &
    PID=$!
    logger -p user.info $PROG: dircproxy tunnel started as $PID
    echo $PID
else
    logger -p user.info $PROG: klecker not reachable
fi

You may not be familiar with fping or autossh. Fping is essentially just ping with some added features, plus it's more amenable for use in scripts. Autossh is an ssh wrapper that's used to start and monitor a copy of ssh.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

I'm confused

emacs's picture

The ssh's manpage said:
option -L has such syntax:
-L [bind_address:]port:host:hostport ... host
Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating a socket to listen to port on the local side,
optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the remote machine....

But the above script you gave had such expression:
-L 57000:localhost:57000 frankie@myhost
the host to be forwarded to is local machine, while the destination host is frankie@myhost, I wonder whether it can works, thanks!

The -L Option

Mitch Frazier's picture

It does work, the -L does the following: the copy of ssh running on the local system listens on port 57000 and forwards all that traffic to the remote copy of ssh. The remote copy of ssh then forwards it to port 57000 on localhost (localhost being local to the remote system, ie the remote system). This gives you "-L 57000:localhost:57000", the first port number is on the local system, the host and the second port number are on the remote system.

Mitch Frazier is an Associate Editor for Linux Journal.