如何使用 chroot 監獄將 SFTP 用戶限制在家目錄中

在本教程中,我們將討論如何限制SFTP用戶訪問其主目錄或特定目錄。這意味著用戶只能訪問自己的主目錄,而不能訪問整個文件系統。

限制用戶主目錄對於共享服務器環境至關重要,這樣未經授權的用戶就無法偷窺其他用戶的文件和文件夾。

重要提示:還請注意,本文的目的是僅提供SFTP訪問權限,而不是SSH登錄,按照本文的步驟將具有進行文件傳輸的權限,但不允許進行遠程SSH會話。

建議閱讀: 使用Chrooted Jail限制SSH用戶訪問特定目錄

實現這一目標的最簡單方法是為SFTP訪問創建一個chrooted jail環境。這種方法對於所有Unix/Linux操作系統都是相同的。使用chrooted環境,我們可以將用戶限制在其主目錄或特定目錄中。

將用戶限制在主目錄中

在本節中,我們將創建一個名為sftpgroup的新組,並為用戶賬戶分配正確的所有權和權限。有兩種選擇可以將用戶限制在主目錄或特定目錄中,我們將在本文中看到這兩種方法。

創建或修改用戶和組

讓我們限制現有使用者,例如tecmint,只能存取名為/home/tecmint的家目錄。為此,您需要使用如下所示的sftpgroup命令創建一個新的群組:

# groupadd sftpgroup

接下來,將使用者‘tecmint’分配到sftpgroup群組中。

# usermod -G sftpgroup tecmint

您也可以使用useradd命令創建一個新使用者,例如senthil,並將該使用者分配到sftpusers群組中。

# adduser senthil -g sftpgroup -s /sbin/nologin
# passwd tecmint

修改SSH配置文件

打開並將以下行添加到/etc/ssh/sshd_config配置文件中。

Subsystem sftp internal-sftp
 
   Match Group sftpgroup
   ChrootDirectory /home
   ForceCommand internal-sftp
   X11Forwarding no
   AllowTcpForwarding no

保存並退出文件,重新啟動sshd服務以使新更改生效。

# systemctl restart sshd
OR
# service sshd restart

如果您將多個使用者chroot到同一目錄中,則應更改每個使用者的家目錄權限,以防止所有使用者瀏覽其他使用者的家目錄。

# chmod 700 /home/tecmint

驗證SSH和SFTP使用者登錄

現在,是時候從本地系統檢查登錄情況了。嘗試從本地系統ssh到遠程系統。

# ssh [email protected]

這裡,

  1. tecmint – 遠程系統的使用者名稱。
  2. 192.168.1.150 – 遠程系統的IP地址。
樣本輸出:
[email protected]'s password: 
Could not chdir to home directory /home/tecmint: No such file or directory
This service allows sftp connections only.
Connection to 192.168.1.150 closed.

然後,使用SFTP訪問遠程系統。

# sftp [email protected]
樣本輸出:
[email protected]'s password: 
Connected to 192.168.1.150.
sftp>

讓我們檢查當前工作目錄:

sftp&gt pwd
Remote working directory: /

sftp&gt ls
tecmint  

這裡,tecmint 是主目錄。進入 tecmint 目錄並創建您選擇的文件或文件夾。

sftp&gt cd tecmint
Remote working directory: /

sftp&gt mkdir test
tecmint  

限制用戶訪問特定目錄

在我們之前的示例中,我們將現有用戶限制在主目錄中。現在,我們將看到如何將新用戶限制在自定義目錄中。

創建組和新用戶

創建一個新組 sftpgroup

# groupadd sftpgroup

接下來,為 SFTP 組創建一個目錄並為 root 用戶分配權限。

# mkdir -p /sftpusers/chroot
# chown root:root /sftpusers/chroot/

接下來,為每個用戶創建新目錄,他們將擁有完全訪問權限。例如,我們將使用以下一系列命令創建 tecmint 用戶及其新主目錄,並使用正確的組權限。

# adduser tecmint -g sftpgroup -s /sbin/nologin
# passwd tecmint
# mkdir /sftpusers/chroot/tecmint
# chown tecmint:sftpgroup /sftpusers/chroot/tecmint/
# chmod 700 /sftpusers/chroot/tecmint/

為 SFTP 訪問配置 SSH

修改或添加以下行到文件末尾:

#Subsystem  	sftp	/usr/libexec/openssh/sftp-server
Subsystem sftp  internal-sftp
 
Match Group sftpgroup
   ChrootDirectory /sftpusers/chroot/
   ForceCommand internal-sftp
   X11Forwarding no
   AllowTcpForwarding no

保存並退出文件。重新啟動 sshd 服務以使保存的更改生效。

# systemctl restart sshd
OR
# service sshd restart

就是這樣,您可以通過使用上面提供的步驟登錄到遠程 SSH 和 SFTP 伺服器來進行檢查 驗證 SSH 和 SFTP 登錄

請注意,此方法將禁用 shell 訪問,即您無法使用 SSH 訪問遠程系統的 shell 會話。您只能通過 SFTP 訪問遠程系統並在本地和遠程系統之間進行文件傳輸。

結論

現在您知道如何在Linux中使用Chroot環境來限制用戶的主目錄。如果您覺得這篇文章有用,請在您的社交網絡上分享這篇文章,並在下面的評論部分告訴我們是否有其他方法來限制用戶的主目錄。

Source:
https://www.tecmint.com/restrict-sftp-user-home-directories-using-chroot/