murrayju / CreateProcessAsUser

Creates a process in a different Windows session
MIT License
363 stars 114 forks source link

Integration with TopShelf #24

Open davisford opened 6 years ago

davisford commented 6 years ago

Hi,

I was trying to write a simple wrapper like you have here with DemoService but using TopShelf. Unfortunately, I cannot get it working. What I have is very simple:

class Program
    {
        static void Main(string[] args)
        {
            var rc = HostFactory.Run(x =>
            {
                Console.WriteLine("in run...");
                x.Service<ServiceWrapper>(m =>
                {
                    m.ConstructUsing(name => new ServiceWrapper());
                    m.WhenStarted((wrapper) => { Console.WriteLine("starting service..."); wrapper.Start(); });
                    m.WhenStopped((wrapper) => { wrapper.Stop(); });
                });

                x.EnableServiceRecovery(r =>
                {
                    r.RestartService(0);
                    r.RestartService(1);
                    r.RestartService(1);
                    r.SetResetPeriod(1);
                });

                x.RunAsLocalService();
                x.SetDescription("DemoServiceTopShelf");
                x.SetDisplayName("DemoServiceTopShelf");
                x.SetServiceName("DemoServiceTopShelf");
                x.OnException(ex =>
                {
                    Console.WriteLine("exception {0}", ex.Message);
                });

            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;
        }
    }

    class ServiceWrapper
    {
        public ServiceWrapper() {  }
        public void Start()
        {
            Console.WriteLine("Trying to launch calc.exe");
            ProcessExtensions.StartProcessAsCurrentUser("calc.exe");
        }
        public void Stop() { }
    }

So, I'm running VS as Administrator, and if I run this, the WTSQueryUserToken( ) call always returns zero.

So, I figured maybe I have to install the service first. TopShelf builds command line params for install/uninstall/start, etc. of the service. It installs fine:

DMSMonitorSvc.exe install
in run...
Configuration Result:
[Success] Name DemoServiceTopShelf
[Success] ServiceName DemoServiceTopShelf
Topshelf v4.0.0.0, .NET Framework v4.0.30319.42000

Running a transacted installation.

Beginning the Install phase of the installation.
Installing DemoServiceTopShelf service
Installing service DemoServiceTopShelf...
Service DemoServiceTopShelf has been successfully installed.

The Install phase completed successfully, and the Commit phase is beginning.

The Commit phase completed successfully.

The transacted install has completed.

If I try to start it in the Services tool, it fails with Windows could not start the DemoServiceTopShelf service on Local Computer. Error 5: Access is denied.

In event viewer, I see these events got logged related to it:

Special privileges assigned to new logon.

Subject:
    Security ID:        SYSTEM
    Account Name:       SYSTEM
    Account Domain:     NT AUTHORITY
    Logon ID:       0x3E7

Privileges:     SeAssignPrimaryTokenPrivilege
            SeTcbPrivilege
            SeSecurityPrivilege
            SeTakeOwnershipPrivilege
            SeLoadDriverPrivilege
            SeBackupPrivilege
            SeRestorePrivilege
            SeDebugPrivilege
            SeAuditPrivilege
            SeSystemEnvironmentPrivilege
            SeImpersonatePrivilege
            SeDelegateSessionUserImpersonatePrivilege

And this event log:

An account was successfully logged on.

Subject:
    Security ID:        SYSTEM
    Account Name:       DESKTOP-F26HMBM$
    Account Domain:     WORKGROUP
    Logon ID:       0x3E7

Logon Information:
    Logon Type:     5
    Restricted Admin Mode:  -
    Virtual Account:        No
    Elevated Token:     Yes

Impersonation Level:        Impersonation

New Logon:
    Security ID:        SYSTEM
    Account Name:       SYSTEM
    Account Domain:     NT AUTHORITY
    Logon ID:       0x3E7
    Linked Logon ID:        0x0
    Network Account Name:   -
    Network Account Domain: -
    Logon GUID:     {00000000-0000-0000-0000-000000000000}

Process Information:
    Process ID:     0x2b0
    Process Name:       C:\Windows\System32\services.exe

Network Information:
    Workstation Name:   -
    Source Network Address: -
    Source Port:        -

Detailed Authentication Information:
    Logon Process:      Advapi  
    Authentication Package: Negotiate
    Transited Services: -
    Package Name (NTLM only):   -
    Key Length:     0

This event is generated when a logon session is created. It is generated on the computer that was accessed.

The subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.

The logon type field indicates the kind of logon that occurred. The most common types are 2 (interactive) and 3 (network).

The New Logon fields indicate the account for whom the new logon was created, i.e. the account that was logged on.

The network fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.

The impersonation level field indicates the extent to which a process in the logon session can impersonate.

The authentication information fields provide detailed information about this specific logon request.
    - Logon GUID is a unique identifier that can be used to correlate this event with a KDC event.
    - Transited services indicate which intermediate services have participated in this logon request.
    - Package name indicates which sub-protocol was used among the NTLM protocols.
    - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.

I have searched through past issues related to the Access Denied, but I don't see a concrete solution here. It is worth noting if you clone this repo and run the .bat scripts, it does work for me on the same machine.

Any insight into what might be going wrong?

AndrewSav commented 6 years ago

Here are some thoughts for you. I've never used TopShelf before, so please bear with me.

I believe that "Access Denied" that you are seeing, is an artifact of TopShelf wrongly passing it's internal error code to Windows Service Control Manager. I opened an issue with them.

The actual issue that is happening to you is an exception thrown inside StartProcessAsCurrentUser, and it's normally written in the Application Event Log, but you are not giving it in your error description.

You can look it up there or you can configure topshelf to write exceptions to a log file, for example with NLog. Insert this into your app.config straight after <configuration>

  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <nlog>
    <targets>
      <target name="file" type="File"
              layout="${longdate} ${logger} ${message} ${exception:format=ToString}" 
              fileName="logfile.txt" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
  </nlog>

Add x.UseNLog(); inside your HostFactory.Run, as described here.

Both in event log or in the logfile.txt I'm seeing this:

System.Exception: StartProcessAsCurrentUser: CreateProcessAsUser failed.  Error Code -2
   at murrayju.ProcessExtensions.ProcessExtensions.StartProcessAsCurrentUser(String appPath, String cmdLine, String workDir, Boolean visible) in D:\Users\andrewsav\Documents\GitHub\CreateProcessAsUser\ProcessExtensions\ProcessExtensions.cs:line 249
   at TopShelfDemo.ServiceWrapper.Start() in D:\Users\andrewsav\Documents\GitHub\CreateProcessAsUser\TopShelfDemo\Program.cs:line 58
   at TopShelfDemo.Program.<>c.<Main>b__0_5(ServiceWrapper wrapper) in D:\Users\andrewsav\Documents\GitHub\CreateProcessAsUser\TopShelfDemo\Program.cs:line 21
   at Topshelf.ServiceConfiguratorExtensions.<>c__DisplayClass2_0`1.<WhenStarted>b__0(T service, HostControl control)
   at Topshelf.Builders.DelegateServiceBuilder`1.DelegateServiceHandle.Start(HostControl hostControl)
   at Topshelf.Runtime.Windows.WindowsServiceHost.OnStart(String[] args)

So I'm getting Error 2. If you look it up here you will find out that it means "File Not Found". That is to say that CreateProcessAsUser method cannot find calc.exe. If you refer to CreateProcessAsUser documentation you will discover that it does not search path, so your calc.exe expects to be in your current folder.

Topshelf apprarently sets current folder to the executable folder, I'm not sure why, some more discussion is here.

Also make sure that you are not running into 32 vs 64 bit issue as mentioned here.

I added Directory.SetCurrentDirectory(Environment.SystemDirectory); in your example in front of ProcessExtensions.StartProcessAsCurrentUser("calc.exe"); and it worked for me.