메뉴 닫기

SYSTEM 권한(Windows Service) 에서 일반사용자 (user) 권한으로 프로세스 실행

INT_PTR ExcuteAsUser(TCHAR* szCmd)
{
    BOOL bRet;
    INT_PTR hr;
    HANDLE processToken = NULL;
    TOKEN_PRIVILEGES oldTokenPrivileges = { 0 };
    HANDLE impersonationToken = NULL;
    HANDLE userToken = NULL;
    LPVOID pEnvironment = NULL;
    PROCESS_INFORMATION processInformation = { 0 };
    __try {
        bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &processToken);
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
        // This step might not be necessary because SeTcbPrivilege is enabled by default for Local System
        LUID luid;
        bRet = LookupPrivilegeValue(NULL, SE_TCB_NAME, &luid);
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
        TOKEN_PRIVILEGES adjTokenPrivileges = { 0 };
        adjTokenPrivileges.PrivilegeCount = 1;
        adjTokenPrivileges.Privileges[0].Luid = luid;
        adjTokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        DWORD dwOldTPLen;
        bRet = AdjustTokenPrivileges(processToken, FALSE, &adjTokenPrivileges, sizeof(TOKEN_PRIVILEGES), &oldTokenPrivileges, &dwOldTPLen);
        if (bRet) {
            hr = GetLastError();
            if (hr == ERROR_SUCCESS);
            else if (hr == ERROR_NOT_ALL_ASSIGNED) {
                // Enabled by default
            }
        }
        else {
            hr = GetLastError();
            return hr;
        }
        //WTSGetActiveConsoleSessionId, WTSQueryUserToken 함수를 Kernel32.dll에서 직접가져오는 이유는
        //원래 함수가 XP이상 지원이라서..
        HMODULE hInstKernel32 = NULL;
        HMODULE hInstWtsapi32 = NULL;
        typedef DWORD (WINAPI *WTSGetActiveConsoleSessionIdPROC)();
        WTSGetActiveConsoleSessionIdPROC WTSGetActiveConsoleSessionId = NULL;
        hInstKernel32 = LoadLibrary("Kernel32.dll");
        if (!hInstKernel32)
        {
            return -1;
        }
        WTSGetActiveConsoleSessionId = (WTSGetActiveConsoleSessionIdPROC)GetProcAddress(hInstKernel32,"WTSGetActiveConsoleSessionId");
        DWORD conSessId = WTSGetActiveConsoleSessionId();
        if (conSessId == 0xFFFFFFFF) {
            // There is no session attached to the console
            return ERROR_SUCCESS;
        }
        typedef BOOL (WINAPI *WTSQueryUserTokenPROC)(ULONG SessionId, PHANDLE phToken );
        WTSQueryUserTokenPROC WTSQueryUserToken = NULL;
        hInstWtsapi32 = LoadLibrary("Wtsapi32.dll");
        if (!hInstWtsapi32)
        {
            return -1;
        }
        WTSQueryUserToken = (WTSQueryUserTokenPROC)GetProcAddress(hInstWtsapi32,"WTSQueryUserToken");
        bRet = WTSQueryUserToken(conSessId, &impersonationToken);
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
        bRet = DuplicateTokenEx(impersonationToken, MAXIMUM_ALLOWED, NULL, SecurityIdentification, TokenPrimary, &userToken);
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
        STARTUPINFO si = { 0 };
        si.cb = sizeof(STARTUPINFO);
        si.lpDesktop = _T("winsta0\\default");
        bRet = CreateEnvironmentBlock(&pEnvironment, userToken, TRUE);
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
        bRet = CreateProcessAsUser(
            userToken,
            szCmd,
            NULL,
            NULL,
            NULL,
            FALSE,
            CREATE_UNICODE_ENVIRONMENT,
            pEnvironment,
            NULL,
            &si,
            &processInformation
            );
        if (!bRet) {
            hr = GetLastError();
            return hr;
        }
    }
    __finally {
        if (processInformation.hThread) {
            CloseHandle(processInformation.hThread);
        }
        if (processInformation.hProcess) {
            CloseHandle(processInformation.hProcess);
        }
        if (pEnvironment) {
            bRet = DestroyEnvironmentBlock(pEnvironment);
        }
        if (userToken) {
            CloseHandle(userToken);
        }
        if (impersonationToken) {
            CloseHandle(impersonationToken);
        }
        if (processToken) {
            bRet = AdjustTokenPrivileges(processToken, FALSE, &oldTokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
            CloseHandle(processToken);
        }
    }
    return 0;
}  

34 Comments

  1. g say

    You actually make it seem so easy with your presentation but I find this
    matter to be actually something which I think I would never understand.
    It seems too complex and very broad for me. I am
    looking forward for your next post, I’ll try to
    get the hang of it!

  2. g only

    An outstanding share! I’ve just forwarded this onto a co-worker who was doing a little research on this.
    And he in fact bought me breakfast simply because I stumbled upon it
    for him… lol. So let me reword this…. Thanks for the
    meal!! But yeah, thanks for spending time to discuss this matter here on your site.

  3. Shakita Wahington

    I just want to say I am newbie to blogging and site-building and seriously loved your blog site. More than likely I’m want to bookmark your blog . You definitely come with wonderful article content. With thanks for sharing your blog site.

  4. buy online viagra in usa

    There are some fascinating points in time in this short article yet I don?t know if I see every one of them center to heart. There is some legitimacy but I will certainly take hold point of view up until I check out it even more. Good post, many thanks and also we want much more! Included in FeedBurner also

  5. best web hosting sites

    It’s a shame you don’t have a donate button! I’d without a doubt donate to
    this excellent blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to
    my Google account. I look forward to brand new updates and will share this blog with
    my Facebook group. Chat soon!

  6. click here for more

    I uncovered your blog website on google and also check a few of your early blog posts. Continue to maintain the great operate. I simply extra up your RSS feed to my MSN Information Visitor. Looking for forward to learning more from you later!?

  7. Loan Judkins

    Aw, this was a truly good post. In idea I want to place in composing similar to this furthermore? taking time as well as real initiative to make a great post? however what can I claim? I postpone alot as well as never seem to obtain something done.

  8. Kyung Dankert

    Aw, this was an actually great message. In suggestion I would love to put in composing similar to this in addition? taking some time as well as real initiative to make an excellent post? yet what can I state? I postpone alot and also never seem to get something done.

  9. read more

    This internet site is actually a walk-through for every one of the details you desired regarding this and also didn?t understand that to ask. Glance below, as well as you?ll absolutely find it.

  10. home page

    I?m pleased, I need to state. Really seldom do I run into a blog that?s both enlightening as well as entertaining, as well as let me tell you, you have actually struck the nail on the head. Your suggestion is superior; the problem is something that inadequate people are speaking smartly about. I am extremely satisfied that I stumbled across this in my look for something associating with this.

  11. this contact form

    An interesting conversation deserves remark. I believe that you need to create much more on this subject, it might not be a taboo subject but typically people are not enough to talk on such subjects. To the following. Cheers

  12. Google

    May I simply just say what a relief to discover a person that genuinely knows what they’re talking about over the internet. You certainly know how to bring an issue to light and make it important. More and more people have to read this and understand this side of your story. I was surprised that you aren’t more popular given that you certainly have the gift.

  13. Check This Out

    An outstanding share, I simply provided this onto a coworker who was doing a little evaluation on this. And he in fact bought me breakfast since I discovered it for him. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for investing the moment to review this, I feel highly regarding it and enjoy reading more on this subject. Preferably, as you come to be proficiency, would certainly you mind upgrading your blog with even more details? It is extremely useful for me. Big thumb up for this blog post!

  14. click

    The following time I check out a blog site, I wish that it does not dissatisfy me as high as this. I mean, I understand it was my selection to read, yet I in fact assumed youd have something interesting to say. All I listen to is a number of whining concerning something that you might repair if you werent as well busy seeking interest.

댓글 남기기

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