mattjohnsonpint/SimpleImpersonation

Powershell returns SecurityException

Closed this issue · 5 comments

I'm trying to execute some PS scripts as another user.

Here is the function :

public string GetSizeLecteurH(string GID, string Serveur)
        {
            using (SimpleImpersonation.Impersonation.LogonUser(Login.Split('\\')[0], Login.Split('\\')[1], Password, SimpleImpersonation.LogonType.Interactive))
            {
                using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    PowerShellInstance.AddScript(TestLecteurH);
                    PowerShellInstance.AddParameter("GID", GID);
                    PowerShellInstance.AddParameter("Serveur", Serveur);
                    //PowerShellInstance.AddParameter("credential", Credential);

                    Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
                    try
                    {
                        if (!PowerShellInstance.HadErrors) return PSOutput.Count > 0 ? PSOutput.ElementAt(0).ToString() : "pas de retour";
                        else return PowerShellInstance.Streams.Error.ElementAt(0).Exception + "";
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.StackTrace);
                        return "inexistant";
                    }
                }
            }
        }

I'm providing a string for the Login var as "domain\login".

When I execute this code, the Collection returns a "System.Security.SecurityException" : Requested registry access is not allowed

However it will works if I do not use the Impersonation and just run the entire script as the identity I'm passing to the LogonUser function.

I'm a bit lost, how can I avoid this error ?

Hmmm.. I'm not sure if one can impersonate the execution of a PowerShell environment or not. It would seem maybe not.

Maybe better to impersonate in the PowerShell script itself? I haven't tried it, but I see one such script here.

If I'm correct, you have to load the user profile before trying to access the registry.
CreateProcessWithLogonW and CreateProcessAsUser state, that they won't load the user profile, and this has to be done before calling them.

CreateProcessAsUser does not load the specified user's profile into the HKEY_USERS registry key

Those are typically called after LogonUser, so it seems that LogonUser also does not load the user profile.

And it seems, that @jamezor already implemented something similar: jamezor@d1b6ee5

Not sure if it will help this case or not, but please try again with the new API introduced for version 3.0.0. See the readme for details. Thanks.

With the new API, the handle is available, so the @jamezor changes referenced above should be able to be done outside of this library.