Files
scripts-admin-debian/miscellaneous/sftp_chroot.sh
2024-10-31 23:04:46 +01:00

57 lines
2.3 KiB
Bash

#!/bin/bash
# This script automatically configures a chroot environment for an SFTP user in the /sftp directory.
# It creates a user with restricted SFTP access, sets up the necessary directory structure,
# configures permissions, and adds an authorized_keys file for key-based authentication.
# Usage:
# Save this script as "sftp_chroot.sh" and make it executable by running the command: `chmod +x sftp_chroot.sh`.
# Then, execute it with root privileges using: `sudo ./sftp_chroot.sh`.
# The script will prompt you for the SFTP username, set up the necessary chroot environment, configure permissions,
# and apply the SSH settings to restrict the user to SFTP access only. Finally, it will restart the SSH service to
# apply the changes.
# Check if the script is executed with root privileges
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
# Prompt for the SFTP username
read -p "Enter the SFTP username: " USERNAME
# Create the user with /bin/false shell to limit access
useradd -m -d /sftp/$USERNAME -s /bin/false $USERNAME
# Create the chroot environment in /sftp
mkdir -p /sftp/$USERNAME
mkdir -p /sftp/$USERNAME/upload
mkdir -p /sftp/$USERNAME/.ssh
# Set permissions for the chroot directory
chown root:root /sftp/$USERNAME
chmod 755 /sftp/$USERNAME
chown $USERNAME:$USERNAME /sftp/$USERNAME/upload
# Create the authorized_keys file
touch /sftp/$USERNAME/.ssh/authorized_keys
chmod 700 /sftp/$USERNAME/.ssh
chmod 600 /sftp/$USERNAME/.ssh/authorized_keys
chown -R $USERNAME:$USERNAME /sftp/$USERNAME/.ssh
echo "User $USERNAME has been successfully configured in a chroot environment."
# Add SFTP configuration to sshd_config if necessary
if ! grep -q "Match User $USERNAME" /etc/ssh/sshd_config; then
echo -e "\n# SFTP configuration for $USERNAME" >> /etc/ssh/sshd_config
echo "Match User $USERNAME" >> /etc/ssh/sshd_config
echo " ChrootDirectory /sftp/$USERNAME" >> /etc/ssh/sshd_config
echo " ForceCommand internal-sftp" >> /etc/ssh/sshd_config
echo " AllowTcpForwarding no" >> /etc/ssh/sshd_config
echo " PermitTunnel no" >> /etc/ssh/sshd_config
fi
# Restart the SSH service
systemctl restart ssh
echo "Chroot jail for $USERNAME configured successfully. You can now add SSH keys in /sftp/$USERNAME/.ssh/authorized_keys"