I am trying to create a function where I input a Security Group name and return a list of the security permissions.
How do I get a list of security permissions like read, write, full control etc. for a Security Group such as Domain Controllers, Domain Guests, etc. from Active Directory using C#?
You need to check the path of the LDAP connection that you are making to communicate with the Active Directory server.
For example:
DirectoryEntry rootDSE = null;
rootDSE = new DirectoryEntry("LDAP://OU=" + department + ",OU=Users,OU=" + ou + ",dc=corp,dc=local", username, password);
Now in that case I need only groups that exist in Department → Users → OU → DC
Same as in your case. You can define on which OU your security group exist.
After that I can fetch a group like this:
DirectorySearcher ouSearch = new DirectorySearcher(rootDSE);
ouSearch.PageSize = 1001;
ouSearch.Filter = "(objectClass=group)";
ouSearch.SearchScope = SearchScope.Subtree;
ouSearch.PropertiesToLoad.Add("name");
SearchResultCollection allOUS = ouSearch.FindAll();
foreach (SearchResult oneResult in allOUS)
{
dt.Rows.Add(oneResult.Properties["name"][0].ToString());
}
rootDSE.Dispose();
Now in case of permissions
Permissions are stored on the individual file system items, e.g. files and/or directories - or other objects (like registry keys, etc.). When you have an AD group or user account, you can read its SID (Security Identifier) property - that SID will show up in ACLs (Access Control Lists) all over Windows - but from the user or group, there's no mechanism to get all permissions it might have anywhere in the machine/server.
Permissions for files and directories can e.g. be retrieved using the .GetAccessControl() method on the FileInfo and DirectoryInfo classes:
FileInfo info = new FileInfo(#"D:\test.txt");
FileSecurity fs = info.GetAccessControl();
DirectoryInfo dir = new DirectoryInfo(#"D:\test\");
DirectorySecurity ds = dir.GetAccessControl();
I hope this is what you are looking for!
Related
How can I get a list of users from active directory? Is there a way to pull username, firstname, lastname? I saw a similar post where this was used:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
I have never done anything with active directory so I am completely lost. Any help would be greatly appreciated!
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.
There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.
For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value);
Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.
If you want to filter y active accounts add this to Harvey's code:
UserPrincipal userPrin = new UserPrincipal(context);
userPrin.Enabled = true;
after the first using. Then add
searcher.QueryFilter = userPrin;
before the find all. And that should get you the active ones.
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here:
https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here:
https://learn.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
Certainly the credit goes to #Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
Include the System.DirectoryServices.dll, then use the code below:
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
userNames += child.Name + Environment.NewLine ;
}
}
MessageBox.Show(userNames);
I have an C# network application that prompts admins for network proxy authentication information. I ask the user if they want to save this information, which if they choose yes, I encrypt in a unique local file for the user. I would then like to remove all file permissions except the user that created it, but all other users to have the ability to delete the file.
Now, I found MS article below, but it's not helping if I don't know the default users that were setup on the file in the first place. Is there a remove all file permissions? I can then add the individual rights I'm wanting to setup for full access by current user and delete permissions for "All Users" or "Authenticated Users", which looks to be different depending on version of Windows.
http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx
I figured it out..
public void SetFileSecurity(String filePath, String domainName, String userName)
{
//get file info
FileInfo fi = new FileInfo(filePath);
//get security access
FileSecurity fs = fi.GetAccessControl();
//remove any inherited access
fs.SetAccessRuleProtection(true, false);
//get any special user access
AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
//remove any special access
foreach (FileSystemAccessRule rule in rules)
fs.RemoveAccessRule(rule);
//add current user with full control.
fs.AddAccessRule(new FileSystemAccessRule(domainName + "\\" + userName, FileSystemRights.FullControl, AccessControlType.Allow));
//add all other users delete only permissions.
fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow));
//flush security access.
File.SetAccessControl(filePath, fs);
}
If you need to remove for the specific group , you can use this method ;
public static void RemoveGroupPermission(string path, string group_name)
{
long begin = Datetime.Now.Ticks;
DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.RemoveAccessRuleAll(new FileSystemAccessRule(Environment.UserDomainName +
#"\" + group_name, 0, 0));
dirInfo.SetAccessControl(dirSecurity);
long end = DateTime.Now.Ticks;
Console.WriteLine("Tick : " + (end - begin));
}
Impersonation may be help you to solve this out.
The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.
click Here to see implimentation
Attempting to find printers / shares in Active Directory using C#.
This is my sample code that works for users however I cannot seen to be able to find a printer using the same concept. (I am new to Active Directory).
DirectoryEntry entry = new DirectoryEntry();
entry.Path = "LDAP://xxx.xxx.xx.xx/CN=Printers;DC=domainName, DC=com";
entry.Username = #"domainName.com\Administrator";
entry.Password = "admin";
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
Any assistance would be greatly appreciated.
In contrast to users (CN=Users) there is no CN=Printers container in Active Directory after installation.
Printers are published in Active Directory in the releated computer container. What does
releated computer container mean? Well, open Active Directory Users and Computers MMC snap-in and
follow this procedure:
Select advanced features in the view menu.
Select Users, Contancts, Groups and Computers as containers in the view menu.
Navigate to the computer object (which is now displayed as container)
your printer belongs to.
Click on the plus sign of the computer container. There you will see
the printer object.
So, you see printers are published in Active Directory in the releated computer container (the printer belongs to) and not in one common container such as CN=Printers.
So, to search for a printer object in Active Directory, you have to specify
a different LDAP path. For example you could specify the root of your Active Directory
as the search root:
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Path = "LDAP://xxx.xxx.xxx.xxx/DC=domainName,DC=com";
entry.Username = #"domainName.com\Administrator";
entry.Password = "SecurePassword";
using (DirectorySearcher search = new DirectorySearcher(entry))
{
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
}
}
Of course, you could also specify as search root the LDAP path to the computer where your printer
is shared on. For example if your printer is shared on a computer called server10 and this computer is located in the CN=Computers container, then specify this LDAP path:
LDAP://xxx.xxx.xxx.xxx/CN=server10,CN=Computers,DC=domainName,DC=com
If you share a printer on the domain controller then the LDAP path is slightly different (because by default domain controller computer objects are located in the OU=Domain Controllers organizational unit):
LDAP://xxx.xxx.xxx.xxx/CN=DomainControllerName,OU=Domain Controllers,DC=domainName,DC=com
How can I get a list of users from active directory? Is there a way to pull username, firstname, lastname? I saw a similar post where this was used:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
I have never done anything with active directory so I am completely lost. Any help would be greatly appreciated!
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.
There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.
For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value);
Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.
If you want to filter y active accounts add this to Harvey's code:
UserPrincipal userPrin = new UserPrincipal(context);
userPrin.Enabled = true;
after the first using. Then add
searcher.QueryFilter = userPrin;
before the find all. And that should get you the active ones.
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here:
https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here:
https://learn.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
Certainly the credit goes to #Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
Include the System.DirectoryServices.dll, then use the code below:
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
userNames += child.Name + Environment.NewLine ;
}
}
MessageBox.Show(userNames);
I have this code to connect to Active Directory and get all the groups that exist, it works and returns all the groups in results :
DirectoryEntry dirEnt = new DirectoryEntry();
using (DirectorySearcher srch = new DirectorySearcher(dirEnt, "(objectClass=Group)"))
{
srch.PageSize = 1000;
SearchResultCollection results = srch.FindAll();
}
I now want to return users of a specific group i.e. Administrators, how would I go about this?
I had tried changing (objectClass=Group) to (objectClass=Group)(cn=admin) but then it returns no results.
All the best
Here's a reference about how to in Active Directory:
Howto: (Almost) Everything In Active Directory via C#