Create process from windows service

This article reviews several scenarios of process creating from Windows service like: creating process win GUI from non-interactive service, creating process under another user account and in the different session. The article doesn’t contain code examples however it explains how to achieve the result with a free command line tool DevxExec. This text requires basic level of familiarity of Windows API.

There are could be different situations when you need to create an additional process from your main process. One of those situations is when you need to isolate some code of your service because that code could be a reason of resource leak or can damage your common process somehow. Another case is when your application needs to perform action that requires changing primary process token. Finally you just may need to run a 3rd party application.

From first glance creating a new process is a very simple operation. That is actually true. There are 3 different functions CreateProcess, CreateProcessAsUser and CreateProcessWithLogon in Windows API that you can use to create a new process. However there are situations when they don’t work in the way you could expect.

How to run a process from the Windows service

To allow several users work with the same computer at the same time Windows isolates processes of each user with special object called session. During system startup it creates session with ID=0. OS uses this session to isolate windows services processes from users’ processes. Also Windows creates another session (ID=1) during startup and run first instance of winlogon.exe under that session. Therefore first logged in (via console) user will work under session with ID=1. When another user wants to login to computer system creates a new session for him.

Window always creates a new session before the user logs in. Another words it happens when a new remote desktop connection is established or when user connected via console uses “switch user” function. Once the session is created, Windows runs a new instance of winlogon.exe. So the login screen, where user types his credentials, always relates to its own session.

Every session has own windows station. Windows station is another isolation object that has come to us from older version of system. Every window station contains a dedicated clipboard and a number of desktops.

Here is the typical hierarchy of sessions, window stations and desktops in Windows Vista and Seven (Windows 7).

The typical hierarchy of sessions, Windows stations and desktops in Windows Vista and Seven

In older systems like XP or 2003, it is different. The user logged in via console and the services are running in the same session and interactive services even use the same windows station and the same desktop.

The typical hierarchy of sessions, Windows stations and desktops in older versions

When you are running a process from windows service under user account, that process may not have (usually it doesn’t) access to the window station and to the desktop related to session 0. Of course, if your process doesn’t create any window then you are just lucky. However it’s actually not easy to write an application that doesn’t create any window at all. Typical Windows application infrastructure is based on a window even if this window is newer shown. The console application written on the most of languages (like Visual C++ or C#) creates a window too. Therefore in 99% of cases our application needs the access to the window station and to the desktop.

Information

When you run a console application and the user under which the process is running doesn’t have an access to the window station on some versions of OS you may see the error message like this:

To solve this problem you can add permissions to the window station and the desktop. Usually services run under the separate window station “Service-0x0-3e7$”. However if the option “Allow interact with Desktop” is on for the service then it runs under “WinSta0”. The difference between those windows stations is that “Service-0x0-3e7$” can’t be ever interactive so user will be not able to see the GUI of applications are running there. In case of “WinSta0” user can see the GUI but remember that in Windows Vista/Seven/2008 interactive services and logged in user have different window stations with the same name but in different sessions.

In Windows Vista/Seven/2008, ones a window is created into the Session0Winsta0Default, operation system will show a dialog like this. This dialog allows switching active user desktop to Session0Winsta0Default.

It’s actually not really important if you service runs in interactive mode or not. You always can specify window station and a desktop while creating a new process. There is a special parameter in StartupInfo structure for this.

You also can use the Developex free tool DevxExec to run a process from the windows service under another user.

DevxExec.exe /user: Administrator /password:qwerty “cmd.exe”

This command automatically grand to user “Administrator” permissions on the appropriate window station and the desktop and run a command shell.

How to run an application for a user from the Windows service

Let’s see the following scenario. You have a Windows service running. User Marcus has logged to the computer. And you want yours service to start the application that will be shown to Marcus on his current desktop. In other words, you need to run a new process in another session.

It sounds like an easy task. Yes, you can change a window station and a desktop, but unfortunately, there is no option to specify a session ID to CreateProcess functions. However Windows security token is always related to one session and fortunately we can change the session for the security token. Therefore if we create a new token for our user (for example using LogonUser), then change a session for this token using SetTokenInformation function and finally, call CreateProcessAsUser, the new process will be created in the appropriate session.

Again you can use DevxExec. It has a special parameter /sessionid to specify the session you what to run a new process in. For example this command could start a command shell for a logged in user under Administrator.

DevxExec.exe /user: Marcus /password:qwerty /sessionid:1 “cmd.exe”

How to run an application for a user from the Windows service (part 2)

Here is another scenario. User Marcus has logged to the computer. And you want your service to start an application as Annette that Marcus can work with on his current desktop. The solution above will work in that scenario too, but only if Annette is a member of the local “Administrators” group. Otherwise she will not have access to the Marcus’s desktop and windows station.

So our service (that runs in session = 0) need to give permission to Annette to Marcus’s desktop (session ≠ 0). The problem is how to get a handle of desktop that lives in another session. If you find out how to do it please let me know. Unfortunately I haven’t found how to do it but here is a workaround solution:

  1. Get a primary process (OpenProcessToken).
  2. Create a primary copy of this token (DuplicateTokenEx)
  3. Modify session id of the replica (SetTokenInformation).
  4. Create a new temporary process using that taken with CreateProcessAsUser.
  5. This process will be run into the Marcus’s session therefore it could access his window station and his desktop and give permission to Annette.

DevxExec works approximately that way so you can create a process for either user in either session.

To be continued…

Mike Makarov
Developex CTO

Skip to content



Navigation Menu

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Repository files navigation

CreateProcessAsUser

Create process at active user from Windows Service

How it works

Module read active windows desktop, change service token to active user and create process.

Example usage

DWORD pId = _CreateProcessAsUser("C:\\Windows\\system32\\cmd.exe", "/c route");

Launching a process that the currently logged on user can see on their desktop session (and interact with) from a Windows service is a popular topic – and there are a wide variety of answers out there when someone asks how to do this, some people say it is not even possible on Windows Vista or Windows 7. Turns out it is actually very easy…

Firstly, I do not really recommend this method because ideally you should have a process running in the user’s session already that communicates with your service via Named Pipes, TCP/IP, or whatever – this process can receive a command from your service and launch/do whatever you want and it will already be running in the user’s session and security context. The only reason for posting this method is because in some scenarios that ideal method is not always possible or not warranted. I think of this as a quick and dirty way of doing it if you can’t do it a more ‘proper’ way. I’m using it as part of an installation package for a program that we deploy via SCCM (which therefore gets run from the SCCM Agent service) to run a one off job that needs to be executed as the currently logged on user to avoid them needing to log out and back on before the newly deployed application will work correctly (and no its not just HKCU registry edits or anything like that which could be done in an easier way).

I’ve seen plenty of other different ways of doing this, some unnecessarily complex, but this method I am going to demonstrate seems to be by far the most simple and elegant. Oh and you don’t need to mark your service as an Interactive service and the user will not get switched to the ‘services’ desktop when they try to interact with the newly launched process.

Here is the most basic example I could come up with (needs error handling etc):

Dim UserTokenHandle As IntPtr = IntPtr.Zero
WindowsApi.WTSQueryUserToken(WindowsApi.WTSGetActiveConsoleSessionId, UserTokenHandle)

Dim ProcInfo As New WindowsApi.PROCESS_INFORMATION
Dim StartInfo As New WindowsApi.STARTUPINFOW
StartInfo.cb = CUInt(Runtime.InteropServices.Marshal.SizeOf(StartInfo))

WindowsApi.CreateProcessAsUser(UserTokenHandle, «C:\Windows\System32\cmd.exe», IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, False, 0, IntPtr.Zero, Nothing, StartInfo, ProcInfo)
If Not UserTokenHandle = IntPtr.Zero Then
    WindowsApi.CloseHandle(UserTokenHandle)
End If

Obviously this example launches command prompt but you can replace C:\Windows\System32\cmd.exe with whatever application you want to launch. As soon as CreateProcessAsUser is called, the process will be started and will appear on the user’s screen and act just like any other program. Well with one exception, with that basic example the user’s environmental variables will not be set – so for example if from that newly launched command prompt process you type “Echo %USERNAME%” then it will show that the %USERNAME% variable is currently set to the local system account. I’m sure you could get the environmental variables to get setup correctly by calling CreateEnvironmentBlock and passing the result in to the lpEnvironment argument of CreateProcessAsUser (instead of passing in Nothing as I do in this example).

Also note that this method assumes your service is running as Local System – other accounts wont have the required permissions for this to work.

For anyone that can’t be bothered (or doesn’t know how) to define the Windows APIs used in this example, here you go (I have also included each of these in my Windows API library)

Imports System.Runtime.InteropServices

Public Class WindowsApi

    <DllImport(«kernel32.dll», EntryPoint:=«WTSGetActiveConsoleSessionId», SetLastError:=True)> _
    Public Shared Function WTSGetActiveConsoleSessionId() As UInteger
    End Function

    <DllImport(«Wtsapi32.dll», EntryPoint:=«WTSQueryUserToken», SetLastError:=True)> _
    Public Shared Function WTSQueryUserToken(ByVal SessionId As UInteger, ByRef phToken As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport(«kernel32.dll», EntryPoint:=«CloseHandle», SetLastError:=True)> _
    Public Shared Function CloseHandle(<InAttribute()> ByVal hObject As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport(«advapi32.dll», EntryPoint:=«CreateProcessAsUserW», SetLastError:=True)> _
    Public Shared Function CreateProcessAsUser(<InAttribute()> ByVal hToken As IntPtr, _
                                                    <InAttribute(), MarshalAs(UnmanagedType.LPWStr)> ByVal lpApplicationName As String, _
                                                    ByVal lpCommandLine As System.IntPtr, _
                                                    <InAttribute()> ByVal lpProcessAttributes As IntPtr, _
                                                    <InAttribute()> ByVal lpThreadAttributes As IntPtr, _
                                                    <MarshalAs(UnmanagedType.Bool)> ByVal bInheritHandles As Boolean, _
                                                    ByVal dwCreationFlags As UInteger, _
                                                    <InAttribute()> ByVal lpEnvironment As IntPtr, _
                                                    <InAttribute(), MarshalAsAttribute(UnmanagedType.LPWStr)> ByVal lpCurrentDirectory As String, _
                                                    <InAttribute()> ByRef lpStartupInfo As STARTUPINFOW, _
                                                    <OutAttribute()> ByRef lpProcessInformation As PROCESS_INFORMATION) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <StructLayout(LayoutKind.Sequential)> _
    Public Structure SECURITY_ATTRIBUTES
        Public nLength As UInteger
        Public lpSecurityDescriptor As IntPtr
        <MarshalAs(UnmanagedType.Bool)> _
        Public bInheritHandle As Boolean
    End Structure

    <StructLayout(LayoutKind.Sequential)> _
    Public Structure STARTUPINFOW
        Public cb As UInteger
        <MarshalAs(UnmanagedType.LPWStr)> _
        Public lpReserved As String
        <MarshalAs(UnmanagedType.LPWStr)> _
        Public lpDesktop As String
        <MarshalAs(UnmanagedType.LPWStr)> _
        Public lpTitle As String
        Public dwX As UInteger
        Public dwY As UInteger
        Public dwXSize As UInteger
        Public dwYSize As UInteger
        Public dwXCountChars As UInteger
        Public dwYCountChars As UInteger
        Public dwFillAttribute As UInteger
        Public dwFlags As UInteger
        Public wShowWindow As UShort
        Public cbReserved2 As UShort
        Public lpReserved2 As IntPtr
        Public hStdInput As IntPtr
        Public hStdOutput As IntPtr
        Public hStdError As IntPtr
    End Structure

    <StructLayout(LayoutKind.Sequential)> _
    Public Structure PROCESS_INFORMATION
        Public hProcess As IntPtr
        Public hThread As IntPtr
        Public dwProcessId As UInteger
        Public dwThreadId As UInteger
    End Structure

End Class

Hope it helps someone out

Chris

If you have some knowledge about Windows services and their functionalities then go ahead. Otherwise you may not understand some of the points mentioned here.

Are you suffering from starting a process from your windows service ? I have a cunning solution for that. Normally we cannot start any process either on our local machine or from a remote machine through a windows service.

We can start the process by enabling the Desktop Interactive of the service, but the UAC system of Vista and Windows 7 is a problem, that every time we start the process from a service it asks whether to allow the desktop interactivity. We can’t ask our clients to stop the UAC system. So what is the solution ?

Now I think you have some idea why can’t we start a process from service. But you might have a question in your mind why we need a process for a service ? There can be several answers

  • We need to perform a CPU intensive operation
  • COM interoperability is clashing with some threading components of the service
  • Some actions can be performed more efficiently by a separate process rather than a service

I figured out this solution as I suffered from the bolded point. Here the method I have used.

Create an ASPX webpage (it should be hosted in a later version of IIS 4.0)

In the Page_Load method start the process.

Then Create the Windows Service to access the the web page. (Access it through normal WebRequest and WebResponse). Cool !

The real cool thing is you can almost start all the processes by using this method from a windows service. Even processes with arguments and Verbs.’

Here’s the code for the webpage

protected void Page_Load(object sender, EventArgs e)
{

Process p = new Process();

p.StartInfo.FileName = "path to your process (your .exe file)"

p.StartInfo.UseShellExecute = false;

p.StartInfo.CreateNoWindow = true;

p.Start();

p.WaitForExit();

p.Dispose();

}

 

In the service within the OnStart() put the following code

try

{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("ASPX page path");

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

}

catch (Exception ex)

{

}

Guest




  • #1

I had originally written a program as a c# console application. The program
used a reference that I wrote in c++. Later I was told to re-write the
application as a windows service. When the service would start up, as soon as
it accessed the reference (by instantiating a class within the reference),
the service would crash. In the event viewer I saw that it throw a
System.IO.FileNotFoundException saying that the c++ reference was missing
(even though it was in the same directory as the .exe). I decided to write a
windows service that would simply launch the console application. In the
“OnStart†method I called the win32 API CreateProcess (which I P/Invoked).
When the service started it launched the console application successfully,
the console application then as soon as the reference was «used» by the
console application the console application crashes saying
File.IO.FileNotFoundException. As sanity check first I ran the console app by
itself and it ran just fine. Then I created a second c# console application
and in the main I used the exact same code from the “OnStart†of the afore
mentioned service (CreateProcess api) and it launched my original program
just fine.

Why is there a difference if I use CreateProcess from a c# service vs. c#
console application? Also isn’t a service simply a console application that
interacts with service control manager?



  • #2

Noam said:

Why is there a difference if I use CreateProcess from a c# service vs. c#
console application? Also isn’t a service simply a console application that
interacts with service control manager?

When you ran the console application manually, you were logged in to
Windows. When your service executed, it logged in differently, using
the LocalSystem account which is restricted.

Without knowing what the process you are trying to start does, I can’t
say exactly why you got the FileNotFound exception, but it may be that
the LocalSystem account does not have the necessary permissions to
access some resource needed by the process.

What happens when you set the service to log in as yourself, can it
then run correctly?

Guest




  • #3

Thank you so much for getting back to me so quickly I really appreciate it.
In the Log On tab under the service I had it set to my domain\username and
password (so the service is not set under Local System account). Also my
company uses active directory and I am an administrator on my computer. Still
no dice

chanmm




  • #4

Can you specifiy the full path rather than depend on the default exe folder?

chanmm

Guest




  • #5

I’m not sure i understand your answer, when you say specify the full path are
you referring to the path to the CreateProcess api (that i am passing) or for
the reference that i am recieving the System.IO.FileNotFoungException? If it
is for the reference my understanding is that all references (if not in the
GAC) must be in the same directory as the .exe… Also I have other refernces
in that directory that the program is picking up just fine.

Here is some informtaion on the c++ referance that is throwing the error.
Configuration type: Dynamic Libray
MFC: Use MFC in a Shared DLL
Runtime Library: /MDd

every other value is the default

Ben Voigt




  • #6

Noam said:

I’m not sure i understand your answer, when you say specify the full path
are
you referring to the path to the CreateProcess api (that i am passing) or
for
the reference that i am recieving the System.IO.FileNotFoungException? If
it
is for the reference my understanding is that all references (if not in
the
GAC) must be in the same directory as the .exe… Also I have other
refernces
in that directory that the program is picking up just fine.

Can you somehow run your process through depends.exe, possibly by changing
your CreateProcess call? Depends.exe will watch the process and tell you
more about why the DLL failed to load. Although you will have trouble
getting the window to be visible so you can interact and inspect it….
services running as user accounts run in a separate desktop by default.

Here is some informtaion on the c++ referance that is throwing the error.
Configuration type: Dynamic Libray
MFC: Use MFC in a Shared DLL
Runtime Library: /MDd

Does your DLL have a DllMain? Doing anything significant there?

Willy Denoyette [MVP]




  • #7

| I’m not sure i understand your answer, when you say specify the full path
are
| you referring to the path to the CreateProcess api (that i am passing) or
for
| the reference that i am recieving the System.IO.FileNotFoungException? If
it
| is for the reference my understanding is that all references (if not in
the
| GAC) must be in the same directory as the .exe… Also I have other
refernces
| in that directory that the program is picking up just fine.
|
| Here is some informtaion on the c++ referance that is throwing the error.
| Configuration type: Dynamic Libray
| MFC: Use MFC in a Shared DLL
| Runtime Library: /MDd
|

As far as I see you have a MFC DLL as «reference», right.
Questions are:
— what version of the C compiler was used to build this DLL? If it’s VC 8
(vs2005), the DLL must contain an embedded manifest if the CRT library is
not statically linked.
— this DLL is in the same path as the exe?
— this DLL is built using the /clr option, right?

Willy.

Guest




  • #8

Again thank you so much for the reply I really apreciate everyones help. I am
using Visual Studios 2003 Verssion 7.1.3088. The dll is in the same path as
the exe and the /clr option was used.

Guest




  • #9

Thank you so much for your reply. My dll is not a regular dll it is a visual
studios assembly. As such there is no dll main. I am trying depends.exe now
but I haven’t seen anything useful.

John Vottero




  • #10

[snip]

Why is there a difference if I use CreateProcess from a c# service vs. c#
console application? Also isn’t a service simply a console application
that
interacts with service control manager?

One key difference between running a console app and a windows service is
the default directory. Try changing your directory to C:\Windows\System32
then run your console app from there (by entering the full path to the
console exe). Does that work? I think it will fail the same way that the
service is failing. If it does, make your service change it’s directory via
System.Environment.CurrentDirectory.

Guest




  • #11

How about running the service as the local system account and checking
«interact with desktop»?

John Vottero said:

[snip]

Why is there a difference if I use CreateProcess from a c# service vs. c#
console application? Also isn’t a service simply a console application
that
interacts with service control manager?

One key difference between running a console app and a windows service is
the default directory. Try changing your directory to C:\Windows\System32
then run your console app from there (by entering the full path to the
console exe). Does that work? I think it will fail the same way that the
service is failing. If it does, make your service change it’s directory via
System.Environment.CurrentDirectory.

Willy Denoyette [MVP]




  • #12

|
| How about running the service as the local system account and checking
| «interact with desktop»?
|

No, this doesn’t have anything to do with the OP’s issue, and, this is
something you should only consider when «debugging» a service, but not in
production.

Willy.

| «John Vottero» wrote:
|
| >
| > | >
| > [snip]
| >
| > > Why is there a difference if I use CreateProcess from a c# service vs.
c#
| > > console application? Also isn’t a service simply a console application
| > > that
| > > interacts with service control manager?
| >
| > One key difference between running a console app and a windows service
is
| > the default directory. Try changing your directory to
C:\Windows\System32
| > then run your console app from there (by entering the full path to the
| > console exe). Does that work? I think it will fail the same way that
the
| > service is failing. If it does, make your service change it’s directory
via
| > System.Environment.CurrentDirectory.
| >
| >
| >
| >

Guest




  • #13

Thank you so much kind sir, I think it must be some sort of path issues…
but as soon as i ran the service with the local system and cheked interact
with desktop everything started running perfectly

Mike said:

How about running the service as the local system account and checking
«interact with desktop»?

John Vottero said:

[snip]

Why is there a difference if I use CreateProcess from a c# service vs. c#
console application? Also isn’t a service simply a console application
that
interacts with service control manager?

One key difference between running a console app and a windows service is
the default directory. Try changing your directory to C:\Windows\System32
then run your console app from there (by entering the full path to the
console exe). Does that work? I think it will fail the same way that the
service is failing. If it does, make your service change it’s directory via
System.Environment.CurrentDirectory.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Команда открытия сетевых настроек windows
  • Как на жестком диске создать том на жестком диске windows
  • Ошибка d3d windows 7
  • Radeon 9600xt windows 98
  • Cmd codes for windows