Files
BackTunnel/scripts/backtunnel-auth-setup

80 lines
2.7 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (c) 2025 LUXIM d.o.o., Slovenia
# Author: Matjaž Mozetič
#
# Name: backtunnel-auth-setup
# Summary: Initialize a tunnel-only, SFTP-only SSH key for BackTunnel access via reverse tunnel.
# Description:
# Generates (if missing) a dedicated SSH key (~/.ssh/id_ed25519_backtunnel) and installs its public
# key on the remote accounts authorized_keys, restricted to:
# from="127.0.0.1",command="internal-sftp",restrict
# This makes the key usable only through the reverse tunnel (localhost on the remote) and only for SFTP,
# not for shell or port-forwarding.
#
# Usage:
# backtunnel-auth-setup [-p PORT] user@localhost
#
# Examples:
# backtunnel-auth-setup alice@localhost
# backtunnel-auth-setup -p 4422 alice@localhost
#
# Dependencies:
# - bash
# - ssh, ssh-keygen
#
# Exit codes:
# 0 success (key exists/created, restricted entry ensured)
# 1 invalid usage (missing destination) or other failures
#
# Security:
# - The installed authorized_keys entry is tightly scoped to 127.0.0.1 and internal-sftp with restrict.
# - Remote authorized_keys is created with 600 permissions; umask 077 enforced during remote script.
#
# Notes:
# - Idempotent: re-running wont duplicate the restricted line if it is already present.
# 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."