Reverse Port Forwarding with Bash

This is a bash implementation of remote port forwarding.
Remote port forwarding makes a locally reachable port available on a remote server through a designated port. This can potentially make local services externally reachable from an otherwise unreachable origin. This type of tool demonstrates why restricting outbound network connectivity is important for hardening systems.

Server

#! /bin/bash
#
# Bash Reverse Port Forwarding (Server) 
# Peer connects over port 8080 and redirects a local port
# This port is accessible on localhost:2222
#
### Listen for external connections
listen_external='0.0.0.0 8080';

### Socket to access forwarded port
listen_internal='127.0.0.1 2222';

### Create a FIFO (named pipe)
fifo=$(mktemp -u);
mkfifo $fifo;

### Start the listener
ncat -l $listen_external 0<$fifo | ncat -l $listen_internal >$fifo;

### Clean up
echo 'Lost connection!' rm $fifo;

Client

set -o nounset
echo "[$$] Publishing $lhost:$lport to $rhost:$rport" \
&& exec 3<>/dev/tcp/$lhost/$lport \
&& exec 4<>/dev/tcp/$rhost/$rport \
&& bash <(cat 0<&3 1>&4 & ) \
&& cat 0<&4 1>&3

References

https://www.frameloss.org/2013/12/14/wicked-cool-reverse-proxy-with-bash-and-netcat/