#!/usr/bin/env bash # Initialize tunnel-only SSH auth for BackTunnel (Option A) # Usage: backtunnel-auth-setup [-p PORT] user@localhost set -euo pipefail PORT=2222 while [[ $# -gt 0 ]]; do case "$1" in -p|--port) PORT="$2"; shift 2;; -h|--help) echo "Usage: backtunnel-auth-setup [-p PORT] user@localhost" exit 0;; *) break;; esac done DEST="${1:-}" [[ -n "$DEST" ]] || { echo "Missing destination (e.g., user@localhost)."; exit 1; } KEY="$HOME/.ssh/id_ed25519_backtunnel" PUB="$KEY.pub" # 1) Create a dedicated key if missing if [[ ! -f "$KEY" ]]; then echo "Generating dedicated key at $KEY ..." ssh-keygen -t ed25519 -f "$KEY" -N "" -C "backtunnel" fi # 2) Append restricted key only (idempotent): tunnel-only + SFTP-only echo "Installing restricted key (tunnel-only, SFTP-only) via port $PORT ..." RESTRICTED_LINE="$(printf 'from="127.0.0.1",command="internal-sftp",restrict '; cat "$PUB")" ssh -p "$PORT" "$DEST" bash -lc ' set -euo pipefail umask 077 mkdir -p ~/.ssh touch ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys # Only append if not already present if ! grep -Fqx -- "$RESTRICTED_LINE" ~/.ssh/authorized_keys 2>/dev/null; then printf "%s\n" "$RESTRICTED_LINE" >> ~/.ssh/authorized_keys fi ' _ RESTRICTED_LINE="$RESTRICTED_LINE" echo "Done. This key will only work via the reverse tunnel (127.0.0.1) and only for SFTP."