This is similar to, but not a dupe of, this question - however, where it sought information on manually joining a server to a domain (and was rightly redirected) I am looking for help with some code that programmatically joins a machine to a domain.
The scenario is that we have a launcher service that instantiates Amazon EC2 Server2008R1 VMs, optionally passing a Machine Name in through the User-Data stream. A process is baked into our images that checks User-Data for a name on bootup - If none is present then the VM remains outside of our Cloud domain, but if the name is present then the machine is renamed as specified and auto-joined to the domain.
Here's the problem - if I run this process manually any time after instance start, it works exactly as described; the machine name is changed, and the VM is joined to the domain (we force a restart to make this happen).
However, when running as a Scheduled Task (triggered on startup) the machine rename happens as expected, but the subsequent call to JoinDomainOrWorkgroup (see below) picks-up the old randomised machine name given to the VM by EC2 instead of the new name it has just been assigned.
This results in a WMI return code of 8525, we get a disconnected misnamed entry in the AD repository (of that randomised name) and the machine is not joined to the domain. The VM then restarts, and a second pass through the startup process (abnormally triggered because there is content in User-Data but the machine is not yet in the domain) executes all the same steps and succeeds.
It looks like the machine name is set in the first pass but not 'finalised', and JoinDomainOrWorkgroup still sees the original name. On the second pass, the machine name is already set properly, and so JoinDomainOrWorkgroup works as expected. Quite why the process behaves this way during startup, but works perfectly when run manually on an already-started VM, is I think the nub of the problem.
I've tried inserting a delay between the rename and join steps in case the call to JoinDomainOrWorkgroup was happening before the rename was finalised behind the scenes, but this hasn't helped - and I didn't really expect it to, since the whole process works perfectly when run manually. So it's probably a combination of a subtle difference in machine state during bootup and something silly in the code.
Maybe using System.Environment.MachineName in the SetDomainMembership method is inadvisable? But it stil fails even if I pass the new name in as a string as I do for SetMachineName. So I'm stumped.
Here's the WMI code that renames the machine:
/// <summary>
/// Set Machine Name
/// </summary>
public static bool SetMachineName(string newName)
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Setting Machine Name to '{0}'...", newName));
// Invoke WMI to populate the machine name
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
{
ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
inputArgs["Name"] = newName;
// Set the name
ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
// Weird WMI shennanigans to get a return code (is there no better way to do this??)
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if (ret == 0)
{
// It worked
return true;
}
else
{
// It didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to change Machine Name from '{0}' to '{1}'", System.Environment.MachineName, newName));
return false;
}
}
}
And here's the WMI code that joins it to the domain:
/// <summary>
/// Set domain membership
/// </summary>
public static bool SetDomainMembership()
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Setting domain membership of '{0}' to '{1}'...", System.Environment.MachineName, _targetDomain));
// Invoke WMI to join the domain
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
{
try
{
// Obtain in-parameters for the method
ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");
inParams["Name"] = "*****";
inParams["Password"] = "*****";
inParams["UserName"] = "*****";
inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account
// Execute the method and obtain the return values.
ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("JoinDomainOrWorkgroup return code: '{0}'", outParams["ReturnValue"]));
// Did it work? ** disabled so we restart later even if it fails
//uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
//if (ret != 0)
//{
// // Nope
// _lh.Log(LogHandler.LogType.Fatal, string.Format("JoinDomainOrWorkgroup failed with return code: '{0}'", outParams["ReturnValue"]));
// return false;
//}
return true;
}
catch (ManagementException e)
{
// It didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to join domain '{0}'", _targetDomain), e);
return false;
}
}
}
Apologies if this code looks mind-numbingly stupid - I'm new to WMI, and this is largely cribbed from examples I've found on the interwebs; if there's a smarter/neater way to do this then by all means demonstrate. If you can cure the problem at the same time, bonus points!
OK, here it is.
Firstly, the order of the fields in System Properties is a little misleading - you see Machine Name first, and Domain/Workgroup below that. This subconsciously affected my thinking, and meant my code copied that ordering by trying to set the name first, and then join the machine to the domain. Whilst this does work under some circumstances, it's not consistent or reliable. So the biggest lesson learned here is...
Join the domain first - then change
the machine name.
Yep, that's actually all there is to it. After numerous test iterations, it finally dawned on me that it might work better if I tried it this way around. I tripped-up on the change of name on my first pass, but quickly realised that it was still using the local system credentials - but now that the machine was joined to the domain at this point, it needed the same domain credentials as were used to join the domain itself. A fast bit of code-tweaking later, and we now have a consistently-reliable WMI routine that joins the domain and then changes the name.
It might not be the neatest implementation (feel free to comment on improvements) but it works. Enjoy.
/// <summary>
/// Join domain and set Machine Name
/// </summary>
public static bool JoinAndSetName(string newName)
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Joining domain and changing Machine Name from '{0}' to '{1}'...", Environment.MachineName, newName));
// Get WMI object for this machine
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + Environment.MachineName + "'")))
{
try
{
// Obtain in-parameters for the method
ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");
inParams["Name"] = "domain_name";
inParams["Password"] = "domain_account_password";
inParams["UserName"] = "domain_account";
inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account
_lh.Log(LogHandler.LogType.Debug, string.Format("Joining machine to domain under name '{0}'...", inParams["Name"]));
// Execute the method and obtain the return values.
ManagementBaseObject joinParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("JoinDomainOrWorkgroup return code: '{0}'", joinParams["ReturnValue"]));
// Did it work?
if ((uint)(joinParams.Properties["ReturnValue"].Value) != 0)
{
// Join to domain didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("JoinDomainOrWorkgroup failed with return code: '{0}'", joinParams["ReturnValue"]));
return false;
}
}
catch (ManagementException e)
{
// Join to domain didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to join domain '{0}'", _targetDomain), e);
return false;
}
// Join to domain worked - now change name
ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
inputArgs["Name"] = newName;
inputArgs["Password"] = "domain_account_password";
inputArgs["UserName"] = "domain_account";
// Set the name
ManagementBaseObject nameParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("Machine Rename return code: '{0}'", nameParams["ReturnValue"]));
if ((uint)(nameParams.Properties["ReturnValue"].Value) != 0)
{
// Name change didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to change Machine Name from '{0}' to '{1}'", Environment.MachineName, newName));
return false;
}
// All ok
return true;
}
}
Ok little update after all these years if somebody would need it.
WMI does not contain JoinDomain anymore only workgroup (WIN 10, Build 1909). You can use netapi32.dll
More info here:
https://learn.microsoft.com/en-us/windows/win32/api/lmjoin/nf-lmjoin-netjoindomain
Little fast example:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
static extern uint NetJoinDomain(
string lpServer,
string lpDomain,
string lpAccountOU,
string lpAccount,
string lpPassword,
JoinOptions NameType);
[Flags]
enum JoinOptions
{
NETSETUP_JOIN_DOMAIN = 0x00000001,
NETSETUP_ACCT_CREATE = 0x00000002,
NETSETUP_ACCT_DELETE = 0x00000004,
NETSETUP_WIN9X_UPGRADE = 0x00000010,
NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020,
NETSETUP_JOIN_UNSECURE = 0x00000040,
NETSETUP_MACHINE_PWD_PASSED = 0x00000080,
NETSETUP_DEFER_SPN_SET = 0x10000000
}
public static uint domainjoin(string server, string domain, string OU, string account, string password)
{
try
{
uint value1 = NetJoinDomain(server, domain, OU, account, password, (JoinOptions.NETSETUP_JOIN_DOMAIN | JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED | JoinOptions.NETSETUP_ACCT_CREATE));
return value1;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return 11;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var succes = domainjoin(null, "mydomain.local", null, "administrator", "UltraSecretPasword");
MessageBox.Show(succes.ToString());
}
}
Related
I am very new to the LDAP and Active Directory integration portion. Although I successfully configured my local machine to access Active Directory domain controller, when I deployed it on one of our server neither through IP address of the domain nor through domain name it was accessible.
My website is in ASP.NET C#.
It was getting this error:
The specified domain either does not exist or could not be contacted.
My method written to access AD is here:
private SearchResultCollection sResults { get; set; }
sResults = null;
public void SearchByUsername(string username)
{
try
{
// initiate a directory entry
private const string ldapPath = "LDAP://192.168.0.190/OU=Domain Users,DC=mydomain,DC=net"
dEntry = new DirectoryEntry(ldapPath);
dSearcher = new DirectorySearcher(dEntry);
dSearcher.Filter = "(&(objectClass=user)(sAMAccountname= " + username + "))";
performSearch();
getValues();
}
catch (Exception)
{
throw;
}
}
private void performSearch()
{
// perform search in Active Directory
sResults = dSearcher.FindAll();
}
private void getValues()
{
// loop through results of search
foreach (SearchResult sResult in sResults)
{
Employee emp = new Employee();
emp.CN = getProperty(sResult, "cn");
emp.FirstName = getProperty(sResult, "givenName");
emp.LastName = getProperty(sResult, "sn");
emp.Username = getProperty(sResult, "sAMAccountname");
emp.Email = getProperty(sResult, "mail");
Employees.Add(emp);
}
}
Above method works very well on my local machine both with IP address and domain name. Server where I am trying this to work is Windows Server 2012 R2.
I ran command nltest /dclist:mydomain.net and made sure that the server is within the domain as it returned me details. i.e. DC name, IP address, domain name.
Is there any syntactical issue I have run into? OR is it related to configuration issue like DNS ?
Also, like to mention as I tried searching about this on www.serverfault.com but couldn't gather much details.
Please suggest me direction.
Finally things seemed working out.
Earlier I mentioned that I made sure that the machine I am working on is in the domain but things were slightly different there. The machine I am trying to make things work is not actually in the domain but in the workgroup.
Below two Netdom commands helped me identifying this situation.
netdom verify - with this command it is found that machine hasn't joined domain.
netdom join - with this command, was able to join machine to network domain.
Reference: https://technet.microsoft.com/en-us/library/cc772217.aspx
Once it is in domain, Active Directory became immediately accessible.
Question first, explanation later: How can I get the GC server for any given LDAP server?
To understand my needs, let me explain:
I had to extend Henning Krause's ExchangeAddressListService (I am not sure whether I should/may c'n'p all of Henning's code into this post?) to get useful debug output:
private DirectoryEntry GetDirectoryEntry(string path, string protocol)
{
var ldapPath = string.IsNullOrEmpty(path) ? string.Format("{0}:", protocol) : string.Format("{0}://{1}", protocol, path);
dbg.Add("Getting DirectoryEntry for path " + ldapPath);
return new DirectoryEntry(ldapPath);
}
public ActiveDirectoryConnection(Debug dbg)
{
this.dbg = dbg;
}
and to allow for selection of a certain domain:
internal AddressList(string path, ActiveDirectoryConnection connection, string domain)
{
_Path = path;
_Connection = connection;
_Domain = domain;
}
...
private IEnumerable<AddressList> GetAddressLists(string containerName)
{
string exchangeRootPath;
using (var root = _Connection.GetLdapDirectoryEntry(_Domain+"/RootDSE"))
...
foreach (SearchResult addressBook in searchResultCollection)
{
yield return
new AddressList((string)addressBook.Properties["distinguishedName"][0], _Connection, _Domain);
}
...
}
Now I have a problem with the domain because it seems as if for some domains SOMEDOMAIN the Global Catalog cannot be accessed via GC://SOMEDOMAIN. This is my code I use:
var domain = User.Identity.Name.Split('\\')[0]; // SOMEDOMAIN\SomeUser -> Domain is SOMEDOMAIN
dbg.Add("User NETBIOS domain is "+domain);
AddressListService addressListService = new ExchangeAddressListService(connection,domain);
IEnumerable<AddressList> addressLists = addressListService.GetGlobalAddressLists();
AddressList addressList = addressLists.First()
try {
IEnumerable<SearchResult> searchResults = addressList.GetMembers("displayName", "distinguishedname", "mail")
} catch(Exception e) {
dbg.Add("Error in GetMembers: "+e.Message);
return new AjaxAnswer(dbg.Flush());
}
It produces the error log:
User NETBIOS domain is SOMEDOMAIN
Getting DirectoryEntry for path LDAP://SOMEDOMAIN/RootDSE
Getting DirectoryEntry for path LDAP://CN=Microsoft Exchange, CN=Services, CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path LDAP://CN=All Global Address Lists,CN=Address Lists Container, CN=MYMAIL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path LDAP://CN=Default Global Address List,CN=All Global Address Lists,CN=Address Lists Container,CN=MYMAIL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path GC://SOMEDOMAIN
Error in GetMembers: The server is not operational.
Not all DC are GC. So GC://SOMEDOMAIN may fail if SOMEDOMAIN is not a GC.
In my project, I use the DsGetDcName Win32 function to discover the GC.
Details of DsGetDcName function:
http://msdn.microsoft.com/en-us/library/ms675983%28v=vs.85%29.aspx
See below for how to pinvoke the call:
http://www.pinvoke.net/default.aspx/netapi32.dsgetdcname
As I know System.DirectoryServices.ActiveDirectory also provide classes to handle GC.
e.g. Forest.GlobalCatalogs
I already use the DsGetDcName function, so never tried this before.
Research:
Similar Issue with workaround, but not actual solution to existing problem
Similar issue pointing to Microsoft End Point update as culprit
The above links are the most suited to my problem, I have also viewed every similar question listed by Stack Overflow upon creating this post, and only the above referenced questions fit my issue.
Background:
I have been using UserPrincipal.GetAuthorizationGroups for permissions for specific page access running IIS 7.5 on Server 2008 R2 in a C#.NET 4.0 web forms site for 2 and a half years. On May 15 2013 we removed a primary Domain controller running Server 2008 (not r2) and replaced it with a Server 2012 Domain Controller. The next day we started receiving the exception listed below.
I use Principal Context for Forms Authentication. The username/pass handshake succeeds and the auth cookie is properly set, but the subsequent Principal Context call that also calls UserPrincipal.GetAuthorizationGroups fails intermittently. We've resolved a few BPA issues that appeared in the Server 2012 Domain Controller but this has yet to resolve the issue. I also instituted a cron that runs on two separate servers. The two servers will fail at Group SID resolution at different times though they are running the same code base. (A dev environment and production environment).
The issue resolves itself temporarily upon web server reboot, and also on the dev server it will resolve itself after 12 hours of not functioning. The production server will usually stop functioning properly until a reboot without resolving itself.
At this point I am trying to refine the cron targeting specific Domain Controllers in the network as well as the new DC and using the standard LDAP query that is currently failing to yield more targeted exception times. Thus far we've found on one web server that there is no pattern to the days at which it fails, but it will recover within roughly 12 hours. The latest results show Group SID resolution failure between 8AM-8PM then it recovers, several days later it will fail at 8pm and recover at 8am then run fine for another 12 hours and fail again. We are hoping to see if it is just a specific server communication issue or to see if it is the entire set of Domain Controllers.
Exception:
Exception information:
Exception type: PrincipalOperationException
Exception message: An error (1301) occurred while enumerating the groups.
The group's SID could not be resolved.
at System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target, IntPtr[] pSids)
at System.DirectoryServices.AccountManagement.SidList..ctor(SID_AND_ATTR[] sidAndAttr)
at System.DirectoryServices.AccountManagement.AuthZSet..ctor(Byte[] userSid, NetCred credentials, ContextOptions contextOptions, String flatUserAuthority, StoreCtx userStoreCtx, Object userCtxBase)
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p)
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups()
Question:
Given the above information, does anyone have any idea why decommissioning the Windows Server 2008 (not r2) and implementing a new Server 2012 DC would cause UserPrincipal.GetAuthorizationGroups to fail with the 1301 SID resolution error?
Ideas on eliminating possible causes would also be appreciated.
Disclaimer:
This is my first post to Stack Overflow, I often research here but have not joined in discussions until now. Forgive me if I should have posted elsewhere and feel free to point out better steps before posting.
UPDATE 13-JUN-2013:
On the 12th of June I addressed the possibility of items not disposed causing the issue.
The time frame has been too short to determine if the adjusted code has fixed the issue, but I will continue to update as we work towards a resolution such that maybe with any luck someone here can lend a hand.
Original Code
public bool isGroupMember(string userName, ArrayList groupList)
{
bool valid = false;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain_server + ".domain.org:636", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
// find the user in the identity store
UserPrincipal user =
UserPrincipal.FindByIdentity(
ctx,
userName);
// get the groups for the user principal and
// store the results in a PrincipalSearchResult object
PrincipalSearchResult<Principal> groups =
user.GetAuthorizationGroups();
// display the names of the groups to which the
// user belongs
foreach (Principal group in groups)
{
foreach (string groupName in groupList)
{
if (group.ToString() == groupName)
{
valid = true;
}
}
}
return valid;
}
Updated Code
public bool isGroupMember(string userName, ArrayList groupList, string domain_server)
{
bool valid = false;
try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain_server + ".domain.org:636", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
{
// find the user in the identity store
UserPrincipal user =
UserPrincipal.FindByIdentity(
ctx,
userName);
try
{
// get the groups for the user principal and
// store the results in a PrincipalSearchResult object
using (PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups())
{
// display the names of the groups to which the
// user belongs
foreach (Principal group in groups)
{
foreach (string groupName in groupList)
{
if (group.ToString() == groupName)
{
valid = true;
}
}
group.Dispose();
}
}//end using-2
}
catch
{
log_gen("arbitrary info");
return false;
}
}//end using-1
}
catch
{
log_gen("arbitrary info");
return false;
}
return valid;
}
I have just run into this same issue and the info I have managed to track down may be helpful; as above we have seen this problem where the domain controller is running Server 2012 - firstly with a customer deployment and then replicated on our own network.
After some experimentation we found that our code would run fine on Server 2012, but hit the 1301 error code when the client system was running Server 2008. The key information about what was happening was found here:
MS blog translated from German
The hotfix referred to in the link below has fixed the problem on our test system
SID S-1-18-1 and SID S-1-18-2 can't be mapped
Hope this is helpful for someone! As many have noted this method call seems rather fragile and we will probably look at implementing some alternative approach before we hit other issues.
Gary
Here's my solution. It seems to work consistently well. Because the problem happens when iterating over the collection, I use a different approach when iterating in order to handle the exception without blocking the actual iterating:
private string[] GetUserRoles(string Username)
{
List<string> roles = new List<string>();
try
{
string domain = Username.Contains("\\") ? Username.Substring(0, Username.IndexOf("\\")) : string.Empty;
string username = Username.Contains("\\") ? Username.Substring(Username.LastIndexOf("\\") + 1) : Username;
if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(username))
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username);
if (user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
int count = groups.Count();
for (int i = 0; i < count; i++)
{
IEnumerable<Principal> principalCollection = groups.Skip(i).Take(1);
Principal principal = null;
try
{
principal = principalCollection.FirstOrDefault();
}
catch (Exception e)
{
//Error handling...
//Known exception - sometimes AD can't query a particular group, requires server hotfix?
//http://support.microsoft.com/kb/2830145
}
if (principal!=null && principal is GroupPrincipal)
{
GroupPrincipal groupPrincipal = (GroupPrincipal)principal;
if (groupPrincipal != null && !string.IsNullOrEmpty(groupPrincipal.Name))
{
roles.Add(groupPrincipal.Name.Trim());
}
}
}
}
}
}
catch (Exception e)
{
//Error handling...
}
return roles.ToArray();
}
We experienced this issue when our infrastructure team brought a 2012 Domain Controller online. We also had pre-2012 DCs in place and so we experienced the issue intermittently. We came up with a fix which I wanted to share - it has 2 parts.
First of all, install the hotfix mentioned by Gary Hill. This will resolve the following issue:
An error (1301) occurred while enumerating the groups. The group's SID could not be resolved.
We thought we were home free after installing this hotfix. However, after it was installed we got a different intermittent error. Certain groups that we were interrogating had a null sAMAccountName property. The actual property was populated in Active Directory but it was incorrectly being returned with a null value by the API. I presume this is a bug somewhere in the Active Directory API but I don't know any more than that.
Fortunately we were able to work around the issue by switching to use the group Name property instead of the sAMAccountName property. This worked for us. I believe, that sAMAccountName is effectively deprecated and exists only for backwards compatibility reasons. That being the case it seemed a reasonable change to make.
I enclose a cut down version of our GetRolesForUser code to demonstrate the change in place.
using (var context = new PrincipalContext(ContextType.Domain, _domainName))
{
try
{
var p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
if (p == null) throw new NullReferenceException(string.Format("UserPrincipal.FindByIdentity returned null for user: {0}, this can indicate a problem with one or more of the AD controllers", username));
var groups = p.GetAuthorizationGroups();
var domain = username.Substring(0, username.IndexOf(#"\", StringComparison.InvariantCultureIgnoreCase)).ToLower();
foreach (GroupPrincipal group in groups)
{
if (!string.IsNullOrEmpty(group.Name))
{
var domainGroup = domain + #"\" + group.Name.ToLower();
if (_groupsToUse.Any(x => x.Equals(domainGroup, StringComparison.InvariantCultureIgnoreCase)))
{
// Go through each application role defined and check if the AD domain group is part of it
foreach (string role in roleKeys)
{
string[] roleMembers = new [] { "role1", "role2" };
foreach (string member in roleMembers)
{
// Check if the domain group is part of the role
if (member.ToLower().Contains(domainGroup))
{
// Cache the Application Role (NOT the AD role)
results.Add(role);
}
}
}
}
}
group.Dispose();
}
}
catch (Exception ex)
{
throw new ProviderException("Unable to query Active Directory.", ex);
}
}
Hope that helps.
I experienced error code 1301 with UserPrincipal.GetAuthorizationGroups while using a brand new virtual development domain which contained 2 workstations and 50 users/groups (many of which are the built in ones). We were running Windows Server 2012 R2 Essentials with two Windows 8.1 Enterprise workstations joined to the domain.
I was able to recursively obtain a list of a user's group membership using the following code:
class ADGroupSearch
{
List<String> groupNames;
public ADGroupSearch()
{
this.groupNames = new List<String>();
}
public List<String> GetGroups()
{
return this.groupNames;
}
public void AddGroupName(String groupName)
{
this.groupNames.Add(groupName);
}
public List<String> GetListOfGroupsRecursively(String samAcctName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, System.Environment.UserDomainName);
Principal principal = Principal.FindByIdentity(ctx, IdentityType.SamAccountName, samAcctName);
if (principal == null)
{
return GetGroups();
}
else
{
PrincipalSearchResult<Principal> searchResults = principal.GetGroups();
if (searchResults != null)
{
foreach (GroupPrincipal sr in searchResults)
{
if (!this.groupNames.Contains(sr.Name))
{
AddGroupName(sr.Name);
}
Principal p = Principal.FindByIdentity(ctx, IdentityType.SamAccountName, sr.SamAccountName);
try
{
GetMembersForGroup(p);
}
catch (Exception ex)
{
//ignore errors and continue
}
}
}
return GetGroups();
}
}
private void GetMembersForGroup(Principal group)
{
if (group != null && typeof(GroupPrincipal) == group.GetType())
{
GetListOfGroupsRecursively(group.SamAccountName);
}
}
private bool IsGroup(Principal principal)
{
return principal.StructuralObjectClass.ToLower().Equals("group");
}
}
I'm in an environment with multiple domain forests and trusts. I have pretty much this exact same code running on a web site form used to perform user security group lookups across the different domains.
I get this exact error in one of the very large domains where group membership can include 50+ different groups. It works fine in other domains forests.
In my research I found a thread that looks unrelated, but actually has the same stack trace. It is for a remote application running on SBS. The thread mentions that the error is caused by unresolvable SIDS in a group. I believe these would be what are known as "tombstoned" SIDS in active directory. See the thread here.
The thread suggests that finding the tombstoned enteries and removing them from the groups solves the problem. Is it possible the error you are receiving is because SIDS are getting tombstoned every 12 hours by a separate unrelated process? Ultimately, I believe this is a bug in the framework, and that the method should not crash because of tombstoned/unresolvable SIDS.
Good luck!
If anyone is interested this is a VB.NET version of the same code.
Few things you have to do before this code can work
1) You have to reference the assembly System.DirectoryServices
2) Make sure to pass "theusername" variable without the domain, so if your domain is "GIS" and your username is "Hussein" Windows generally authenticate you as GIS\Hussein. So you have to send in just purely the username "Hussein". I worked out the case sensitive stuff.
3) The method GetGroupsNew takes a username and returns a list of groups
4) The method isMemberofnew takes a username and a group and verifies that this user is part of that group or not, this is the one I was interested in.
Private Function getGroupsNew(theusername As String) As List(Of String)
Dim lstGroups As New List(Of String)
Try
Dim allDomains = Forest.GetCurrentForest().Domains.Cast(Of Domain)()
Dim allSearcher = allDomains.[Select](Function(domain)
Dim searcher As New DirectorySearcher(New DirectoryEntry("LDAP://" + domain.Name))
searcher.Filter = [String].Format("(&(&(objectCategory=person)(objectClass=user)(userPrincipalName=*{0}*)))", theusername)
Return searcher
End Function)
Dim directoryEntriesFound = allSearcher.SelectMany(Function(searcher) searcher.FindAll().Cast(Of SearchResult)().[Select](Function(result) result.GetDirectoryEntry()))
Dim memberOf = directoryEntriesFound.[Select](Function(entry)
Using entry
Return New With { _
Key .Name = entry.Name, _
Key .GroupName = DirectCast(entry.Properties("MemberOf").Value, Object()).[Select](Function(obj) obj.ToString()) _
}
End Using
End Function)
For Each user As Object In memberOf
For Each groupName As Object In user.GroupName
lstGroups.Add(groupName)
Next
Next
Return lstGroups
Catch ex As Exception
Throw
End Try
End Function
Private Function isMemberofGroupNew(theusername As String, thegroupname As String) As Boolean
Try
Dim lstGroups As List(Of String) = getGroupsNew(theusername)
For Each sGroup In lstGroups
If sGroup.ToLower.Contains(thegroupname.ToLower) Then Return True
Next
Return False
Catch ex As Exception
Throw
End Try
End Function
we had a similar issue after upgrading the domain controller to 2012. Suddenly my call to user.GetAuthorizationGroups() started failing; I was getting the same exception you were (error 1301). So, I changed it to user.GetGroups(). That worked for a little while, then started failing intermittently on "bad username or password". My latest workaround appears to fix it, for the moment at least. Instead of calling either of those, after constructing the user object, I also construct a group object, one for each group I want to see if the user is a member of. ie, "user.IsMemberOf(group)". That seems to work.
try
{
using (HostingEnvironment.Impersonate())
{
using (var principalContext = new PrincipalContext(ContextType.Domain, "MYDOMAIN"))
{
using (var user = UserPrincipal.FindByIdentity(principalContext, userName))
{
if (user == null)
{
Log.Debug("UserPrincipal.FindByIdentity failed for userName = " + userName + ", thus not authorized!");
isAuthorized = false;
}
if (isAuthorized)
{
firstName = user.GivenName;
lastName = user.Surname;
// so this code started failing:
// var groups = user.GetGroups();
// adGroups.AddRange(from #group in groups where
// #group.Name.ToUpper().Contains("MYSEARCHSTRING") select #group.Name);
// so the following workaround, which calls, instead,
// "user.IsMemberOf(group)",
// appears to work (for now at least). Will monitor for issues.
// test membership in SuperUsers
const string superUsersGroupName = "MyApp-SuperUsers";
using (var superUsers = GroupPrincipal.FindByIdentity(principalContext, superUsersGroupName))
{
if (superUsers != null && user.IsMemberOf(superUsers))
// add to the list of groups this user is a member of
// then do something with it later
adGroups.Add(superUsersGroupName);
}
I had same exception. If someone don't wanna used "LDAP", use this code. Cause I'm had nested groups, I'm used GetMembers(true) and it's little bit longer in time than GetMembers().
https://stackoverflow.com/a/27548271/1857271
or download fix from here: http://support.microsoft.com/kb/2830145
Facing the same problem enumerating authorization groups and the patches noted in the answer did not apply to our web server.
Manually enumerating and ignoring the trouble causing groups is working well, however:
private static bool UserIsMember(string usr, string grp)
{
usr = usr.ToLower();
grp = grp.ToLower();
using (var pc = new PrincipalContext(ContextType.Domain, "DOMAIN_NAME"))
{
using (var user = UserPrincipal.FindByIdentity(pc, usr))
{
var isMember = false;
var authGroups = user?.GetAuthorizationGroups().GetEnumerator();
while (authGroups?.MoveNext() ?? false)
{
try
{
isMember = authGroups.Current.Name.ToLower().Contains(grp);
if (isMember) break;
}
catch
{
// ignored
}
}
authGroups?.Dispose();
return isMember;
}
}
}
I had the problem that if i am connected over VPN and use groups=UserPrincipal.GetGroups() then the Exception occures when iterating over the groups.
If someone want to read all groups of a user there is following possibility (which is faster than using GetGroups())
private IList<string> GetUserGroupsLDAP(string samAccountName)
{
var groupList = new List<string>();
var domainConnection = new DirectoryEntry("LDAP://" + serverName, serverUser, serverUserPassword); // probably you don't need username and password
var samSearcher = new DirectorySearcher();
samSearcher.SearchRoot = domainConnection;
samSearcher.Filter = "(samAccountName=" + samAccountName + ")";
var samResult = samSearcher.FindOne();
if (samResult != null)
{
var theUser = samResult.GetDirectoryEntry();
theUser.RefreshCache(new string[] { "tokenGroups" });
var sidSearcher = new DirectorySearcher();
sidSearcher.SearchRoot = domainConnection;
sidSearcher.PropertiesToLoad.Add("name");
sidSearcher.Filter = CreateFilter(theUser);
foreach (SearchResult result in sidSearcher.FindAll())
{
groupList.Add((string)result.Properties["name"][0]);
}
}
return groupList;
}
private string CreateFilter(DirectoryEntry theUser)
{
string filter = "(|";
foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
{
var SID = new SecurityIdentifier(resultBytes, 0);
filter += "(objectSid=" + SID.Value + ")";
}
filter += ")";
return filter;
}
I have a fairly odd requirement to be able to impersonate a user, when I'm already impersonating another, using C#.
I'm writing an app to allow the management of Active Directory users. This app will provide the ability for anyone in the company to view and maintain certain details about themselves (some of which will not actually be saved to Active Directory, but some of which will), for managers to be able to view and maintain details about their team, and for HR to be able to view and maintain details about anyone.
For obvious reasons I don't want to develop or test this against the live domain. We have recently ported all users over to this domain from another domain, which means I can actually test against the old domain without affecting anything. However, to enable me to do this I have to impersonate my old account on the old domain, which I do on loading the application.
Although for me everything will work fine as I'm setup as a domain admin, going forward obviously not all users will be domain admins, and won't be able to write to AD under their own account, and therefore we have another domain admin user setup specifically for this application, whenever data needs to be saved to AD that user is impersonated. This was working great before when I was testing against an Active Directory I'd setup on a virtual machine because I was logging onto the local domain, however that didn't allow me to step through the code in Visual Studio so debugging was slow, and hence I've stopped using that virtual machine and am using this old domain. Now I'm already impersonating another user (i.e. my old domain account), when it then tries to impersonate the domain admin user it fails with an "System.Security.SecurityException: Access is denied." exception. The line this fails on is just writing out some debugging information using "WindowsIdentity.GetCurrent().Name".
If I change my code so I'm actually logging in using the new domain admin rather than my old account, the first time it goes through it logs in successfully (so the credentials are correct), however when it then goes through and tries to do the same again to write to AD it fails with the above exception. Therefore I think it must be a problem with trying to do a nested impersonate.
Is it possible to do a nested impersonate?
Below is the code I'm using:
private static WindowsImpersonationContext ImpersonateUser(out string result, string sUsername,
string sDomain, string sPassword)
{
// initialize tokens
var pExistingTokenHandle = new IntPtr(0);
var pDuplicateTokenHandle = new IntPtr(0);
// if domain name was blank, assume local machine
if (sDomain == "")
{
sDomain = Environment.MachineName;
}
try
{
result = null;
const int logon32ProviderDefault = 0;
// create token
const int logon32LogonInteractive = 2;
// get handle to token
var bImpersonated = LogonUser(sUsername, sDomain, sPassword,
logon32LogonInteractive,
logon32ProviderDefault,
ref pExistingTokenHandle);
// did impersonation fail?
if (!bImpersonated)
{
var nErrorCode = Marshal.GetLastWin32Error();
result = "LogonUser() failed with error code: " + nErrorCode + "\r\n";
}
// Get identity before impersonation
result += string.Format("Before impersonation: {0}\r\n", WindowsIdentity.GetCurrent().Name);
var bRetVal = DuplicateToken(pExistingTokenHandle, (int)SecurityImpersonationLevel.SecurityImpersonation,
ref pDuplicateTokenHandle);
// did DuplicateToken fail?
if (bRetVal)
{
// create new identity using new primary token
var newId = new WindowsIdentity(pDuplicateTokenHandle);
var impersonatedUser = newId.Impersonate();
// check the identity after impersonation
result += "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
return impersonatedUser;
}
else
{
var nErrorCode = Marshal.GetLastWin32Error();
CloseHandle(pExistingTokenHandle); // close existing handle
result += "DuplicateToken() failed with error code: " + nErrorCode + "\r\n";
return null;
}
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
{
CloseHandle(pExistingTokenHandle);
}
if (pDuplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(pDuplicateTokenHandle);
}
}
}
When this is called for the nested impersonation which fails, "bImpersonated" is actually "true", as is bRetVal, which suggests its worked, however when it gets to "WindowsIdentity.GetCurrent().Name" it fails with the exception above.
I hope this makes sense, and would appreciate any assistance.
For instances when Active Directory takes too long to replicate data between sites, I need to ensure that the local AD replica contains the most up to date information.
How can I get a list of DomainControllers for the current site?
I haven't found anything on Codeproject or on StackOverflow
Going to all this trouble is probably wasted effort. Unless you are experiencing issues with the built in logic for finding a domain controller you should just go with the built in method that returns one. According to Microsoft it automatically tries to find the closes one: http://technet.microsoft.com/en-us/library/cc978016.aspx.
Just use the static DomainController.FindOne method and pass in your directorycontext.
Update
Alright, try the code below, let me know how it works for you. It pings each, returns the roundtrip time, if -1 (no connection) it skips it. Flags PDC status if present. Orders by PDC status, followed by ping round trip.
static void Main(string[] args)
{
var dcsInOrder = (from DomainController c in Domain.GetCurrentDomain().DomainControllers
let responseTime = Pinger(c.Name)
where responseTime >=0
let pdcStatus = c.Roles.Contains(ActiveDirectoryRole.PdcRole)
orderby pdcStatus, responseTime
select new {DC = c, ResponseTime = responseTime}
).ToList();
foreach (var dc in dcsInOrder)
{
System.Console.WriteLine(dc.DC.Name + " - " + dc.ResponseTime);
}
System.Console.ReadLine();
}
private static int Pinger(string address)
{
Ping p = new Ping();
try
{
PingReply reply = p.Send(address, 3000);
if (reply.Status == IPStatus.Success) return (int)reply.RoundtripTime;
}
catch { }
return -1;
}
First, I'll answer the question that you actually asked:
System.DirectoryServices.ActiveDirectory.ActiveDirectorySite.GetComputerSite().Servers
But it seems like you're asking how to make sure that you're talking to the closest domain controller possible. Windows doesn't exactly provide this functionality, the best it will do is give you a domain controller in the same site that the code is running from.
I think the first thing to check is that you have your sites and subnets configured correctly. Run Active Directory Sites and Services, and make sure that subnets and domain controllers are assigned to the correct sites.
This MSDN page (and the Technet article in Peter's answer) says that you must be searching by the DNS name for the DC Locator to attempt to find a DC in the current site. I don't know if the Name property of the Domain class is the DNS domain name.
I have to assume that DomainController.FindOne is a wrapper for DsGetDcName. At that link, you can find how to turn on tracing for that function. You can use this if you still have problems, or maybe you should just PInvoke this function.
Here is a code sample that has no hard coding of DCs. Comments and criticism are welcome.
/// <summary>
/// For best results ensure all hosts are pingable, and turned on.
/// </summary>
/// <returns>An ordered list of DCs with the PDCE first</returns>
static LinkedList<DomainController> GetNearbyDCs()
{
LinkedList<DomainController> preferredDCs = new LinkedList<DomainController>();
List<string> TestedDCs = new List<string>();
using (var mysite = ActiveDirectorySite.GetComputerSite())
{
using (var currentDomain = Domain.GetCurrentDomain())
{
DirectoryContext dctx = new DirectoryContext(DirectoryContextType.Domain, currentDomain.Name);
var listOfDCs = DomainController.FindAll(dctx, mysite.Name);
foreach (DomainController item in listOfDCs)
{
Console.WriteLine(item.Name );
if (IsConnected(item.IPAddress))
{
// Enumerating "Roles" will cause the object to bind to the server
ActiveDirectoryRoleCollection rollColl = item.Roles;
if (rollColl.Count > 0)
{
foreach (ActiveDirectoryRole roleItem in rollColl)
{
if (!TestedDCs.Contains(item.Name))
{
TestedDCs.Add(item.Name);
if (roleItem == ActiveDirectoryRole.PdcRole)
{
preferredDCs.AddFirst(item);
break;
}
else
{
if (preferredDCs.Count > 0)
{
var tmp = preferredDCs.First;
preferredDCs.AddBefore(tmp, item);
}
else
{
preferredDCs.AddFirst(item);
}
break;
}
}
}
}
else
{
// The DC exists but has no roles
TestedDCs.Add(item.Name);
if (preferredDCs.Count > 0)
{
var tmp = preferredDCs.First;
preferredDCs.AddBefore(tmp, item);
}
else
{
preferredDCs.AddFirst(item);
}
}
}
else
{
preferredDCs.AddLast(item);
}
}
}
}
return preferredDCs;
}
static bool IsConnected(string hostToPing)
{
string pingurl = string.Format("{0}", hostToPing);
string host = pingurl;
bool result = false;
Ping p = new Ping();
try
{
PingReply reply = p.Send(host, 3000);
if (reply.Status == IPStatus.Success)
return true;
}
catch { }
return result;
}
Here's my approach using powershell but I'm sure it's a simple implementation in c#, etc. If DHCP is setup correctly, the Primary DNS server in your subnet should be the closest Domain Controller. So the following code should grab the first DNS IP and resolve it to the hostname of the closest DC. This doesn't require RSAT or credentials and contains no specific properties of the current domain.
$NetItems = #(Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'True'" -ComputerName $env:COMPUTERNAME)
foreach ($objItem in $NetItems)
{
if ($objItem.{DNSServerSearchOrder}.Count -ge 1)
{
$PrimaryDNS = $objItem.DNSServerSearchOrder[0]
$domain = $objItem.DNSDomain
break
}
}
[System.Net.Dns]::GetHostbyAddress($PrimaryDNS).hostname -replace ".$($domain)",""