0

I am trying to run a script which gets the username of every locked account on a Linux system. The server is a Gentoo Hardened Server with SELinux. I tried by writing some Python which looks in /shadow/passwd for the obligatory '!' instead of a password hash.

I was going to just use this...

def get_users_blacklist(users):
    f = open('shadow.example', 'r')         #f is for file

    blacklist = []                          #obvious
    for l in f:                             #l is for line
        s = l.split(':')                    #s is for shadower
        for u in users:                     #u is for user
            if (u == s[0]):
                if (s[1] == "!"):
                    blacklist.append(u)

    return blacklist

It takes a list of users to check and if the password field in shadow is '!' (account disabled) then it adds them to a list.

However on my server the script can't read /etc/shadow because of SELinux and there is a 'permission denied' error using it. I need some other way of ascertaining this information about users. Google is mixing in the many results to lock a users account and I can't find the command to check if an account is locked.

I tried 'audit2allow' to allow sysadm_r Python scripts to read /etc/shadow but got a 'neverallow' error from semodule when inserting the rules. This is actually pretty hard and pretty risky.

What I am trying to do is ban all passwordless accounts in the group users in sshd_config automatically. There is an issue where users whom's accounts have been deactivated with `passwd -l user' can still get in with SSH pubkey auth. I want to apply this to the server of many users, so I wrote a script.

The script: https://pastebin.com/Z5T7GS4J

I think there should be some utility involving filecaps that can tell me if a users password has been locked/removed from the system. I could not find it on Google. It is not an option to put SELinux in permissive mode for my solution, because of automation and also a lack of clustering.

John Tate
  • 179
  • 4
  • 19
  • 1
    I have no idea what I'm talking about here, but could you do a getpwent call instead if reading the password file? – davidgo May 08 '20 at 22:28
  • Are you sure the script is running with `sysadm_r` and user `root`? `/etc/shadow` is only read/write for `root`. – hargut May 15 '20 at 18:58

2 Answers2

2

Sort of a hack, but it may work out for you...

#!/bin/bash
unset VISUAL
export EDITOR=cat
vipw -s >mybackupshadow.out

then run your script against mybackupshadow.out, deleting it when you're finished, of course.

This assumes that you have root access. I haven't tried this with SELinux as we don't use it, so not sure what affects SELinux has on vipw.

Fubar
  • 236
  • 1
  • 3
0

You could use this single line of code in python:

>>> blacklist = [ x.split(":")[0] for x in open("/tmp/shadow", "r") if x.split(":")[1] == '!']
>>> print blacklist
['lxd', 'monitoring-agent']
>>> 
c4f4t0r
  • 5,149
  • 3
  • 28
  • 41