#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2001-2006 Mitel Networks Corporation
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 		
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#----------------------------------------------------------------------

package esmith;

use strict;
use Errno;
use esmith::AccountsDB;
use esmith::ConfigDB;
use English;

my $a = esmith::AccountsDB->open or die "Could not open accounts db";
my $conf = esmith::ConfigDB->open or die "Could not open configuration db";

my $ldapauth = $conf->get('ldap')->prop('Authentication') || 'disabled';
my $x = 0; # exit value

my $event = $ARGV [0];

my @users_to_lock = bad_password_users();

defined $ARGV[1] && push @users_to_lock, $ARGV[1];

for my $user (@users_to_lock)
{
    lock_user($user);
}

exit 0;

sub lock_user
{
    my ($userName) = @_;
    #------------------------------------------------------------
    # Lock the user account in all authentication databases
    #------------------------------------------------------------

    my $u = $a->get($userName) or die "No account record for user $userName";

    if ($ldapauth ne 'enabled')
    {
        system("/usr/bin/passwd", "-l", $userName) == 0
            or ( $x = 255, warn "Error locking (unix) account $userName" );
    }
    system("/usr/sbin/cpu", "usermod", "-L", $userName) == 0
        or ( $x = $ldapauth ne 'enabled' ? $x : 255, warn "Error locking (ldap) account $userName" );
    system("/usr/bin/smbpasswd", "-d", $userName) == 0
        or ( $x = 255, warn "Error locking (smb) account $userName" );
    $u->set_prop('PasswordSet', 'no');

    if ($userName eq 'admin')
    {
        $conf->set_value('PasswordSet', 'no');
    }
}

sub bad_password_users
{
    my @smbpasswd = `/usr/bin/pdbedit -wL`
        or die "Error listing smb passwords\n";

    my @users;

    SMBPASSWD:
    foreach my $smb_entry (@smbpasswd)
    {
        my ($user, $uid, $lanman_hash, $nt_hash, @rest) 
            = split /:/, $smb_entry;

        if (   $lanman_hash eq "AAD3B435B51404EEAAD3B435B51404EE"
            or $nt_hash     eq "31D6CFE0D16AE931B73C59D7E0C089C0"
           )
        {
            push @users, $user;
            next SMBPASSWD;
        }
    }

    return @users;
}

exit ($x);
