[ACCEPTED]-Starting a process with credentials from a Windows Service-windows-services

Accepted answer
Score: 19

When you launch a new process using ProcessStartInfo 16 the process is started in the same window 15 station and desktop as the launching process. If 14 you are using different credentials then 13 the user will, in general, not have sufficient 12 rights to run in that desktop. The failure 11 to initialize errors are caused when user32.dll 10 attempts to initialize in the new process 9 and can't.

To get around this you must first 8 retrieve the security descriptors associated 7 with the window station and desktop and 6 add the appropriate permissions to the DACL 5 for your user, then launch your process 4 under the new credentials.

EDIT: A detailed 3 description on how to do this and sample 2 code was a little long for here so I put 1 together an article with code.

        //The following security adjustments are necessary to give the new 
        //process sufficient permission to run in the service's window station
        //and desktop. This uses classes from the AsproLock library also from 
        //Asprosys.
        IntPtr hWinSta = GetProcessWindowStation();
        WindowStationSecurity ws = new WindowStationSecurity(hWinSta,
          System.Security.AccessControl.AccessControlSections.Access);
        ws.AddAccessRule(new WindowStationAccessRule("LaunchProcessUser",
            WindowStationRights.AllAccess, System.Security.AccessControl.AccessControlType.Allow));
        ws.AcceptChanges();

        IntPtr hDesk = GetThreadDesktop(GetCurrentThreadId());
        DesktopSecurity ds = new DesktopSecurity(hDesk,
            System.Security.AccessControl.AccessControlSections.Access);
        ds.AddAccessRule(new DesktopAccessRule("LaunchProcessUser",
            DesktopRights.AllAccess, System.Security.AccessControl.AccessControlType.Allow));
        ds.AcceptChanges();

        EventLog.WriteEntry("Launching application.", EventLogEntryType.Information);

        using (Process process = Process.Start(psi))
        {
        }
Score: 17

Based on the answer by @StephenMartin.

A new process launched using the Process class 12 runs in the same window station and desktop 11 as the launching process. If you are running 10 the new process using different credentials, then 9 the new process won't have permissions to 8 access the window station and desktop. What 7 results in errors like 0xC0000142.

The following 6 is a "compact" standalone code 5 to grant a user an access to the current 4 window station and desktop. It does not 3 require the AsproLock library.

Call the GrantAccessToWindowStationAndDesktop method 2 with the username you use to run the Process (Process.StartInfo.UserName), before 1 calling Process.Start.

public static void GrantAccessToWindowStationAndDesktop(string username)
{
    IntPtr handle;
    const int WindowStationAllAccess = 0x000f037f;
    handle = GetProcessWindowStation();
    GrantAccess(username, handle, WindowStationAllAccess);
    const int DesktopRightsAllAccess = 0x000f01ff;
    handle = GetThreadDesktop(GetCurrentThreadId());
    GrantAccess(username, handle, DesktopRightsAllAccess);
}

private static void GrantAccess(string username, IntPtr handle, int accessMask)
{
    SafeHandle safeHandle = new NoopSafeHandle(handle);
    GenericSecurity security =
        new GenericSecurity(
            false, ResourceType.WindowObject, safeHandle,
            AccessControlSections.Access);

    security.AddAccessRule(
        new GenericAccessRule(
            new NTAccount(username), accessMask, AccessControlType.Allow));
    security.Persist(safeHandle, AccessControlSections.Access);
}

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetProcessWindowStation();

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetThreadDesktop(int dwThreadId);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern int GetCurrentThreadId();

// All the code to manipulate a security object is available in .NET framework,
// but its API tries to be type-safe and handle-safe, enforcing a special
// implementation (to an otherwise generic WinAPI) for each handle type.
// This is to make sure only a correct set of permissions can be set
// for corresponding object types and mainly that handles do not leak.
// Hence the AccessRule and the NativeObjectSecurity classes are abstract.
// This is the simplest possible implementation that yet allows us to make use
// of the existing .NET implementation, sparing necessity to
// P/Invoke the underlying WinAPI.

private class GenericAccessRule : AccessRule
{
    public GenericAccessRule(
        IdentityReference identity, int accessMask, AccessControlType type) :
        base(identity, accessMask, false, InheritanceFlags.None,
             PropagationFlags.None, type)
    {
    }
}

private class GenericSecurity : NativeObjectSecurity
{
    public GenericSecurity(
        bool isContainer, ResourceType resType, SafeHandle objectHandle,
        AccessControlSections sectionsRequested)
        : base(isContainer, resType, objectHandle, sectionsRequested)
    {
    }

    new public void Persist(
        SafeHandle handle, AccessControlSections includeSections)
    {
        base.Persist(handle, includeSections);
    }

    new public void AddAccessRule(AccessRule rule)
    {
        base.AddAccessRule(rule);
    }

    #region NativeObjectSecurity Abstract Method Overrides

    public override Type AccessRightType
    {
        get { throw new NotImplementedException(); }
    }

    public override AccessRule AccessRuleFactory(
        System.Security.Principal.IdentityReference identityReference, 
        int accessMask, bool isInherited, InheritanceFlags inheritanceFlags,
        PropagationFlags propagationFlags, AccessControlType type)
    {
        throw new NotImplementedException();
    }

    public override Type AccessRuleType
    {
        get { return typeof(AccessRule); }
    }

    public override AuditRule AuditRuleFactory(
        System.Security.Principal.IdentityReference identityReference,
        int accessMask, bool isInherited, InheritanceFlags inheritanceFlags,
        PropagationFlags propagationFlags, AuditFlags flags)
    {
        throw new NotImplementedException();
    }

    public override Type AuditRuleType
    {
        get { return typeof(AuditRule); }
    }

    #endregion
}

// Handles returned by GetProcessWindowStation and GetThreadDesktop
// should not be closed
private class NoopSafeHandle : SafeHandle
{
    public NoopSafeHandle(IntPtr handle) :
        base(handle, false)
    {
    }

    public override bool IsInvalid
    {
        get { return false; }
    }

    protected override bool ReleaseHandle()
    {
        return true;
    }
}
Score: 3

Based on the answer by @Stephen Martin and Martin Prikryl.

This code helps you to run a process with 4 different user credentials from a service.
I 3 have now optimized the source code.
The 2 removal and setting of rights is now also 1 possible.

namespace QlikConnectorPSExecute
{
    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Security.AccessControl;
    using System.Security.Principal;
    #endregion

    //inspired by: http://stackoverflow.com/questions/677874/starting-a-process-with-credentials-from-a-windows-service
    public class WindowsGrandAccess : IDisposable
    {
        #region DLL-Import
        // All the code to manipulate a security object is available in .NET framework,
        // but its API tries to be type-safe and handle-safe, enforcing a special implementation
        // (to an otherwise generic WinAPI) for each handle type. This is to make sure
        // only a correct set of permissions can be set for corresponding object types and
        // mainly that handles do not leak.
        // Hence the AccessRule and the NativeObjectSecurity classes are abstract.
        // This is the simplest possible implementation that yet allows us to make use
        // of the existing .NET implementation, sparing necessity to
        // P/Invoke the underlying WinAPI.

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetProcessWindowStation();

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetThreadDesktop(int dwThreadId);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern int GetCurrentThreadId();
        #endregion

        #region Variables && Properties
        public static int WindowStationAllAccess { get; private set; } = 0x000f037f;
        public static int DesktopRightsAllAccess { get; private set; } = 0x000f01ff;

        private GenericSecurity WindowStationSecurity {get; set;}
        private GenericSecurity DesktopSecurity { get; set; }
        private int? OldWindowStationMask { get; set; }
        private int? OldDesktopMask { get; set; }
        private NTAccount AccountInfo { get; set; }
        private SafeHandle WsSafeHandle { get; set; }
        private SafeHandle DSafeHandle { get; set; }
        #endregion

        #region Constructor & Dispose
        public WindowsGrandAccess(NTAccount accountInfo, int windowStationMask, int desktopMask)
        {
            if (accountInfo != null)
                Init(accountInfo, windowStationMask, desktopMask);
        }

        public void Dispose()
        {
            try
            {
                if (AccountInfo == null)
                    return;

                RestAccessMask(OldWindowStationMask, WindowStationAllAccess, WindowStationSecurity, WsSafeHandle);
                RestAccessMask(OldDesktopMask, DesktopRightsAllAccess, DesktopSecurity, DSafeHandle);
            }
            catch (Exception ex)
            {
                throw new Exception($"The object \"{nameof(WindowsGrandAccess)}\" could not be dispose.", ex);
            }
        }
        #endregion

        #region Methods
        private void Init(NTAccount accountInfo, int windowStationMask, int desktopMask)
        {
            AccountInfo = accountInfo;

            WsSafeHandle = new NoopSafeHandle(GetProcessWindowStation());
            WindowStationSecurity = new GenericSecurity(false, ResourceType.WindowObject, WsSafeHandle, AccessControlSections.Access);

            DSafeHandle = new NoopSafeHandle(GetThreadDesktop(GetCurrentThreadId()));
            DesktopSecurity = new GenericSecurity(false, ResourceType.WindowObject, DSafeHandle, AccessControlSections.Access);

            OldWindowStationMask = ReadAccessMask(WindowStationSecurity, WsSafeHandle, windowStationMask);
            OldDesktopMask = ReadAccessMask(DesktopSecurity, DSafeHandle, desktopMask);
        }

        private AuthorizationRuleCollection GetAccessRules(GenericSecurity security)
        {
            return security.GetAccessRules(true, false, typeof(NTAccount));
        }

        private int? ReadAccessMask(GenericSecurity security, SafeHandle safeHandle, int accessMask)
        {
            var ruels = GetAccessRules(security);

            var username = AccountInfo.Value;
            if (!username.Contains("\\"))
                username = $"{Environment.MachineName}\\{username}";

            var userResult = ruels.Cast<GrantAccessRule>().SingleOrDefault(r => r.IdentityReference.Value.ToLower() == username.ToLower() && accessMask == r.PublicAccessMask);
            if (userResult == null)
            {
                AddGrandAccess(security, accessMask, safeHandle);
                userResult = ruels.Cast<GrantAccessRule>().SingleOrDefault(r => r.IdentityReference.Value.ToLower() == username.ToLower());
                if (userResult != null)
                    return userResult.PublicAccessMask;
            }
            else
              return userResult.PublicAccessMask;

            return null;
        }

        private void AddGrandAccess(GenericSecurity security, int accessMask, SafeHandle safeHandle)
        {
            var rule = new GrantAccessRule(AccountInfo, accessMask, AccessControlType.Allow);
            security.AddAccessRule(rule);
            security.Persist(safeHandle, AccessControlSections.Access);
        }

        private void RemoveGrantAccess(GenericSecurity security, int accessMask, SafeHandle safeHandle)
        {
            var rule = new GrantAccessRule(AccountInfo, accessMask, AccessControlType.Allow);
            security.RemoveAccessRule(rule);
            security.Persist(safeHandle, AccessControlSections.Access);
        }

        private void SetGrandAccess(GenericSecurity security, int accessMask, SafeHandle safeHandle)
        {
            var rule = new GrantAccessRule(AccountInfo, accessMask, AccessControlType.Allow);
            security.SetAccessRule(rule);
            security.Persist(safeHandle, AccessControlSections.Access);
        }

        private void RestAccessMask(int? oldAccessMask, int fullAccessMask, GenericSecurity security, SafeHandle safeHandle)
        {
            if (oldAccessMask == null)
                RemoveGrantAccess(security, fullAccessMask, safeHandle);
            else if (oldAccessMask != fullAccessMask)
            {
                SetGrandAccess(security, oldAccessMask.Value, safeHandle);
            }
        }
        #endregion

        #region private classes
        private class GenericSecurity : NativeObjectSecurity
        {
            public GenericSecurity(
                bool isContainer, ResourceType resType, SafeHandle objectHandle,
                AccessControlSections sectionsRequested)
                : base(isContainer, resType, objectHandle, sectionsRequested) { }

            new public void Persist(SafeHandle handle, AccessControlSections includeSections)
            {
                base.Persist(handle, includeSections);
            }

            new public void AddAccessRule(AccessRule rule)
            {
                base.AddAccessRule(rule);
            }

            new public bool RemoveAccessRule(AccessRule rule)
            {
                return base.RemoveAccessRule(rule);
            }

            new public void SetAccessRule(AccessRule rule)
            {
                base.SetAccessRule(rule);
            }

            new public AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, Type targetType)
            {
                return base.GetAccessRules(includeExplicit, includeInherited, targetType);
            }

            public override Type AccessRightType
            {
                get { throw new NotImplementedException(); }
            }

            public override AccessRule AccessRuleFactory(
                System.Security.Principal.IdentityReference identityReference,
                int accessMask, bool isInherited, InheritanceFlags inheritanceFlags,
                PropagationFlags propagationFlags, AccessControlType type)
            {
                return new GrantAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
            }

            public override Type AccessRuleType
            {
                get { return typeof(AccessRule); }
            }

            public override AuditRule AuditRuleFactory(
                System.Security.Principal.IdentityReference identityReference, int accessMask,
                bool isInherited, InheritanceFlags inheritanceFlags,
                PropagationFlags propagationFlags, AuditFlags flags)
            {
                throw new NotImplementedException();
            }

            public override Type AuditRuleType
            {
                get { return typeof(AuditRule); }
            }
        }

        private class GrantAccessRule : AccessRule
        {
            public GrantAccessRule(IdentityReference identity, int accessMask, bool isInherited,
                                     InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags,
                                     AccessControlType type) :
                                     base(identity, accessMask, isInherited,
                                          inheritanceFlags, propagationFlags, type) { }

            public GrantAccessRule(IdentityReference identity, int accessMask, AccessControlType type) :
                base(identity, accessMask, false, InheritanceFlags.None,
                     PropagationFlags.None, type) { }

            public int PublicAccessMask
            {
                get { return base.AccessMask; }
            }
        }

        // Handles returned by GetProcessWindowStation and GetThreadDesktop should not be closed
        private class NoopSafeHandle : SafeHandle
        {
            public NoopSafeHandle(IntPtr handle) :
                base(handle, false) {}

            public override bool IsInvalid
            {
                get { return false; }
            }

            protected override bool ReleaseHandle()
            {
                return true;
            }
        }
        #endregion
    }
}

Using Sample

using (var windowsAccess = new WindowsGrandAccess(accountInfo, WindowsGrandAccess.WindowStationAllAccess, WindowsGrandAccess.DesktopRightsAllAccess))
{
   ...
}

Thank you.

Score: 2

This is symptomatic of :
- insufficient 4 rights;
- failure load of a library;

Use 3 Filemon to detect some access denied or
WinDbg 2 to run the application in a debugger and 1 view any issue.

Score: 2

I have reimplemented Martin Prikryl's answer 9 in Python, which I hope someone finds useful.

I 8 ran into this problem running a subprocess 7 in a Python script. I was using the pythonnet package 6 to run System.Diagnostics.Process as different user. My issue was 5 that the subprocess was not running and 4 I received no stdout or stderr.

# Import .NET objects using pythonnet
from System.Diagnostics import Process

# Use .NET API to run a subprocess using the given executable
# as the target user, in the provided working directory.
process = Process()
process.StartInfo.UseShellExecute = False
process.StartInfo.CreateNoWindow = True
process.StartInfo.LoadUserProfile = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.StartInfo.WorkingDirectory = working_dir
process.StartInfo.Domain = "mydomain"
process.StartInfo.UserName = username.lower().replace("mydomain\\", "")
process.StartInfo.PasswordInClearText = password
process.StartInfo.FileName = executable
process.StartInfo.Arguments = " ".join(args)

# Run the subprocess.
process.Start()

# Read subprocess console output
stdout = process.StandardOutput.ReadToEnd()
stderr = process.StandardError.ReadToEnd()
log.info(f"\n{executable} subprocess stdout:\n\n{stdout}")
log.info(f"{executable} subprocess stderr:\n\n{stderr}")
log.info(f"Done running {executable} as {username}.")

I used Martin 3 Prikryl's answer, but I reimplemented it 2 in Python using the pyWin32 library, which 1 solved my issue.:

import win32api, win32process, win32service, win32security

WINDOW_STATION_ALL_ACCESS = 983935
DESKTOP_RIGHTS_ALL_ACCESS = 983551
SE_WINDOW_OBJECT = 7
DACL_SECURITY_INFORMATION = 4


def set_access(user, handle, access):
    info = win32security.GetSecurityInfo(
        handle, SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION
    )
    dacl = info.GetSecurityDescriptorDacl()
    dacl.AddAccessAllowedAce(win32security.ACL_REVISION, access, user)
    win32security.SetSecurityInfo(
        handle, SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION, None, None, dacl, None
    )


username = "mattsegal"
user, domain, user_type = win32security.LookupAccountName("", username)
thread_id = win32api.GetCurrentThreadId()
station_handle = win32process.GetProcessWindowStation()
desktop_handle = win32service.GetThreadDesktop(thread_id)
set_access(user, station_handle, WINDOW_STATION_ALL_ACCESS)
set_access(user, desktop_handle, DESKTOP_RIGHTS_ALL_ACCESS)
Score: 0

How are you setting the domain, user, and 6 password? Are you setting the domain properly 5 as well as the password (it must use a SecureString).

Also, are 4 you setting the WorkingDirectory property? When 3 using a UserName and Password, the documentation 2 states that you must set the WorkingDirectory 1 property.

Score: 0

It may be that any process kicked off by 16 a service must also have the "Log on as 15 a Service" privelege.

If the user id that 14 you are using to start the second process 13 does not have administrative rights to the 12 box, this could be the case.

An easy test 11 would be to change the local security policy 10 to give the userid "Log on as a service" and 9 try it again.

Edit: After the additional 8 info..

Grazing over Google on this one, it 7 appears that 0xc0000142 relates to not being 6 able to initialize a needed DLL. Is there 5 something that the service has open that 4 the spawned process needs? In any case, it 3 looks like it has to do with the process 2 that's kicked off, and not how you are doing 1 it.

Score: 0

I had this problem today, and I spent quite 6 some time trying to figure it out. What 5 I ended up doing was to create the service 4 as interactive (using the Allow service 3 to interact with desktop checkbox in services.msc). As 2 soon as I did that the 0xc0000142 errors 1 went away.

More Related questions