有條件地停止互動式和非互動式ssh登入並給出錯誤訊息

有條件地停止互動式和非互動式ssh登入並給出錯誤訊息

我想阻止互動的非互動式基於條件邏輯的 ssh 登入。我需要測試用戶名並給出錯誤訊息。

使用 sftp(非互動式 ssh)的人也應該接受運氣測試。

我將如何實施?我對系統有完全的控制權。

我嘗試使用 sshd ForceCommand,但根據https://stackoverflow.com/a/33714333/746461它對 notty 不起作用。

我不熟悉 PAM,我懷疑 PAM 是否可以在互動式登入的情況下輸出自訂錯誤訊息。

https://linuxhint.com/understanding_bash_shell_configuration_startup/說帶有選項的非互動式登入 shell--noprofile可以繞過所有 bash 設定檔。這就是為什麼我不能在那裡寫下我的邏輯。

答案1

我想通了。我可以實作一個 PAM 模組來做到這一點。

將以下內容儲存到文件/root/checkConnections.

#! /bin/bash

limit=$1
c=$(pgrep -xcu $PAM_USER sshd)
if [[ $c -ge "$limit" ]]; then 
    echo "Max $limit ssh connections allowed, but you have $c."
    exit 1
fi

然後在/etc/pam.d/sshd中加入

session required pam_exec.so stdout /root/checkConnections 5

pam_exec.so執行 shell 腳本,stdout向使用者終端輸出訊息。

當條件失敗時,效果是這樣的。

$ ssh localhost
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-74-generic x86_64)

94 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable

Max 5 ssh connections allowed, but you have 5.
/root/checkConnections failed: exit code 1
Last login: Thu Jun 24 12:19:27 2021 from 172.18.33.67
Connection to localhost closed.

相關內容