Files
esg/scripts/ssh-socks-tunnel.sh

38 lines
1.1 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
: "${SSH_TUNNEL_HOST:?Set SSH_TUNNEL_HOST to the authorized server hostname or IP}"
ssh_user="${SSH_TUNNEL_USER:-${USER:-}}"
if [[ -z "$ssh_user" ]]; then
echo "SSH_TUNNEL_USER is required when the local username cannot be detected." >&2
exit 1
fi
ssh_port="${SSH_TUNNEL_PORT:-22}"
socks_host="${SOCKS_BIND_HOST:-127.0.0.1}"
socks_port="${SOCKS_PORT:-4030}"
ssh_target="${ssh_user}@${SSH_TUNNEL_HOST}"
echo "Opening SOCKS5 tunnel on ${socks_host}:${socks_port} via ${ssh_target}:${ssh_port}"
echo "Keep this terminal open while running the gateway. Press Ctrl-C to close the tunnel."
ssh_args=(
-N
-D "${socks_host}:${socks_port}"
-p "$ssh_port"
-o ExitOnForwardFailure=yes
-o ServerAliveInterval=30
-o ServerAliveCountMax=3
)
if [[ -n "${SSH_IDENTITY_FILE:-}" ]]; then
ssh_args+=( -i "$SSH_IDENTITY_FILE" )
fi
# Password authentication, when enabled by the server, is handled by ssh itself
# and is intentionally not accepted as an environment variable or command-line
# argument.
exec ssh "${ssh_args[@]}" "$ssh_target"