PasswordExpires, Part I
public class PasswordExpires
{
DomainPolicy policy;
const int UF_DONT_EXPIRE_PASSWD = 0x10000;
public PasswordExpires()
{
//get our current domain policy
Domain domain = Domain.GetCurrentDomain();
DirectoryEntry root = domain.GetDirectoryEntry();
using (domain)
using (root)
{
this.policy = new DomainPolicy(root);
}
}
PasswordExpires, Part II
public DateTime GetExpiration(DirectoryEntry user)
{
int flags =
(int)user.Properties["userAccountControl"][0];
//check to see if password is set to expire
if(Convert.ToBoolean(flags & UF_DONT_EXPIRE_PASSWD))
{
//the user’s password will never expire
return DateTime.MaxValue;
}
long ticks = GetInt64(user, "pwdLastSet");
//user must change password at next login
if (ticks == 0)
return DateTime.MinValue;
//password has never been set
if (ticks == -1)
{
throw new InvalidOperationException(
"User does not have a password"
);
}
//get when the user last set their password;
DateTime pwdLastSet = DateTime.FromFileTime(
ticks
);
//use our policy class to determine when
//it will expire
return pwdLastSet.Add(
this.policy.MaxPasswordAge
);
}
PasswordExpires, Part III
public TimeSpan GetTimeLeft(DirectoryEntry user)
{
DateTime willExpire = GetExpiration(user);
if (willExpire == DateTime.MaxValue)
return TimeSpan.MaxValue;
if (willExpire == DateTime.MinValue)
return TimeSpan.MinValue;
if (willExpire.CompareTo(DateTime.Now) > 0)
{
//the password has not expired
//(pwdLast + MaxPwdAge)- Now = Time Left
return willExpire.Subtract(DateTime.Now);
}
//the password has already expired
return TimeSpan.MinValue;
}
private Int64 GetInt64(DirectoryEntry entry, string attr)
{
//we will use the marshaling behavior of
//the searcher
DirectorySearcher ds = new DirectorySearcher(
entry,
String.Format("({0}=*)", attr),
new string[] { attr },
SearchScope.Base
);
SearchResult sr = ds.FindOne();
if (sr != null)
{
if (sr.Properties.Contains(attr))
{
return (Int64)sr.Properties[attr][0];
}
}
return -1;
}
Checking Password Expiration
string adsPath = "LDAP://CN=User1,OU=Users,DC=domain,DC=com";
DirectoryEntry user = new DirectoryEntry(
adsPath,
null,
null,
AuthenticationTypes.Secure
);
string attrib = "msDS-User-Account-Control-Computed";
using (user)
{
user.RefreshCache(new string[] { attrib });
int flags = (int)user.Properties[attrib].Value
& (int)AdsUserFlags.PasswordExpired);
if (Convert.ToBoolean(flags)
{
//password has expired
Console.WriteLine("Expired");
}
}
No comments:
Post a Comment