How can I disconnect ssh users, or limit the number of ssh logins?
I have an application that is using ssh to authenticate. Due to a variety of regulations (HIPAA, etc) users can only be logged in for a certain amount of time, and they can only be logged in once.
I would like for sshd to automatically disconnect a user if another, second connection is attempted. The idea is:
user 1 is connected.
user 2 uses user 1's credentials to try to log in.
both are kicked (we aren't sure if user 1 or user 2 is legit).
If this happens more than X times in Y minutes, the account is frozen until an administrator unfreezes it (most likely due to a password reset).
Right now, users are sandboxed in their own scponly directories; I'm not sure if that matters.
Trying to kill individual sshd connections is like playing whackamole, and I'd prefer this to be something that sshd does itself, and not a root-level script.
EDIT: This is on
2.6.31-22-server #73-Ubuntu SMP
And my limits.conf file contains lines like:
user1 hard maxlogins 1
user2 hard maxlogins 1
and my sshd_config file contains the line:
UsePAM yes
Yet I can still log in as user1 from multiple different machines. What am I doing wrong here, so that I can at least block user1 from having multiple logins?
Solution 1:
Setting up maxlogins limit actually works here. Just make sure you use '-' limit type, not 'hard'.
user1 - maxlogins 1
If you want to kick users who made double login using scponly, here's quick and dirty script, which does that. Put it into crontab, so it executes every minute.
#!/bin/sh
for user in `grep scponly /etc/passwd | gawk -F: '{print $1}'`; do
echo "Checking user: $user"
instances=`ps -u $user| grep scponly | wc -l`
echo "scponly instances $instances"
if [ $instances -gt 1 ] ; then
echo "Too many connections detected, slaying scponly for user $user"
if [ -e /tmp/$user ] ; then
attempts=`cat /tmp/$user`
echo "Detected $attempts attempts"
# increment attempts counter
echo $(($attempts+1)) > /tmp/$user
if [ $attempts -gt 3 ] ; then
echo "Blocking $user"
/usr/sbin/usermod -L $user
fi
else
echo "1" > /tmp/$user
fi
killall -u $user scponly
fi
done
Download script: http://dl.dropbox.com/u/17194482/kill-scponly.sh
Solution 2:
The PAM limits won't catch scp or sftp connections because they are not allocated a pty or written to utmp.