On Ubuntu pam_limits
can limit the number of sessions per user.
While you read the configuration files of Ubuntu from /etc/pam.d/login
for example you can find a line something like session require pam_limits.so
.
# Sets up user limits according to /etc/security/limits.conf
# (Replaces the use of /etc/limits in old login)
session require pam_limits.so
So, the path for configuration files for limits has been changed comparing to older versions of login
.
Anyway it goes to /etc/security/
location same as in the previous answer by @matigo however I would edit limits.conf
file instead of creating files in subfolders since it's only one user you need limit.
In order to limit the number of sessions per user, you can add entries to a file in /etc/security/limits.conf
Actually you see examples in the comments in this file
Add a line by the end of file:
#<domain> <type> <item> <value>
johndoe hard maxlogins 1
Bear in mind to logout your user johndoe
and restart sshd
after your edits to apply.
pkill -9 -u johndoe # kill all running apps under johndoe user
service ssh restart
To kill exactly johndoe
terminal sessions
# First run "w" command
[root@vps ~]# w
00:34:21 up 48 days, 23:38, 4 users, load average: 0.79, 0.58, 0.56
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
kate pts/0 192.168.1.101 19:47 4:45m 0.04s 0.00s mc
johndoe pts/1 192.168.1.102 20:35 3:54m 2:23 0.00s nano
max pts/2 192.168.1.103 00:27 5.00s 0.08s 0.04s top
root pts/4 192.168.1.104 00:34 1.00s 0.02s 0.01s w
# then use pkill
pkill -9 -t pts/1
# then restart SSH
service ssh restart
P.S. I didn't tested, but maybe you would need "-" instead of "hard" in a limit type column.
#<domain> <type> <item> <value>
johndoe - maxlogins 1
That should be a solution in case you stick with a direct SSH connection... but if you use it for tunneling why just don't use something like wireguard
?
EDIT 2023-05-02
While you use SSH tunneling I believe you need some workaround.
Stream connections are not visible with w
command, but you can reveal them with netstat
.
So my guess is to use ~/.ssh/rc
to see and count your running connections in case johndoe - maxlogins 1
in limits.conf
not working.
First check PermitUserRC
option in sshd_config
. You need to enable it (by default it's enabled) and restart ssh
service.
Then use a script to check amount of connections from current IP. Here is a draft script to use (add these lines into your ~/.ssh/rc
under user johndoe
):
myip=`awk -F" " '{split($0,a); print a[1]}' <<< $SSH_CLIENT`
conncount=`netstat -anpW | grep ':22 \+' | grep ESTABLISHED | grep $myip | wc -l`
if test $conncount -gt 1; then exit 429; fi;
Explanation: Line (1) Get your current IP, (2) Count amount of connections to :22
port from $myip
and (3) if we have greater than 1 connection from this our IP terminate process and exit with error code 429
wireguard
instead?