I have a WPF app that needs to determine if the current user is a member of an AD group.
I created AD group "TestGroup" in the following location in the AD "tree":
Apps/Shared/Groups/TestGroup
I'm testing the app under VS 2010, running as my domain login, which is a member of TestGroup (and yes, I've logged-off/on since I added myself to that group).
My domain name is ABC.
I first get the WindowsPrincipal by doing:
if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
Thread.CurrentPrincipal = new WindowsPrincipal(GetWindowsIdentity());
(which, BTW, always invokes GetWindowsIdentity()... could that be the problem?)
Then I do:
_windowsPrincipal.IsInRole(#"ABC\TestGroup")
... which always returns false.
Am I passing the correct string to IsInRole? Or do I need to specify the full path of the AD "tree", like: #"ABC\Apps\Shared\Groups\TestGroup" (I've tried just about every permutation). Or could this problem be caused by running in debug under VS?
Or ????
Thanks!
DadCat
Per my comment: It appears that the problem is not in the code. Instead, I had not rebooted since I added myself to the group. I had thought that a logoff/logon ("sign off/on") was all that was needed, but apparently a full reboot is necessary. Maybe this is a new "feature" of Win8.
Related
I have read other questions on SO in regards to security and registry keys, nothing has helped me solve my particular use case scenario.
Here's my scenario:
What I'm Trying To Do
I want to, in code, delete a windows event log.
The Problem
When executing the function, I receive a System.ComponentModel.Win32Exception. The exception message is "Access is denied".
How I Am Doing It Currently
I am using an impersonator function that I wrote which wraps around the EventLog.Delete function, it drops me into a user context that has full access to the EventLog Registry Hive. Subsequently the logs I am interested in also have full access for this particular user.
My Question
Why do I receive a "Access Is Denied" if the user I am running under (through impersonation) has full access to the log in question? I've tested my Impersonation function and it works as expected for other code I've written. I don't get why I would get access denied for this.
In another scenario with my impersonation function it works just fine, for example if I tried to write to a file that the user context that is running the program does not have write access to, then I would not be able to write to the text file, however if I use my impersonation to drop into a user context that does have write access then it works just fine (I can write to the file). So I just don't understand why the same concept can't be applied to registry keys.
What am I missing here?
The Code
Exception Message
My Test
Where sw-test is a user I created for testing purposes, it has full access permissions to the registry we are trying to delete.
[TestMethod]
public void DeleteEventLog_ValidatedUser_DeleteLog()
{
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd"))
{
Logging logging = new Logging();
logging.DeleteEventLog("testLog");
}
}
Okay I eventually got around to figuring this out, there were two issues at play here that were causing the mentioned exception being thrown, they are as follows:
1. Visual Studio was NOT running in administrator mode.
Not running visual studio in administrator mode was one part of the problem, this seems to be associated with access tokens in the windows OS. According to a source I read, if I run a program without UAC on (which is my scenario, I have it off), then the program being run gets a copy of my access token. However if I have UAC enabled, the program gets a copy of my access token but it is a restricted access token. (see: What precisely does 'Run as administrator' do?) - To be honest this doesn't really make sense in my case, why do I have to run as admin if I have UAC off? Shouldn't visual studio have an unrestricted copy of my access token? I am in the administrator group with UAC off...
2. Not Specifying NewCredentials As a Logon32Type In Impersonation
I don't really understand it but as soon as I specified this for my impersonation everything started working perfectly, I read a blog about it, it talks about how it was introduced in the VISTA days and how it was mainly used to specify credentials to outbound network connections to servers, and was mainly used to remedy security-related issues server-side. Don't see how it correlates to interfacing with local event logs though. (see: https://blogs.msdn.microsoft.com/winsdk/2015/08/25/logonuser-logon32_logon_new_credentials-what-is-this-flag-used-for/)
Code
using (new Impersonator(Environment.UserDomainName, "sw-test", "pswd", Advapi32.Logon32Type.NewCredentials))
{
EventLog.CreateEventSource("testSource", "testLog");
EventLog.Delete("testLog");
}
Where the NewCredentials is an int 9
Does someone get any hint for accessing Microsoft.Web.Administration.ServerManager.Sites collection on Win8.1 (and Win8) if the user got no right on file "%SystemRoot%\System32\inetsrv\config\redirection.config" ?
Because the user will get UnauthorizedAccessException in this case...
More largely, on Win8 you can get into trouble on any Microsoft.Web.Administration.ServerManager property if your user has no right on "%SystemRoot%\System32\inetsrv\config".
This works perfectly on Win7, W2008 and W2012..
HowTo: http://www.iis.net/learn/manage/scripting/how-to-use-microsoftwebadministration
I need this in a WiX c# Custom Action launched in 'client' step (while in UI) to browse installed Web sites and applications on them for unicity check on new WebApplication name.
Of course, I cant find any relevant answer for this while googling. There are only a few answers out and they hint to launch with elevated privilege or change the rights on the folder, witch of course is not feasible in a regular user setup UI process.
Ex: http://sharepointyankee.com/2011/03/30/system-unauthorizedaccessexception-filename-redirection-config/
Just for information, it seems to be no way to get rid of this...
So I choose to modify my Custom Action to ignore this case by catching UnauthorizedAccessException and still set success for unicity check and return a success for the CA call.
In this case in client step I won't get a failure, with counterpart that I can't get the real result of the unicity check. But I get the result if it wont fail with UnauthorizedAccessException and I can spawn a dialog to the user inviting him to change the site name.
Then in server step where by the way this check ever works I do the same test to be able to fail the setup with a clear message if the website is not unique.
This is not the best for the user who must then restart the setup to change the site name but it works and avoid strange failures by trying to create two websites with the same name.
I have tried a lot of solutions but I am unable to get the desired result. I am privy to the fact that one can use Environment.SpecialFolder enumeration. I have already tried them all but in vain. I am writing a service that needs to access this folder in C#>
C:\Users\Shahbaaz\efb
Working on Win 7, .Net 4, VS13
UPDATE:
MY problem is that I can't programmatically access C:\Users\Shahbaaz.Shahbaaz is the name of the logged in account. The efb folder was used for illustration only. Sorry about that. I had used UserProfile enum but ended up with C:\SYSTEM directory. CommonDocuments et al give me the C:\Users\Public... directories. Also, if I just use Environment.Username, it gives me SYSTEM instead of the logged in username. Hope this helps!
I think I know what's going on. Wrote a small test:
[Test]
public void PrintAllSpecialFolders()
{
var values = Enum.GetValues(typeof(Environment.SpecialFolder));
Console.WriteLine("Printing special folder paths:");
foreach (Environment.SpecialFolder value in values)
{
Console.WriteLine("{0}: {1}", value, Environment.GetFolderPath(value, Environment.SpecialFolderOption.None));
}
}
That clearly shows the expected result (Windows 7):
...
UserProfile: C:\Users\<myusername>
...
But: You're using a service (which your tag indicates) and you're probably running the service under the LocalSystem account. The local system account doesn't have an user folder in the expected place. Either run your service under your user account or accept the given path as profile folder for the LocalSystem account. Do not try to access your user account from LocalSystem. You'll probably get a permission error.
I have the following block of code that queries Active Directory for users by Group Name using System.DirectoryServices.AccountManagement:
var domainContext = new PrincipalContext(ContextType.Domain, "company.container.internal");
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.Name, "Lvl1Users");
if (groupPrincipal != null)
{
//Read the values
}
Now the site uses the following:
IIS7 on Win2k8
Windows Authentication
Impersonation = True
App Pool on .NET 4.0 using 'NETWORK SERVICE' as the account
On my local machine (you know how this goes) it all works great. My peers that try it locally also it works well. However once deployed to the server it shows the following:
An operations error occurred.
Everything I research says it's a permissions issue. 1 thing to note, on my local machine I'm on the MainNetwork domain which is the parent to company.container.internal domain which I am querying. The IIS machine is on company.container.internal and is querying the same domain. So honestly, I would think the more challenging situation is reading AD on my local machine which is on a different domain, but it works. On the server which is querying the same domain, it fails.
Here is what I've tried, and none of these has worked:
Change AppPool to 'LocalSystem'
Change AppPool to use a static super-duper Admin account
Used Impersonation in code to manipulate the context of the calls in a local block with an admin user on the MainNetwork domain.
Used Impersonation in code to manipulate the context of the calls in a local block with an admin user on the company.container.internal domain.
Adding in using (HostingEnvironment.Impersonate())
What gives here? I have tried impersonating every type of power admin on both domains, and used multiple AppPool settings, and I keep getting the same error. Is there anything that needs to change in the code with the declaration of the domains, or is there a permissions issue I'm missing?
I figured this out and it turned out that using HostingEnvironment.Impersonate() was still at the root to solve the problem. I had already tried this, but there was another issue with my code.
The issue is often that the context for which the Active Directory calls is made is under a user that does not have permissions (also can happen when identity impersonate="true" in ASP.NET, due to the fact that the users token is a "secondary token" that cannot be used when authenticating against another server from: http://bit.ly/1753RjA).
The following code will ensures that the block of code running, is run under the context of say the AppPool (i.e. NETWORKSERVICE) that the ASP.NET site is running under.
using (HostingEnvironment.Impersonate())
{
var domainContext = new PrincipalContext(ContextType.Domain, "myDomain.com");
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.Name, "PowerUsers");
if (groupPrincipal != null)
{
//code to get the infomation
}
}
However, one super important detail is that all the code calling Active Directory must be in that block. I had used some code a team member of mine wrote that was returning a LINQ query results of type Users (custom class), but not evaluating the expression (bad practice). Therefore the expression tree was returned instead of the results.
What ended up happening is the calling code eventually evaluated the results and the An operations error occurred message still appeared. I though the code fix above didn't work. When in fact it did, but there was code evaluating the results outside the block.
In a nutshell, make sure all code to access Active Directory is inside that using block and the exception should be fixed one the service/app is deployed to the server.
I am attempting to Impersonate an administrator account from a LocalSystem Service in order to get data from administrators HKEY CURRENT USER registry - in order to impersonate I am using the codeproject code found at the following site written by Uwe Keim: Impersonator
My source code is as follows:
using (new Impersonator("user", ".", "pass"))
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\CompanyName");
string sValue = rk.GetValue("Value", "").ToString();
rk2.Close();
}
My expectation was that sValue would be from the user/pass account (as I am impersonating it) but oddly enough it is still the sValue from the LocalSystem account where my service is runnning ...
Any clues on what I am doing wrong? Any help would be much appreciated.
Thanks,
I know this is an old thread but I recently came across the same issue (albeit from a C++ Windows service) and thought I'd share my findings, because many forums have asked the same question and none have left a satisfactory answer.
Basically, I've found two ways to approach this, though this is an answer more for C applications rather than .NET (I haven't tested with pinvoke but it may work).
Solution 1:
Instead of using RegOpenKey, use RegOpenCurrentUser() to get the key handle. Apparently, the reason RegOpenKey doesn't get the impersonated user's key is because HKEY_CURRENT_USER is cached in the running thread.
Solution 2:
RegDisablePredefinedCache(). This disables the cache mentioned above and lets subsequent calls to HKEY_CURRENT_USER be of the actual impersonated user. This is the solution I went with.
Hope this helps.
Everything I've read on the subject seems to indicate that impersonation should get you access to the HKEY_CurrentUser for the impersonated account. However, it could be a quirk in the .NET Registry implementation.
This is just a hunch, and an untested one at that, but have you considered using Registry.Users instead of Registry.CurrentUser?
You'll need to find the SID for the Administrator account, but you should be able to deduce that using Regedit
By default the HKEY_CURRENT_USER handle is cached on a process wide basis. So when you impersonate a user and then access the current user hive you will be accessing the hive of the user that started the process not the user being impersonated. This is true for all Win32 processes not just .Net. If you wish to disable this caching so that all current user calls go to the correct user hive under HKEY_USERS then you must call RegDisablePredefinedCache via pInvoke.
Be warned that if the user being impersonated has not had their profile loaded then any CurrentUser requests will be forwarded to the .DEFAULT user. So you may also need to call LoadUserProfile.
Disabling the handle caching will also cause a slight slowdown in all CurrentUser requests.
I'm guessing you're going to find that you're out of luck. It can't be done.
If applications were able to impersonate an Administrator account and write values to the Registry in Windows, it would present a huge security hole. My guess is that the Registry.CurrentUser property will ALWAYS reference the user running your application...whether or not you try impersonation or not.
EDIT
Turns out that I didn't read the implementation details of the Impersonator code you were using. Your problem could be something completely different.
Does your code refer to the Registry static class prior to your impersonation code being run? If so, that would be the problem. If you look at the Registry.CurrentUser property in Reflector, you'll see that it is set by the static constructor of the Registry object. Static constructors get called when the static object is first referenced.
In your case, if you're referencing the Registry object (whether it involves CurrentUser or not) the static constructor is being called which is setting CurrentUser to your original user...not the Impersonated account.