Adding Local User to Local Admin Group II - c#

I am writing a C# program to add a local user to a local group (Administrators, for example). I can create a new user, but I am not able to add it to a group. What I have found is if in this group is any domain user or group it is not working. When I try to add it to the group without domain users it is ok. I run this program as a local admin.
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
{
UserPrincipal user = new UserPrincipal(pc, Login, Password, true);
user.Save();
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "Administrators");
group.Members.Add(user);
group.Save();
}
When I run it as domain admin it works ok, but I need it only as local admin.
Any insight would be greatly appreciated.
PS:
I found this:
Adding Local User to Local Admin Group
, it is great but it is also not working...
Update
I can search for this new user, it exists.
The exception I am getting is
System.Runtime.InteropServices.COMException. Network path not found

Related

How to create AD User belonging to Domain Admins group in C#

I'm working on a C# project which auto-creates new Active Directory users and let them access to the AD server.
I have made a general user with the following code, but since the user does not belong to Domain Admins, it could not access to the server.
Domain domain = Domain.GetCurrentDomain();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal principal = new UserPrincipal(context);
principal.Name = name;
principal.UserPrincipalName = name + "#" + domain.Name;
principal.SamAccountName = name;
principal.Enabled = true;
principal.SetPassword(password);
principal.PasswordNeverExpires = true;
principal.Save();
Is there a way to include which group the new user belong in the code? Or after creating the account, adding the user to Domain Admins group might be another solution but I couldn't figure out how to do this either.
Any advice would be appreciated.
You just need to find the group and add the user you created. Like this:
var group = GroupPrincipal.FindByIdentity(context, "Domain Admins");
group.Members.Add(principal);
group.Save();
The code will have to run with credentials that can add someone to the Domain Admins group, which is likely a domain admin account itself.

UserPrincipal doesn't let me add new user

I'm having a bit of a problem when trying to add a new user or trying to access an already existing user in the Active Directory through my C# program.
var principalContext = new PrincipalContext(ContextType.Domain, "domain", "OU=Users,OU=SI");
UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountStr);
It's throwing the "An operations error ocurred" exception. I found out that it's supposed to that if the user doesn't have the right permission for the Active Directory but I am running the program as administrator with the account of someone who can add users to the AD. So I really don't know what could be wrong. When I try to add a new user I try it like this:
var principalContext = new PrincipalContext(ContextType.Domain, "domain", "OU=Users,OU=SI");
UserPrincipal usr = new UserPrincipal(principalContext);
The code for the existing user already breaks when I call FindByIdentity. The code for the new user however breaks after I try to set some values for the new user principle. For example:
usr.Surname = sn;
The extended error says it's:
SvcErr: DSID-031007DF, problem 5012 (DIR_ERROR)
So any idea as to what might be causing it if it's not a permission problem?
You have to provide a full Distinguished Name for the OU, including the domain. This is not valid:
"OU=Users,OU=SI"
Something like this would be (if your domain was "domain.com"):
"OU=Users,OU=SI,DC=domain,DC=com"

LDAP Path And Permissions To Query Local User Directory?

I am working on a web application, ASP.NET, C#. Users are required to log in using an account local to the machine the app is running on, which I'll call "cyclops" for this example. I want the app to be able to query the local directory of users and groups to determine what groups the user is in. The code looks something like this:
DirectoryEntry entry = new DirectoryEntry("WinNT://cyclops/Users", "SomeServiceAccount",
"SvcAcctP#$$word", AuthenticationTypes.Secure);
entry.RefreshCache();
// Etc.
My two problems are:
That's pretty clearly not the correct path to use, but my research
and experimentation hasn't found the right answer. This MSDN
article talks about local paths, but doesn't fill in the blanks.
Do I use "LDAP://cyclops/Users", "WinNT://localhost/Users",
"WinNT://cyclops/cn=Users"?
As you can see, I'm providing the
credentials of a local service account. That account needs
permission to access the local directory, but I have no idea where
to set those permissions. Is it a specific file somewhere? Does
the account need to be a member of a particular group?
My experimentation has produced many errors: "The group name could not be found.", "The provider does not support searching...", "The server is not operational.", "Unknown error (0x80005004)", etc.
Thank you for your time...
-JW
WinNT requires the following format
WinNT://<domain/server>/<object name>,<object class>
To get groups of a given user, use
using (DirectoryEntry user = new DirectoryEntry("WinNT://./UserAccount,user"))
{
foreach(object group in (IEnumerable)user.Invoke("Groups",null))
{
using(DirectoryEntry g = new DirectoryEntry(group))
{
Response.Write(g.Name);
}
}
}
where
UserAccount is a name of required user.
dot stands for current machine (you can replace it with cyclops or use Environment.MachineName)
user credentials ("SomeServiceAccount", "SvcAcctP#$$word") might be required, depends on setup
To get users in a particular group, use
using (DirectoryEntry entry = new DirectoryEntry("WinNT://./Users,group"))
{
foreach (object member in (IEnumerable)entry.Invoke("Members"))
{
using(DirectoryEntry m = new DirectoryEntry(member))
{
Response.Write(m.Name);
}
}
}
where
Users is a name of group

Adding an AD User to a Machine Local group via AccountManagement

I wanted to implement adding an AD user to a local machine group via User and GroupPrincipals, and I thought it would work nice and easy. Unfortunately, I continue to get a General Access Denied error. It's possible I just don't understand the proper authentication happening, but I assumed I had the proper access set up. Here is a code snippet of what is being called:
var ctx = new PrincipalContext(ContextType.Machine,
Environment.MachineName,
ConfigurationManager.AppSettings["MyUser"],
ConfigurationManager.AppSettings["MyPW"]);
var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "LocalGrp");
var adUser = ADService.GetUserByDomainUserName(vModel.ContactId);
var adCtx = new PrincipalContext(ContextType.Domain,
"myDomain.com",
ConfigurationManager.AppSettings["MyUser"],
ConfigurationManager.AppSettings["MyPW"])
;
var user = UserPrincipal.FindByIdentity(adCtx,
IdentityType.Guid,
adUser.UserGuid.ToString());
if (grp != null &&
user != null)
{
if(!user.IsMemberOf(grp))
{
grp.Members.Add(user);
grp.Save();
}
}
The user is found, the group is found, but when I add and reach the grp.Save() step, I am treated with a General Access Denied exception. with the ctx being opened via the "MyUser" and "MyPW", I thought that would allow group manipulation on the machine since that account is part of the machine local administrators group. Can I not mix machine/domain contexts in this manner, or is there an authentication problem I am just missing?
Did you run Visual Studio in Admin mode. Even though your login has admin rights, your program needs to elevate itself to use those rights if you didn't start it elevated.
See:
http://chrisforbesblogs.net/2010/02/26/run-visual-studio-2010-as-administrator-by-default/
Relevant Google search

Auth as administrator

I've done an application that basically goes through all active users on a network via DirectoryEntry, where I'm able to get each computers Username (login id), this is done by DE.UserName (DirectoryEntry).
Alright, so far so good, now with my problem; whenever I try to fetch it's password it's throwing an exception saying I need to have admin rights in order to get the password of each connected pc.
I am not the owner of the network, so I'm wondering if there's any way to auth as an admin or change your group to Administrator, or in any way bypass this so I can access it's password?
Code:
DirectoryEntry computers = new DirectoryEntry("WinNT://JBVAS");//The domain
IEnumerator enumerator = computers.Children.GetEnumerator();
while(enumerator.MoveNext())
{
DirectoryEntry entry = enumerator.Current as DirectoryEntry;
Console.WriteLine("Username: {0}{1}Password: {2}",
entry.Username, Environment.NewLine, entry.Password);
}
You could use impersonation to make your code (temporary) run under a higher privileged user.
I wrote an easy-to-use impersonation class some years back, you can find it over at CodeProject.com.
An example could be:
using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
// code that executes under the new context
}
Put your Active Directory code that needs administrator permissions inside the using block.

Categories