Following is an example script for resetting the account’s password on Active Directory:
## PAM script to reset password of Microsoft ActiveDirectory LDAP user
use MIME::Base64;
use Encode qw(encode);
## global variables
my $ldapURL = "";
my $retVal = 1;
my $ldap = "";
## arguments
my $host = $args->arg("host");
my $port = $args->arg("port");
my $secure = $args->arg("secure");
my $adminDN = $args->arg("adminName");
my $adminPasswd = $args->arg("adminPasswd");
my $userDN = $args->arg("userName");
my $userPasswd = $args->arg("userPasswd");
my $userPasswdEncoded = encode_base64(encode("UTF-16le", "\"$userPasswd\""));
$ctx->log_info("START PASSWD RESET");
$ctx->log_debug("Input LDAP parameters : host - $host :: port - $port :: secure - $secure :: adminDN - $adminDN :: userDN - $userDN ");
$ctx->log_info("Resetting the password of the LDAP user $userDN");
## validate inputs
if ($host eq "" or $adminDN eq "" or $adminPasswd eq "" or $userDN eq "" or $userPasswd eq "") {
$ctx->log_error("Incomplete LDAP inputs - following parameters are mandatory - host, adminDN, adminPasswd, userDN and userPasswd are passed.");
return 0;
}
# set default ldap port numbers
if ($port eq "") {
if ($secure eq "" || $secure != 0) {
$port = 636;
} else {
$port = 389;
}
}
# create ldap url
if ($secure != 0) {
$ldapURL = "ldaps://".$host.":".$port;
} else {
$ldapURL = "ldap://".$host.":".$port;
}
# Login as LDAP admin
$ctx->log_debug("Authenticating to the LDAP server...");
$ldap = ldap_bind($ctx, $ldapURL, $adminDN, $adminPasswd, 100);
if ($ldap->arg('err') != 0) {
my $le = $ldap->arg('err');
$ctx->log_error("LDAP authentication failed - $le");
return 0;
} else {
$ctx->log_debug("LDAP authentication to $ldapURL as $adminDN successful.");
}
# Reset the user password
$ctx->log_debug("Modifying the password of the user $userDN ...");
$ldap = ldap_modify($ctx, $userDN, "unicodePwd", $userPasswdEncoded);
if ($ldap->arg('err') != 0) {
my $le = $ldap->arg('err');
$ctx->log_error("LDAP modify failed - $le ");
$retVal = 0;
} else {
$ctx->log_debug("LDAP modify successful in resetting the password of the user $userDN.");
}
# Logout LDAP admin
$ctx->log_debug("Logging out $adminDN from $ldapURL");
ldap_unbind($ctx);
$ctx->log_info("END PASSWD RESET");
return $retVal;