메뉴 닫기

[C/C++/MFC] 윈도우 서비스에서 응용 프로그램 실행하기(CreateProcessAsUser) 출처: http://duzi077.tistory.com/25 [개발하는 두더지]

#서비스에서 UI 있는 프로그램을 실행시킬 수는 있지만 SYSTEM 권한으로 실행되어 UI가 나오지 않는 문제 발생
윈도우는 User Interface, GDI, 커널 메인 객체를 제공한다.

커널은 안전하지만, UI, GDI는 그렇지 않기때문에 추가적인 보안성을 제공하기 위해 윈도우는 stations와 desktops를 사용한다.
Station은 클립보드, desktop등을 포함하는 프로세스와 관련이 있는 보안 객체이고, Desktop은 Station내에 존재하며 논리화면, 윈도우, 메뉴, 훅과 같은 User Interface를 포함하는 보안객체이다.

로그온 화면을 관리하는 winlogon desktop, 화면보호기를 담당하는 screen saver desktop, 평상시 윈도우 화면을 보여주는 interactive desktop 3가지로 나눠진다.

사용자가 로그온을 하게 되면 WinSta0\Winlogon 에서 smss.exe(세션메니져), winlogon.exe, msgina.dll 를 통해 일련의 logon 작업을 거쳐 최종적으로 Winst0\default 라는 interactive window station을 생성한다.

그러므로 사용자는 Winsta0의 station에서만이 UI 및 키입력을 받을 수 있다. ( 즉 서비스의 경우는 Service-0x0-3e7$\default)로 생성됨)

Winlogon 과 default desktop은 서로 메시지나 대화상자를 공유할수 없다. 자신의 desktop(winlogon, default)에서만 사용이 가능하다.

하지만 클립보드는 Station에서 관리하기 때문에 다른 desktop에서 사용이 가능하다.

Service의 경우 LocalSystem 계정(administrator 계정보다 상위개념)으로 실행되어 Service-0x0-3e7$\default 와 같은 station을 생성하므로 UI 및 키 입력을 받을수 없다. 그래서 서비스내에서 UI를 가진 프로그램을 실행시키기 위해서는 STARTUPINFO 구조체의 si.lpDesktop = “WinSta0\\Default”; 와 같이 설정하여 실행시켜야 한다. 서비스 프로그램중에서 mtask.exe와 같은 프로그램은 WinSta0을 사용한다.

반면 서비스 프로그램을 UI 또는 키 입력을 받기 위해서는 CreateService로 실행시 SERVICE_INTERATIVE_PROCESS 옵션을 사용하거나 서비스 등록정보에서 로그인정보에 “데스크와 상호 작용”을 설정하면 서비스도 UI 및 키입력을 받을 수 있다.

결국 Session-> WindowStation -> Desktop와 같은 구조를 이루는데 다른 Session에서는 같은 winsta0\defualt를 가졌더라도 메시지 및 UI가 공유될수 없다. 즉 Session 1에 logon한 사용자가 실행시킨 프로그램에서 표시된 대화상자는 Session 2로 logon 사용자의 화면에는 나타나지 않는다는 이야기다.

# 테스트

STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
si.lpReserved = NULL;
si.lpTitle = NULL;
si.lpDesktop = L"WinSta0\\Default";
si.dwX = si.dwY = si.dwXSize = si.dwYSize = 0L;
si.dwFlags = 0;;
si.wShowWindow = SW_SHOW;
si.lpReserved2 = NULL;
si.cbReserved2 = 0;
CreateProcess( lpwzPath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

다음과 같이 테스트를 진행해보았으나 여전히 SYSTEM 권한으로 실행..

#두번째 테스트

BOOL CModule::StartApp(LPWSTR lpwzPath)
{
    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    BOOL bResult = FALSE;
    DWORD dwSessionId,winlogonPid;
    HANDLE hUserToken,hUserTokenDup,hPToken,hProcess;
    DWORD dwCreationFlags;
// Log the client on to the local computer.
    dwSessionId = WTSGetActiveConsoleSessionId();
//////////////////////////////////////////
// Find the winlogon process
////////////////////////////////////////
    PROCESSENTRY32 procEntry;
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
    {
return 1 ;
    }
    procEntry.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnap, &procEntry))
    {
return 1 ;
    }
do {
if (wcsicmp(procEntry.szExeFile, L"winlogon.exe") == 0)
        {
// We found a winlogon process...make sure it's running in the console session
            DWORD winlogonSessId = 0;
if (ProcessIdToSessionId(procEntry.th32ProcessID, &winlogonSessId) && winlogonSessId == dwSessionId)
            {
                winlogonPid = procEntry.th32ProcessID;
break;
            }
        }
    } while (Process32Next(hSnap, &procEntry));
////////////////////////////////////////////////////////////////////////
    WTSQueryUserToken(dwSessionId,&hUserToken);
    dwCreationFlags = NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb= sizeof(STARTUPINFO);
    si.lpDesktop = L"winsta0\\default";
    ZeroMemory(&pi, sizeof(pi));
    TOKEN_PRIVILEGES tp;
    LUID luid;
    hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,winlogonPid);
if(!::OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
|TOKEN_READ|TOKEN_WRITE,&hPToken))
    {
int abcd = GetLastError();
printf("Process token open Error: %u\n",GetLastError());
    }
if (!LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid))
    {
printf("Lookup Privilege value Error: %u\n",GetLastError());
    }
    tp.PrivilegeCount =1;
    tp.Privileges[0].Luid =luid;
    tp.Privileges[0].Attributes =SE_PRIVILEGE_ENABLED;
    DuplicateTokenEx(hPToken,MAXIMUM_ALLOWED,NULL,SecurityIdentification,TokenPrimary,&hUserTokenDup);
int dup = GetLastError();
//Adjust Token privilege
    SetTokenInformation(hUserTokenDup,TokenSessionId,(void*)dwSessionId,sizeof(DWORD));
if (!AdjustTokenPrivileges(hUserTokenDup,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,NULL))
    {
int abc =GetLastError();
printf("Adjust Privilege value Error: %u\n",GetLastError());
    }
if (GetLastError()== ERROR_NOT_ALL_ASSIGNED)
    {
printf("Token does not have the provilege\n");
    }
    LPVOID pEnv =NULL;
if(CreateEnvironmentBlock(&pEnv,hUserTokenDup,TRUE))
    {
        dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT;
    }
else
        pEnv=NULL;
// Launch the process in the client's logon session.
    bResult = CreateProcessAsUser(
        hUserTokenDup,            // client's access token
        lpwzPath,              // file to execute
NULL,     // command line
NULL,              // pointer to process SECURITY_ATTRIBUTES
NULL,              // pointer to thread SECURITY_ATTRIBUTES
        FALSE,             // handles are not inheritable
        dwCreationFlags,  // creation flags
        pEnv,              // pointer to new environment block
NULL,              // name of current directory
        &si,               // pointer to STARTUPINFO structure
        &pi                // receives information about new process
        );
// End impersonation of client.
//GetLastError Shud be 0
int iResultOfCreateProcessAsUser = GetLastError();
//Perform All the Close Handles task
if (pi.hProcess != NULL){
/* 프로그램 실행되고 초기화 후 입력받을 수 있는 상태가 되면 다음코드로 진행*/
        DWORD dwWait = ::WaitForInputIdle(pi.hProcess, INFINITE);
        ::CloseHandle(pi.hProcess);
    }
    SetForegroundWindow((HWND)pi.hProcess);
    CloseHandle(hProcess);
    CloseHandle(hUserToken);
    CloseHandle(hUserTokenDup);
    CloseHandle(hPToken);
return bResult;
}

SYSTEM 앱으로 만들고 UI도 출력 가능!
하지만 UI가 최상위 윈도우가 아니라 밑에 가려져있는 문제발생..
최상위로 올리는 코드는 구현했으나 찾기 귀찮아서… 요청하는 분이 있다면 공개하겠슴다

35 Comments

  1. no g

    Hmm is anyone else having problems with the pictures on this blog loading?
    I’m trying to determine if its a problem on my end or if it’s the blog.
    Any suggestions would be greatly appreciated.

  2. http://tinyurl.com/

    certainly like your web site but you need to test the spelling
    on several of your posts. Several of them are rife with spelling issues and I in finding it
    very troublesome to inform the truth on the other hand I’ll certainly come back again.

  3. cbd oil that works 2020

    Hello there, I found your website via Google at the same time
    as looking for a similar subject, your website came up, it seems to
    be great. I have bookmarked it in my google bookmarks.

    Hello there, just become alert to your blog via Google, and found that
    it’s really informative. I’m going to watch out for brussels.

    I will appreciate for those who proceed this in future.

    Many other people might be benefited from your writing.
    Cheers!

  4. Dora Saice

    I simply want to say I am just beginner to blogs and seriously liked you’re web blog. More than likely I’m likely to bookmark your blog . You definitely come with fabulous article content. Regards for sharing with us your web page.

  5. is hemp oil or cbd oil better for dogs

    There are definitely a lot of details like that to take into consideration. That is a great point to bring up. I offer the ideas above as general motivation however plainly there are inquiries like the one you bring up where the most crucial thing will be working in sincere good faith. I don?t know if best techniques have actually emerged around things like that, but I am sure that your task is plainly determined as a fair game. Both children as well as ladies really feel the influence of simply a moment?s satisfaction, for the rest of their lives.

  6. cbd oul fir dogs

    There are some interesting points in time in this short article however I don?t recognize if I see every one of them center to heart. There is some legitimacy yet I will hold opinion up until I explore it further. Great article, thanks as well as we desire a lot more! Added to FeedBurner also

  7. active cbd capsules

    This is the appropriate blog site for any person who wants to learn about this topic. You realize a lot its almost tough to suggest with you (not that I in fact would want?HaHa). You certainly placed a new spin on a topic thats been written about for several years. Wonderful stuff, just fantastic!

  8. see this website

    I?m satisfied, I need to state. Truly seldom do I encounter a blog that?s both enlightening as well as amusing, as well as let me tell you, you have actually hit the nail on the head. Your suggestion is impressive; the issue is something that not enough people are speaking smartly around. I am really delighted that I stumbled across this in my search for something relating to this.

  9. web site

    I?d have to talk to you below. Which is not something I normally do! I appreciate reviewing an article that will make people believe. Additionally, thanks for permitting me to comment!

  10. Jewell Coln

    Aw, this was a really good message. In suggestion I wish to place in creating like this furthermore? taking some time and actual effort to make an excellent short article? however what can I state? I hesitate alot and also never seem to obtain something done.

  11. pop over to this website

    After research a few of the article on your website now, and I really like your means of blog writing. I bookmarked it to my book marking site listing as well as will be examining back quickly. Pls take a look at my internet site also and also let me know what you believe.

  12. explanation

    An intriguing discussion deserves comment. I believe that you ought to compose more on this topic, it could not be a forbidden topic yet generally individuals are inadequate to talk on such topics. To the next. Thanks

  13. best web hosting company

    Greetings from California! I’m bored to death at work so
    I decided to check out your website on my iphone
    during lunch break. I love the info you provide here and can’t wait
    to take a look when I get home. I’m surprised at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, good blog!

  14. my company

    Can I simply claim what an alleviation to discover somebody who actually understands what theyre speaking about on the net. You absolutely recognize how to bring a problem to light and make it important. Even more individuals need to read this and also comprehend this side of the story. I cant think youre not extra popular because you definitely have the gift.

  15. Get More Info

    There are some interesting moments in this short article yet I don?t know if I see all of them facility to heart. There is some validity yet I will hold viewpoint up until I look into it even more. Good article, thanks and also we desire a lot more! Contributed to FeedBurner as well

  16. index

    The next time I review a blog, I wish that it does not dissatisfy me as long as this. I mean, I know it was my option to review, but I actually believed youd have something interesting to claim. All I hear is a number of yawping regarding something that you could take care of if you werent as well active seeking focus.

댓글 남기기

이메일은 공개되지 않습니다.