[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

show process window

Posted on 2010-09-20
9
Medium Priority
?
455 Views
Last Modified: 2012-05-10
Hi all,

I have written a service that starts a process:

                STARTUPINFO                  si;
            PROCESS_INFORMATION pi;

            memset(&pi, 0, sizeof(pi));
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            si.dwFlags = STARTF_USESHOWWINDOW;
            si.wShowWindow = SW_NORMAL | SW_SHOW;

            CreateProcess(<ExeName>, NULL, NULL, NULL, FALSE,
                  CREATE_DEFAULT_ERROR_MODE, NULL,<WorkingFolder>, &si, &pi))

This works, but the window for <ExeName> is not shown (it's a console application)

How do I create that process so that console window will always be shown?

Thank you.
0
Comment
Question by:darrgyas
  • 5
  • 4
9 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 33717880
>>I have written a service that starts a process
>>[...]
>>This works, but the window for <ExeName> is not shown (it's a console
>>application)

The reason for this is that services run on their own desktop, which is invisible to the logged on user. If you want the window to be visible, you need to either set your service to interact with the user's desktop using 'SERVICE_INTERACTIVE_PROCESS' when calling 'CreateService()' (http://msdn.microsoft.com/en-us/library/ms682450(VS.85).aspx) - which is not recommended for systems more recent than XP - or go the hard way as outlined in http://support.microsoft.com/kb/327618 ("Security, services and the interactive desktop in Windows"). See also the sample code in http://support.microsoft.com/kb/165194 ("CreateProcessAsUser() windowstations and desktops") as well as http://www.microsoft.com/whdc/system/sysinternals/Session0Changes.mspx ("Impact of Session 0 Isolation on Services and Drivers in Windows").
In a nutshell: This is helluva a task if you do not want to risk a security breach and use deprecated methods like SERVICE_INTERACTIVE_PROCESS.

0
 

Author Comment

by:darrgyas
ID: 33717956
If I start some dialog-based applicationfrom the service, like notepad - it is visible.
Also, if checking "allow this service to interact..." in the services applet does not do anything, will doing it programmatically work?
0
 
LVL 86

Expert Comment

by:jkr
ID: 33717999
What Windows version are you on?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:darrgyas
ID: 33718008
server 2003
0
 

Author Comment

by:darrgyas
ID: 33718019
I tried CREATE_NEW_CONSOLE - no effect
0
 
LVL 86

Accepted Solution

by:
jkr earned 2000 total points
ID: 33718045
Server 2003 should support 'SERVICE_INTERACTIVE_PROCESS' as well as setting that in the control panel. BTW, you could also use the following technique to launch an application in the security context of the logged on user:
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <malloc.h>
#include <lmcons.h>

#pragma comment(lib,"kernel32.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"advapi32.lib")

void
__cdecl
DbgReport ( char* __pszFormat, ...) {

    static char s_acBuf [ 2048];

    va_list _args;

    va_start ( _args, __pszFormat);

    vsprintf ( s_acBuf, __pszFormat, _args);

    OutputDebugStringA ( s_acBuf);

    va_end ( _args);
}

DWORD ExecuteCmd   (   LPSTR   pszCmd, BOOL bShow, HANDLE hToken)
{
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    BOOL                bRes;

    DWORD               dwCode  =   0;

    MSG                msg;

    ZeroMemory  (   &si,    sizeof  (   STARTUPINFO));

    si.cb           =   sizeof  (   STARTUPINFO);
    si.dwFlags      =   STARTF_USESHOWWINDOW;
    si.wShowWindow  =   bShow ? SW_SHOWNORMAL : SW_HIDE;

    bRes    =   CreateProcessAsUser   (  hToken,
                                   NULL,
                                   pszCmd,
                                   NULL,
                                   NULL,
                                   TRUE,
                                   NORMAL_PRIORITY_CLASS,
                                   NULL,
                                   NULL,
                                   &si,
                                   &pi
                               );

    
    CloseHandle (   pi.hProcess);
    CloseHandle (   pi.hThread);

    return  (   0);
}


DWORD GetExplorerProcessID()
{
      HANDLE hSnapshot;
      PROCESSENTRY32 pe32;
      ZeroMemory(&pe32,sizeof(pe32));
      DWORD temp;

    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);
      
      pe32.dwSize = sizeof(PROCESSENTRY32);

      if(Process32First(hSnapshot,&pe32))
      {
            do
            {
                  if(!strcmp(pe32.szExeFile,"explorer.exe"))
                  {
                        temp = pe32.th32ProcessID;
                        break;
                  }

            }while(Process32Next(hSnapshot,&pe32));
      }

    DbgReport("Explorer PID: %d\n", temp);

return temp;
}

BOOL EnableDebugPriv  (   BOOL    bEnable)
{
   HANDLE           hToken;
   TOKEN_PRIVILEGES tp;

   if   (   !OpenProcessToken   (   GetCurrentProcess   (),
                                    TOKEN_ADJUST_PRIVILEGES,
                                    &hToken
                                )
        )   return  (   FALSE);


   tp.PrivilegeCount    =   1;

   LookupPrivilegeValue (   NULL,
                            SE_DEBUG_NAME,
                            &tp.Privileges  [   0].Luid
                        );

   tp.Privileges    [   0].Attributes   =       bEnable
                                            ?   SE_PRIVILEGE_ENABLED
                                            :   0;

   AdjustTokenPrivileges    (   hToken,
                                FALSE,
                                &tp,
                                sizeof  (   tp),
                                NULL,
                                NULL
                            );

   return   (   GetLastError()  ==   ERROR_SUCCESS);
}

void GetSidUser(PSID psid,char*pName, DWORD dwNameSize) {

    char                    acReferencedDomain  [   LM20_DNLEN  +   1];
    DWORD                   dwDomainBufSize     =   sizeof  (   acReferencedDomain);
    SID_NAME_USE            eUse;

               //  lookup clear text name of the owner
                if  (   !LookupAccountSid   (   NULL,
                                                psid,
                                                pName,
                                                &dwNameSize,
                                                acReferencedDomain,
                                                &dwDomainBufSize,
                                                &eUse
                                            )
                    )
                    {
                        DWORD dwErr   =   GetLastError    ();

                        DbgReport("LookupAccountSid() failed: %d\n", dwErr);

                    } else DbgReport("SID represents %s\\%s\n", acReferencedDomain, pName);
}

void ImpersonateInteractiveUser(LPSTR pCmd, BOOL bShow)
{
   HANDLE hToken = NULL;                
   HANDLE hProcess = NULL;
   char                    acName  [   LM20_DNLEN  +   1];
   DWORD                   dwNameSize     =   sizeof  (   acName);

   DWORD processID = GetExplorerProcessID();
   if( processID)
    {
    hProcess =
         OpenProcess(  
               PROCESS_ALL_ACCESS,
         TRUE,
          processID );

    if( hProcess)
        {
        if( OpenProcessToken(
                    hProcess,
             TOKEN_ALL_ACCESS,
             &hToken))
        {
         TOKEN_USER* ptu;
         DWORD dw;
         GetTokenInformation(hToken,TokenUser,NULL,0,&dw);
         ptu = (TOKEN_USER*) _alloca(dw);

         if (!GetTokenInformation(hToken,TokenUser,ptu,dw,&dw)) DbgReport("GetTokenInformation() failed, reason: %d\n", GetLastError());
         GetSidUser(ptu->User.Sid,acName,dwNameSize);

         if (!ImpersonateLoggedOnUser( hToken)) DbgReport("ImpersonateLoggedOnUser() failed, reason: %d\n", GetLastError());

         DbgReport("Launching command: %s as \'%s\'\n", pCmd, acName);
         ExecuteCmd(pCmd,bShow,hToken);

          CloseHandle( hToken );
        } else DbgReport("OpenProcessToken() failed, reason: %d\n", GetLastError());
        CloseHandle( hProcess );
    } else DbgReport("OpenProcess() failed, reason: %d\n", GetLastError());
   } 
}


int main (int argc, char** argv) {

  if (2 > argc) return -1;

  EnableDebugPriv(TRUE);

  BOOL bShow = TRUE;

  if (argc == 3) bShow = strcmp(argv[2],"/HIDE");

  if (!bShow) DbgReport("... using /HIDE\n");

  ImpersonateInteractiveUser(argv[1], bShow);

  return 0;

}

Open in new window

0
 

Author Comment

by:darrgyas
ID: 33718281
That works, thank you.
The points well deserved, but just to push my luck is it possible to show console for the service itself?
0
 
LVL 86

Expert Comment

by:jkr
ID: 33718579
I am afraid that this would require opening the window station, adjusting the privileges etc. - IOW a lot of effort. I'd rather recommend to use an application that is launech in the user's context and with which you communicate with some IPC means if you need to display any status updates or something similar.
0
 

Author Comment

by:darrgyas
ID: 33718607
Thank you, I appreciate it.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question