Build a Sftp server based on CentOS7.9 (with user script creation)

background:

· Existing methods:

The company transmits the research and development data to the external cooperative company through the FTP server, and the external company transmits the data to the company;

Employees download the data given by the administrator on the extranet, or transfer the data to the company

· Question 1:

Existing FTP servers do not encrypt data during transmission, and there is a risk of leakage. If the data packets are manually encrypted for transmission and then decrypted after receiving the data, it will take too much time for both parties

· Question 2:

The existing FTP server runs in passive mode, occupying too many ports or even the entire IP address

· Solution:

By building an SFTP server, the data is encrypted and only one TCP port is occupied

Build process:

· system:

CentOS7.9, according to the minimum installation without a graphical interface

  1. First create the sftp user group, and conduct unified management on the basis of the group

groupadd sftp
  1. Create sftp directory and set permissions

# create sftp directory
mkdir /sftp

# Set the directory owner (if the ChrootDirectory function needs to be implemented, the directory owner must be root)
chown root:sftp /sftp

# Set directory permissions (if you need to implement the ChrootDirectory function, the directory permission code cannot be higher than 755)
chmod 755 /sftp
  1. Edit the SSH configuration file

# backup configuration file
cp /etc/ssh/sshd_config{,.bak}

# Disable DNS reverse resolution and GSSAPI authentication functions to prevent login SSH from being too slow
sed -ri 's/#UseDNS yes/UseDNS no/' /etc/ssh/sshd_config
sed -ri 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/' /etc/ssh/sshd_config

# Comment out the Subsystem sftp /usr/libexec/openssh/sftp-server entry that comes with the configuration file
sed -ri 's/Subsystem/# Subsystem/' /etc/ssh/sshd_config

# Add Subsystem sftp internal-sftp entry
echo 'Subsystem sftp internal-sftp' >> /etc/ssh/sshd_config

# For user group sftp matching rules (multiple group names can be separated by commas) (matching users can be written as Match User username)
echo 'Match Group sftp' >> /etc/ssh/sshd_config

# Rule 1: Prohibit sftp group from using X11 graphics function
echo 'X11Forwarding no' >> /etc/ssh/sshd_config

# Rule 2: Forbid the sftp group to use the port forwarding function (external users can use sftp as a springboard to access other internal servers of the company, there are hidden dangers)
echo 'AllowTcpForwarding no' >> /etc/ssh/sshd_config

# Rule 3: Force the sftp group to use the commands provided by the sftp component, and prohibit running custom commands
echo 'ForceCommand internal-sftp' >> /etc/ssh/sshd_config

# Rule 4: After the user logs in, lock it in its root directory to prevent it from accessing other users' directories
echo 'ChrootDirectory /sftp/%u' >> /etc/ssh/sshd_config

# Restart the sshd service to make the previous configuration take effect, and check whether the service is running normally
systemctl restart sshd; systemctl status sshd
  1. Create users (because manual configuration is cumbersome, the following scripts are written to automatically create users, user directories, and configure permissions)

# Create a custom program
vi /usr/bin/sftpadd
# Write the following scripts into the custom program (write from #!/bin/bash)

#!/bin/bash

# Check if the script is running with root or sudo privileges
if [ $UID -ne 0 ]; then
    echo -e "Must run with root or sudo privileges!"
    exit 0
the fi

# --help help information
if [[ "$1" == "--help" ]] || [ $# -eq 0 ];then
    echo -e "\
Usage: sftpadd [user name] [user passwd] [permissions]"
    echo -e "\
List Of Parameter:"
    echo -e "username: sftp user name"
    echo -e "userpasswd: sftp user password"
    echo -e "permissions: u: mkdir upload, allow reading and writing"
    echo -e "d: mkdir download, read-only"
    echo -e "\
Examples 1:"
    echo -e "command: sftpadd tom 123456d"
    echo -e "action: Create user tom, only allow download"
    echo -e "\
Examples 2:"
    echo -e "command: sftpadd jerry 123456 ud"
    echo -e "action: Create user jerry, allow upload and download\
"
    exit 0
the fi

# Verify that the incoming parameters are correct
if [ $# -ne 3 ]; then
    echo -e "Parameter error, Please use sftpadd --help"
    exit 0
the fi

# Extract the incoming value
user_name="$1"; user_passwd="$2"; user_permissions="$3"

# Check if the username is duplicated
if grep -q "$user_name" /etc/passwd; then
    echo -e "User already exists!"
    exit 0
the fi

# Check if the password is less than 6 characters
if [ $(echo ${#user_passwd}) -lt 6 ]; then
    echo -e "User password is less than 6 digits!"
    exit 0
the fi

# Check whether the incoming parameter contains non-u/d characters
if [[ "$(echo $3 | sed -e 's/u//' -e 's/d//')" != "" ]]; then
    echo -e "Permission parameter contains illegal characters! Please use sftpadd --help"
    exit 0
the fi

# Create a user and password, add the user to the sftp group, and prohibit it from logging in to the server through the ssh client software
useradd -g sftp -s /sbin/nologin -M "$user_name" >> /dev/null 2> &1
echo -e "Create User Complete: $user_name"
echo "$user_passwd" | passwd --stdin "$user_name" >> /dev/null 2> &1
echo -e "Create User Password: $user_passwd"

# Generate the path of the user directory
upload_path="/sftp/$user_name/upload/"
download_path="/sftp/$user_name/download/"

# Create and echo the user directory
if [[ "$3" =~ "u" ]];then
    mkdir -p "$upload_path"
    chown "$user_name:sftp" "$upload_path"
    chmod 700 "$upload_path"
    echo -e "Create the upload directory: $upload_path"
the fi

if [[ "$3" =~ "d" ]];then
    mkdir -p "$download_path"
    chown "$user_name:sftp" "$download_path"
    chmod 500 "$download_path"
    echo -e "Create the download directory: $download_path"
the fi

exit 0
# Add executable rights to custom programs
chmod +x sftpadd

· Usage and parameters:

  1. Run sftpadd or sftpadd –help will have detailed prompts

  1. The created user does not have the ssh client login function (flashback immediately after login), and can only be used for sftp login

  1. The program automatically creates a user directory in a fixed mode: if you add the u parameter when creating, it will automatically create the upload directory and set the user to read and write it; if you add the d parameter, it will automatically create the download directory and set the user to only access it read

· Usage example 1:

An external cooperative company needs to send data back to the company, create an account user1 with a password of 123456, and set it to have read and write permissions to the upload directory

Run the command: sftpadd user1 123456 u

The program automatically creates user user1 and the user directory /sftp/user1/upload, and user1 has read and write permissions to the upload directory

· Usage example 2:

The company’s data needs to be downloaded by external cooperative companies, but they are not allowed to operate the files in the download directory (delete, rename, or modify data, etc.), create an account user2 password 123456 for it, and set it to only have read-only permissions for download

Run the command: sftpadd user2 123456 d

· Usage example 3:

An employee of the company needs to upload/download data on the external network, and creates an account user3 with a password of 123456 for him. He has read and write permissions for upload and read-only permission for download. Because the Sftp server is controlled by a high-privileged administrator, user3 can only transfer external data to the company, but cannot transfer internal company data privately (the administrator can only download the data after placing it in the download directory)

Run the command: sftp user3 123456 ud

  1. verify

Log in to the server through the sftp command or WinSCP, Xshell, FileZilla, Xftp and other tools to verify the relevant settings

· Test whether user3 can log in

Run the sftp [email protected] command, and then enter the password to log in

Verify that user3 is locked to the root directory after logging in (cannot access files of other users):

  1. Run the ls / command, if the /download/upload directory created for user3 is displayed, it is normal

  1. If the directory of other users or the system directory is displayed, the ChrootDirectory parameter in the sshd_config configuration file or the permission setting of the /sftp directory is incorrect.

Verify that user3 has read-only permissions to the download directory

  1. Run the mkdir /download/test command to try to create a test directory test in the download directory

  1. If Permission denied is prompted, it means that the permission setting is correct, because the user only has read-only permission for the download directory.

· Verify that user3 has read and write permissions to the upload directory

Run the mkdir /upload/test command to try to create a test directory test in the upload directory. If there is no error message, it means that the permissions are set correctly, because the user has read and write permissions for the upload directory

  1. Port Mapping

· Map SFTP port 22 of the internal network to the external network through a firewall or router

Notice:

  1. Do not map port 22 of the external network IP to port 22 of the internal network SFTP server, because there are special hosts on the external network to attack vulnerable servers or brute force crack passwords. It takes about 5 hours to scan the global IP , the server will be scanned no more than one day after it is mapped to the external network. You should use a port number that is not easy to guess, such as 53110, etc., instead of directly using 22, or 60022, 61022, which are easy to guess.

  1. Be sure to set a high-strength password. On the one hand, it is easy to cause data loss after the user password is brute force cracked. On the other hand, if the SSH component has a security vulnerability, the attacker may gain control of the entire SFTP server through the user account.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Cloud native entry skill treeService grid (istio)ServiceMesh introduction 11128 people are studying systematically