#!/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 run as root 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 a new user with the /bin/false shell to restrict command-line access useradd -m -d /sftp/$USERNAME -s /bin/false $USERNAME # Create the chroot environment in /sftp and necessary directories mkdir -p /sftp/$USERNAME # Root directory of the user in the chroot environment mkdir -p /sftp/$USERNAME/upload # Upload directory for file transfers mkdir -p /sftp/$USERNAME/.ssh # Directory for SSH keys # Set permissions for the chroot directory chown root:root /sftp/$USERNAME # The main chroot directory must be owned by root chmod 755 /sftp/$USERNAME # Allows read and execute access, but no write access for the user chown $USERNAME:$USERNAME /sftp/$USERNAME/upload # User can write to their upload directory # Create the authorized_keys file for SSH key-based authentication touch /sftp/$USERNAME/.ssh/authorized_keys chmod 700 /sftp/$USERNAME/.ssh # Restrict access to .ssh directory for security chmod 600 /sftp/$USERNAME/.ssh/authorized_keys # Restrict permissions on authorized_keys chown -R $USERNAME:$USERNAME /sftp/$USERNAME/.ssh # Ensure user ownership on .ssh echo "User $USERNAME has been successfully set up in a chroot environment." # Update sshd_config to configure the chroot jail for this user if not already present 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