Auto lock and unlock user account in Linux

Posted on Fri 04 March 2011 by Pavlo Khmel

If user entered his password incorrectly several times his account can be locked.

sudo faillog -u khmel
Username Failures Maximum Latest
khmel 7 0 Tue Oct 13 15:28:03 +0200 2009 on 212.18.129.

And even reset of password cannot help:
You should use this command, to reset counts of failures:

sudo faillog -u khmel -r
sudo faillog -u khmel
Username Failures Maximum Latest
khmel 0 0 Tue Oct 13 15:29:39 +0200 2009 on 212.18.129.

You also can have another problem: user can login, but cannot use sudo (because he entered too many times wrong password for sudo)

sudo -s
Password:
sudo: pam_acct_mgmt: 7

Sorry, try again.
Solution is the same

sudo faillog -u phn -r"

Additional information:
pam_tally - this module maintains a count of attempted accesses, can reset count on success, can deny access if too many attempts fail.
/etc/pam.d/system-auth - configuration file to configure attempted login accesses.
For instance on khmel.org:

sudo grep pam_tally /etc/pam.d/system-auth
auth required /lib/security/$ISA/pam_tally.so onerr=fail no_magic_root
account required /lib/security/$ISA/pam_tally.so per_user deny=6 no_magic_root reset

Some explanation:
auth - section that will turn on logging of failed login attempts
account - section that will actually do the account locking
deny=n - deny access if tally for this user exceeds n.
no_magic_root - option ensures that accounts with a UID of 0 are tallied.
reset - option indicates that the login failure count will be reset to 0 if a successful login takes place.
per_user - option allows you to exclude accounts from locking if the accounts have a maximum login failure set explicitly.
unlock_time=n option. It allow access after n seconds after failed attempt. If this option is used the user will be locked out for the specified amount of time after he exceeded his maximum allowed attempts.