Skip to content

Instantly share code, notes, and snippets.

@Zoddo
Last active August 8, 2022 22:29
Show Gist options
  • Save Zoddo/035784d640ecf9156fa471534deb1e1f to your computer and use it in GitHub Desktop.
Save Zoddo/035784d640ecf9156fa471534deb1e1f to your computer and use it in GitHub Desktop.
A script to use as an authorized_keys forced command to allow only SCP within a defined directory
# VM Web
from="192.0.2.1,2001:db8::/32",command="~/force_scp.sh ~/backups/web/",restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDINUz0eaXjFgBSwQpnx/T2DtwO+QRpFGJ5cMOUCtzOpHOcH0gfcFL9ESbXTovnTBGlfjTMy4QLy90uf9YJa2RQEusIiU4Ov7WOZKD2A1/MoYEJ+3kflve6+eh+r7X4yt5jUUWReNjX7a1tT3b99GzEc9WORVNmmFz3NtHPeGb6opodgrLbkaF+7HUJWrnc4xt3oI4qlENkQnJRHWe1IUzuOLpXpxnGvjyIyyZoj5iNRYHmCkiFqoKaxZ2HyKpMRF/dO3bNF3fCReaXZu0GalJvby45ka2cT6uGqm1iVUU1VqSnZU67ams2uK4FqQGj2dalId6ETAGaH8ZeZaMGuUYt root@web
# VM Web2
from="192.0.2.1,2001:db8::/32",command="~/force_scp.sh ~/backups/web2/",restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKM/LkWlD49eXbsncwUjUuREkBCuhVhwCAJSHci4QIDZ+EU108W1Q0o83QTF5bB+oXrj8FbQ/ZqnLAxqP1qrrMD7Sz99ytY49M7Hxlj68JnsXZCvHO0ePWHYsWes5xNeMEmqd/K8vbNKRzG3XI+3px3px0PM3r8mjaHwF/6E+M64XH/GZ4kZVmk68d+Ohp6omlMABNYuu3eXBV2LyXt10lEA3slP2DAi6rUmek5lFxfWNx3nXrJgM0FmZrXqrwe3mHKvmryHmxzUAx7KQy7gTU0gzp0FEZfHve9vWQUsSudwCNpqbj15BkaoEAyuu8vcb/N3sBDxWwV/PVsXlrXbT5 root@web2
# VM syadmin
from="192.0.2.1,2001:db8::/32",command="~/force_scp.sh ~/backups/sysadmin/",restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD1AcpEH0yf3ZHWii5Or9pjjY2KGB256Zv45XJbKXsyhNf51eyw6FDRyGNUVMhAJxtZS/p+aaIiv6En30p69UkZ1gvl3Mr0piUIlI2n/Z6ab2ZGItjhoSbBquZT9edtkLeuTdqm87hZZjyARa6sRxKjIwRBvx9/waThjKGM9TX668gaT5HC+S4FsptsPxhEhDCjDgSE3BScJxntY53tdLBYY7lMzRUjq8mkqqaegapNbWr7RX6caGrnKY+m23NjfbV2whB+PAmvPDGDDv6md2GPQxJZZZfDSDzcPUw+8HxUvR8BGA9iU43WSN7rvm5sNpK5tfoVHVFf3hB1KY6Mvnw5 root@sysadmin
#!/bin/bash
if [[ -z "$SSH_ORIGINAL_COMMAND" || "${SSH_ORIGINAL_COMMAND%% *}" != "scp" ]]; then
echo "Error: You don't have access to any shell" >&2
exit 1
fi
#set -- $SSH_ORIGINAL_COMMAND
umask 377
while getopts "vrdt:f:" opt ${SSH_ORIGINAL_COMMAND#* }; do
case $opt in
v)
# verbose
OPT_V="-v"
;;
r)
# recusrive
OPT_R="-r"
;;
d)
# directory
OPT_D="-d"
;;
t)
# Transfer from the source
CANONICAL_TARGET=$(readlink -m "$1$OPTARG")
if [[ "${CANONICAL_TARGET}" != $(readlink -m "$1")* ]]; then
echo "Error: Unsafe target" >&2
exit 2
fi
OPT_T="-t ${CANONICAL_TARGET}"
mkdir -pm 700 "${CANONICAL_TARGET}"
;;
f)
# Transfer to the source
CANONICAL_TARGET=$(readlink -m "$1$OPTARG")
if [[ "${CANONICAL_TARGET}" != $(readlink -m "$1")* ]]; then
echo "Error: Unsafe target" >&2
exit 2
fi
OPT_T="-f ${CANONICAL_TARGET}"
;;
esac
done
scp $OPT_V $OPT_R $OPT_D $OPT_T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment