Microsoft MVP성태의 닷넷 이야기
VC++: 63. 다른 프로세스에 환경 변수 설정하는 방법 [링크 복사], [링크+제목 복사],
조회: 31002
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 3개 있습니다.)
VC++: 63. 다른 프로세스에 환경 변수 설정하는 방법
; https://www.sysnet.pe.kr/2/0/1297

.NET Framework: 366. 다른 프로세스에 환경 변수 설정하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1438

닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제
; https://www.sysnet.pe.kr/2/0/13502




다른 프로세스에 환경 변수 설정하는 방법


이에 대해서 지난번에 Appinit_Dlls를 통해서 구현해 봤었는데요.

Appinit_Dlls로 구현한 환경 변수 설정 DLL
; https://www.sysnet.pe.kr/2/0/883

아쉽게도, Vista 이후부터 강화된 보안으로 인해 가능한 "인증서 서명"을 하는 것이 권장되므로 사용하는 것이 녹록치 않습니다.

그래서, 다시 생각해 본 것이 "CreateRemoteThread"입니다. 이를 이용한 DllInjection 기법이 사용되곤 하는데, 특정 exe에만 Appinit_Dlls 레지스트리를 통해서 로드하던 바로 그 dll을 실행시키면 자연스럽게 환경 변수 설정이 되기 때문입니다.

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    SetEnvironmentVariable(L"TEST", "1");  // Kernel32.dll
    return FALSE; // FALSE를 반환하므로 대상 EXE에 어떤 부작용도 발생시키지 않음.
}

어떻게 구현하는지에 대해서는 웹을 검색해 보면 잘 설명되어 있는 자료를 쉽게/많이 찾을 수 있습니다.

DLL injection with CreateRemoteThread()
; http://blog.gwangyi.kr/entry/DLL-injection-with-CreateRemoteThread

이에 따라서 코딩을 해보면 다음과 같이 끝나고,

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
 //   char szDllName[] = "D:\\RemoteSetEnvVar\\Debug\\SetEnvVariable.dll";
    char szDllName[] = "D:\\RemoteSetEnvVar\\x64\\Debug\\SetEnvVariable.dll";
    HANDLE hProc = NULL;
    LPVOID pRemoteDll = NULL;

    BOOL result = 1;

    do
    {
        DWORD dwPID = 5012;
        if (argc == 2)
        {
            dwPID = _ttoi(argv[1]);
        }

        hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);

        if (hProc == NULL)
        {
            break;
        }

        pRemoteDll = VirtualAllocEx(hProc, NULL, sizeof(szDllName) + 1, MEM_COMMIT, PAGE_READWRITE);
        if(!pRemoteDll)
        {
            break;
        }

        if (!WriteProcessMemory(hProc, pRemoteDll, szDllName, sizeof(szDllName) + 1, NULL))
        {
            break;
        }

        HMODULE hKernel32 = GetModuleHandle(L"KERNEL32.DLL");
        LPTHREAD_START_ROUTINE pfnLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryA");
        if (pfnLoadLibrary == NULL)
        {
            break;
        }

        HANDLE hThread = CreateRemoteThread(hProc, NULL, 0, pfnLoadLibrary, pRemoteDll, 0, NULL);
        if (hThread == NULL)
        {
            break;
        }

        WaitForSingleObject(hThread, 1000 * 5); // 최대 5초 대기

        DWORD dwRet = 0;
        if (GetExitCodeThread(hThread, &dwRet) == TRUE)
        {
            TCHAR out[1024];
            swprintf_s(out, L"Injection finished.\nExit code: 0x%08lX", dwRet);
            result = 0;
        }

    } while (false);

    if (pRemoteDll != NULL)
    {
        // 이 단계에서 VirtualFree를 호출해서는 안된다.
        // 왜냐하면, 원격 프로세스에서 CreateRemoteThread가 호출되기까지 시간이 걸릴 수 있으므로,
        // 그사이 메모리가 해제되어 버리면 대상 프로세스가 비정상 종료될 수 있음.
        // 결과적으로 보면, Memory Leak이 발생하는 것과 같은데,
        // 만약, 자주 수행되는 경우라면 LoadLibrary로 올라오는 DLL에서 해제하는 방법을 강구해야 한다.
        // 여기서는 환경 변수를 설정하는 용도로 사용하므로, 메모리 누수에 대해 그다지 심각하지 않다고 판단되어 이렇게 주석처리하는 것으로 완료!
        // VirtualFreeEx(hProc, pRemoteDll, 0, MEM_RELEASE);
        pRemoteDll = NULL;
    }

    if (hProc != NULL)
    {
        CloseHandle(hProc);
        hProc = NULL;
    }

    return result;
}

주의할 것은, 32비트 프로세스에 대해서는 위의 코드를 실행하는 프로그램이 32비트여야 하고, 64비트에 대해서도 같은 규칙이 적용됩니다. 만약 어긋날 시에는 CreateRemoteThread의 GetLastError 값이 5로 나와서 "Access Denied" 오류 현상이 발생합니다.

아쉽게도 한가지 더 주의할 사항이 있는데요. 대상 프로세스가 세션이 다른 경우에는 다시 오류 코드 8로 "Not enough storage is available to process this command." 값이 나옵니다.

이에 대해서는 다음의 글에서 잘 설명이 되어 있는데요.

DLL Injection in Windows 7 (3)
; http://www.reversecore.com/75

Windows Vista 이후의 환경에서는 기존의 세션 0에서 실행되던 서비스 프로세스들이 별도로 분리되어 문제가 되는 것인데, 이는 NtCreateThreadEx를 사용하여 해결할 수 있습니다. 다만, 위의 글에서도 밝혔지만 그 함수가 undocumented라는 것으로 업무용으로 사용하기가 다소 껄끄럽다는 점이 있는데요. 이에 대해서 ^^ 또 다른 해결책이 하나 생각났습니다.

관리자 권한이 필요한 작업을 COM+에 대행
; https://www.sysnet.pe.kr/2/0/1290

즉, SYSTEM 권한으로 실행되는 COM+ EXE 서버를 이용하여 위의 코드를 실행하는 EXE를 실행해 주는 것입니다. 그렇게 되면 서비스 세션이 동일하기 때문에 정상적으로 CreateRemoteThread API가 동작하게 되고 환경 변수 설정이 자연스럽게 해결됩니다.

첨부된 소스 코드는 본문에서 소개한 예제 코드를 담은 간단한 프로젝트입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/23/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  [82]  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11886정성태5/7/201919256오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/201916195오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201920991.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201926211.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201922474.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201922603오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201918450오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201926847.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
11878정성태4/22/201922591.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff파일 다운로드1
11877정성태4/22/201922675.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas파일 다운로드1
11876정성태4/21/201921711.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others파일 다운로드1
11875정성태4/21/201922725오류 유형: 530. Visual Studo에서 .NET Core 프로젝트를 열 때 "One or more errors occurred." 오류 발생
11874정성태4/20/201922924.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals파일 다운로드1
11873정성태4/19/201921383.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers파일 다운로드1
11872정성태4/17/201922269.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members파일 다운로드1
11871정성태4/16/201920928.NET Framework: 818. (번역글) .NET Internals Cookbook Part 3 - Initialization tricks [3]파일 다운로드1
11870정성태4/16/201919196.NET Framework: 817. Process.Start로 실행한 콘솔 프로그램의 출력 결과를 얻는 방법파일 다운로드1
11869정성태4/15/201925018.NET Framework: 816. (번역글) .NET Internals Cookbook Part 2 - GC-related things [2]파일 다운로드2
11868정성태4/15/201921013.NET Framework: 815. CER(Constrained Execution Region)이란?파일 다운로드1
11867정성태4/15/201920142.NET Framework: 814. Critical Finalizer와 SafeHandle의 사용 의미파일 다운로드1
11866정성태4/9/201923309Windows: 159. 네트워크 공유 폴더(net use)에 대한 인증 정보는 언제까지 유효할까요?
11865정성태4/9/201919036오류 유형: 529. 제어판 - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools is not accessible.
11864정성태4/9/201917818오류 유형: 528. '...' could be '0': this does not adhere to the specification for the function '...'
11863정성태4/9/201917679디버깅 기술: 127. windbg - .NET x64 EXE의 EntryPoint
11862정성태4/7/201920151개발 환경 구성: 437. .NET EXE의 ASLR 기능을 끄는 방법
11861정성태4/6/201919613디버깅 기술: 126. windbg - .NET x86 CLR2/CLR4 EXE의 EntryPoint
... 76  77  78  79  80  81  [82]  83  84  85  86  87  88  89  90  ...