C# - how to retrieve gMSA account password? - c#

how to retrieve gMSA account password in C#?
I need to use gMSA account to disable/enable AD account.
But I don't know how to get gMSA password?
public static bool DisableUserAccount(string sUserName)
{
UserPrincipal oUserPrincipal = GetUserForDoamin("D-Domain", sUserName);
oUserPrincipal.Enabled = false;
oUserPrincipal.Save();
return true;
}
public static UserPrincipal GetUserForDoamin(string sDomain, string sUserName)
{
PrincipalContext PrincipalDomain = null;
PrincipalDomain = GetPrincipalContext("D-Domain", "NONE"); ;
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(PrincipalDomain, sUserName);
return oUserPrincipal;
}
public static PrincipalContext GetPrincipalContext(string sDomainZone, string sOU)
{
PrincipalContext ServerCredentials = null;
string sDomainName = "";
sDomainName = "D-Domain";
ServerCredentials = new PrincipalContext(ContextType.Domain, sDomainName, "gMSA$", gMSApassword);
break;
return ServerCredentials;
}
At [GetPrincipalContext], gMSApassword is not nullable column. I try "" & null, but it is not working.
I don't know how to setup.

Related

How to check if current PC user is current logged on user?

For security reasons we want to check if the current PC user is the actual logged on user. To do this we want the user to re-enter their password and check his credentials with the domain. How could we accomplish this?
Sofar we tried this:
public static Boolean Authenticate(String password)
{
String user = WindowsIdentity.GetCurrent().Name;
using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
{
return PrincipalContext.ValidateCredentials(user, password);
}
}
But get a System.DirectoryServices.Protocols.LdapException, leaving the Environment.UserDomainName off also triggers this exception.
We also tried:
public static Boolean Authenticate(String password)
{
String user = WindowsIdentity.GetCurrent().Name;
using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Machine))
{
return PrincipalContext.ValidateCredentials(user, password);
}
}
But this returns true on any password.
After some searching I came across this answer. Turns out the Domain name is included in WindowsIdentity.GetCurrent().Name. As found under the remarks in the documentation.
Giving this as a working solution:
public static Boolean Authenticate(String password)
{
String user = WindowsIdentity.GetCurrent().Name; //Should be: DomainName\UserName
String[] DomainAndUserName = user.Split(new Char[] { '\\' }, 2);
if (DomainAndUserName.Length != 2) { return false; } // No DomainName ==> Wrong network;
using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, DomainAndUserName[0]))
{
return PrincipalContext.ValidateCredentials(DomainAndUserName[1], password);
}
}

How to check that windows account is disabled in C#?

I am trying to check if window account is disabled or not in active directory, for this reason I tried System.DirectoryServices.AccountManagement namespace but could not find any method to check if account is disable unlike IsAccountLockedOut method.
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
oUserPrincipal.IsAccountLockedOut();
We use this method:
var context = new DirectoryContext(DirectoryContextType.Domain, "domain");
using (var domainController = DomainController.FindOne(context))
{
using (var directorySearcher = domainController.GetDirectorySearcher())
{
directorySearcher.Filter = String.Format("(sAMAccountName={0})", "login");
directorySearcher.SizeLimit = 1;
var userDirectory = directorySearcher.FindOne();
using (var userDirectoryEntry = userDirectory.GetDirectoryEntry())
{
var active = userDirectoryEntry.IsActive();
}
}
}
IsActive - is an extension method:
public static bool IsActive(this DirectoryEntry directoryEntry)
{
if (directoryEntry.NativeGuid == null) return false;
var value = directoryEntry.Properties["userAccountControl"].Value;
if (value == null)
return true;
var flags = (int)value;
return !Convert.ToBoolean(flags & 0x0002);
}
So, get DirectoryEntry of your account and call this method.
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
bool? IsEnabled = oUserPrincipal.Enabled;
// if IsEnabled = true then User Account is Enabled
// if IsEnabled = false then User Account is Disabled

Add none UserPrincipal field to AD entry

I am trying to add a none UserPrincipal field to a small application, but I just cannot get it to work. I tried several ways to do this simple task, but I cannot get anything to work for me. I am trying to ADD a field called Company to be inserted into the Active Directory, but Company is not a field that can be inserted...
Any ideas? Please post a code example if you have one. I have this so far:
public bool CreateNewUser(string sUserName, string sPassword, string sGivenName, string sSurname, string email, string phone)
{
if (!IsUserExisting(sUserName))
{
string sOU = "OU=Users,OU=External,DC=external,DC=rootteck,DC=com";
PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);
UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);
//User Log on Name
oUserPrincipal.Name = sUserName;
oUserPrincipal.UserPrincipalName = sUserName + "#external.rootteck.com";
oUserPrincipal.GivenName = sGivenName;
oUserPrincipal.Surname = sSurname;
oUserPrincipal.EmailAddress = email;
oUserPrincipal.DisplayName = sGivenName + " " + sSurname;
if (phone != string.Empty) { oUserPrincipal.VoiceTelephoneNumber = phone; }
oUserPrincipal.PasswordNeverExpires = true;
oUserPrincipal.Save();
return true;
}
else
{
return false;
//return GetUser(sUserName);
}
}

c# comparing current windows user to AD group

I am trying to grab the current windows user and see if that user is part of a certain group in Active Directory. The username information finds "Harper\TSmith" which seems fine but when I get to the
UserPrincipal uPrincipal = Psearch.FindOne() as UserPrincipal
Line UPrincipal is null. Can not figure out why. I also have at the bottom a validator class that as a bool method to see if they are part of that particular group.
PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
UserPrincipal findUser = new UserPrincipal(principalCtx);
//findUser.Name = Environment.UserName;
findUser.Name = WindowsIdentity.GetCurrent().Name;
PrincipalSearcher pSearch = new PrincipalSearcher();
pSearch.QueryFilter = findUser;
UserPrincipal uPrincipal = pSearch.FindOne() as UserPrincipal;
Validator validate = new Validator();
//validate.IsUserInGroup("VisualOne", uPrincipal);
if (validate.IsUserInGroup("MyGroup", uPrincipal))
{
var MemberShipForm = new Membership();
MemberShipForm.Show();
}
public bool IsUserInGroup(string groupName, UserPrincipal user)
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, "Harper");
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "MyGroup");
if (user.IsMemberOf(group))
{
return true;
}
return false;
}
PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
UserPrincipal uPrincipal = UserPrincipal.Current;
if (validate.IsUserInGroup("MyGroup", uPrincipal))
{
var MemberShipForm = new Membership();
MemberShipForm.Show();
}

LDAP SetPassword Access is Denied

the following code was working for 3 months without any problems.
Since today I am getting the following error;
“Exception has been thrown by the target of an invocation”
and the inner exception;
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)"
The authentication function works. Here are my functions;
public bool Authenticate(string strUserName, string strPassword)
{
bool authenticated = false;
using (
var entry = new DirectoryEntry("LDAP://myldapserver", strUserName + "#domain", strPassword,
AuthenticationTypes.Secure))
{
try
{
object nativeObject = entry.NativeObject;
authenticated = true;
}
catch (DirectoryServicesCOMException ex)
{
return false;
}
}
return authenticated;
}
And the ChangePassword Method;
public bool ChangePassword(string strUserName, string strOldPassword, string strNewPassword)
{
const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
const long ADS_OPTION_PASSWORD_METHOD = 7;
const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
const int ADS_PASSWORD_ENCODE_CLEAR = 1;
string strPort = "636";
int intPort;
intPort = Int32.Parse(strPort);
try
{
string strUserString = "domain" + #"\" + strUserName.Trim();
var entry = new DirectoryEntry("LDAP://myldapserver", strUserString, strOldPassword,
AuthenticationTypes.Secure);
var search = new DirectorySearcher(entry);
string strFilter = "(SAMAccountName=" + strUserName + ")";
search.Filter = strFilter;
SearchResult result = search.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
**user.Invoke("SetPassword", new object[] { strNewPassword });**
user.CommitChanges();
user.Close();
}
catch (Exception exception)
{
string msg = exception.InnerException.Message;
return false;
}
return true;
}
It throws the expcetion when I invoke the SetPassword property.
Any help would be greatly appreciated.
Here is the example:-
PrincipalContext pr = new PrincipalContext(ContextType.Domain, "corp.local", "OU=" + OU + ",OU=Users,dc=corp,dc=local", username, password);
UserPrincipal us = new UserPrincipal(pr);
To Change the Password
user.SetPassword("setPassword");
If you want the user should change the password at next Logon, you can use like this.
user.ExpirePasswordNow();
Here is your full code:-
public static Boolean ResetPassword(string username, string password, string DomainId, string setpassword, Boolean UnlockAccount,Boolean NextLogon)
{
PrincipalContext pr = new PrincipalContext(ContextType.Domain, "corp.local", "dc=corp,dc=local", username, password);
UserPrincipal user = UserPrincipal.FindByIdentity(pr, DomainId);
Boolean flag = false;
if (user != null && user.Enabled == true)
{
if (UnlockAccount)
{
user.UnlockAccount();
}
user.SetPassword(setpassword);
if (NextLogon)
{
user.ExpirePasswordNow();
}
user.Save();
flag = true;
}
else
{
flag = false;
}
user.Dispose();
pr.Dispose();
return flag;
}
I found a good article here, if you want to use it in your way, have a look here,
http://www.primaryobjects.com/cms/article66.aspx

Categories