Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 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




다른 프로세스에 환경 변수 설정하는 방법 - 두 번째 이야기

지난 이야기에서 SYSTEM 권한으로 코드를 실행하는 방법을 설명했는데요.

Local SYSTEM 권한으로 코드를 실행하는 방법
; https://www.sysnet.pe.kr/2/0/1436

사실 '관리자 권한'으로 실행하는 경우는 많아도 SYSTEM 권한으로 실행할 만한 코드는 거의 없습니다. 그나마 있다면... SYSTEM 권한으로 실행되는 NT 프로세스의 환경 변수의 값을 바꾸는 경우가 있는데요. 예전에도 이와 관련된 글이 있었습니다.

다른 프로세스에 환경 변수 설정하는 방법
; https://www.sysnet.pe.kr/2/0/1297

COM+ 에 대행하기에는 너무 번거로운 선행 작업이 많아서 좀 불편한데요. 그래서, 이번에는 NT 서비스를 이용해 다시 한번 그 부분을 개선해 보기로 했습니다.

예제 프로그램의 목표는 모든 NT 서비스들의 부모 프로세스인 services.exe에 환경 변수를 설정하는 것입니다.




services.exe에 대해 CreateRemoteThread를 사용하는 것은 같지만, 그 코드를 실행하는 것은 "Local SYSTEM 권한으로 코드를 실행하는 방법"에서 설명했던 NT 서비스에서 할 것입니다.

문제는 servies.exe에 로드되는 DLL인데요. 아쉽게도 이것은 C# DLL로 만들 수 없습니다. 왜냐하면 C# 코드를 가진 DLL을 services.exe에 로드해서 실행시킬 수는 없기 때문입니다.

따라서 다음과 같이 2개의 프로젝트를 만들어야 합니다.

  • psexec2: C# EXE 프로젝트, 콘솔 프로그램이면서 스스로를 NT 서비스로 등록시켜 SYSTEM 권한으로 실행하는 코드를 함께 구현
  • SetEnvDll: C++ DLL 프로젝트, services.exe 측에 Injection 되어 환경 변수를 설정하는 함수를 실행

SetEnvDll의 소스 코드는 다음과 같이 간단합니다.

#include <Windows.h>
#pragma comment(lib, "kernel32.lib")

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
            SetEnvironmentVariable(L"ALLTEST", L"TEST");  // Kernel32.dll
            return FALSE;
        case DLL_THREAD_ATTACH:
            return FALSE;

        case DLL_THREAD_DETACH:
            return TRUE;
        case DLL_PROCESS_DETACH:
            return TRUE;
    }

    return FALSE;
}

빌드 방법도 다음의 글에 따라 해주시면 약 4K~5K 정도 됩니다.

Visual C++ CRT(C Runtime DLL: msvcr...dll)에 대한 의존성 제거
; https://www.sysnet.pe.kr/2/0/1437

그 다음은 위의 Win32 DLL을 Injection 시킬 세션 0에서 동작될 SYSTEM 권한의 프로세스가 필요한데요. 이는 psexec2 C# 프로젝트가 할 것입니다. psexec2 내의 코드는 다음의 글에서 설명한 것과 구조는 동일합니다.

Local SYSTEM 권한으로 코드를 실행하는 방법
; https://www.sysnet.pe.kr/2/0/1436

바뀌는 부분은 DoSystemRights 메소드에서 services.exe 프로세스에 Win32 DLL을 Injection 시켜야 하는데요. C++에서 이전에 했던 것처럼,

다른 프로세스에 환경 변수 설정하는 방법
; https://www.sysnet.pe.kr/2/0/1297

그대로 관련 Win32 API들을 C# P/Invoke를 사용해 DllImport로 변경해 주면 됩니다. 대충 다음과 같은 식으로 구성해 주면 되겠지요. ^^

private static void DoSystemRights()
{
    Process thisProcess = Process.GetCurrentProcess();

    // Win32 DLL을 services.exe 프로세스에 Injection 시킵니다.
    string folder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
    string dllPath = Path.Combine(folder, "SetEnvDll.dll");

    IntPtr NullPtr = IntPtr.Zero;

    Process[] processes = Process.GetProcessesByName("services");
    foreach (Process process in processes)
    {
        IntPtr hProc = IntPtr.Zero;
        IntPtr pRemoteDll = IntPtr.Zero;
        IntPtr hKernel32 = IntPtr.Zero;
        IntPtr hThread = IntPtr.Zero;

        // 같은 이름의 실행 파일이 가능하므로, 최대한 범위를 좁힌다.
        if (process.SessionId == thisProcess.SessionId)
        {
            do
            {
                hProc = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id);
                if (hProc == IntPtr.Zero)
                {
                    break;
                }

                byte[] contents = Encoding.ASCII.GetBytes(dllPath);
                pRemoteDll = Win32API.VirtualAllocEx(hProc, NullPtr, (uint)(contents.Length + 1),
                                    Win32API.AllocationType.Commit, Win32API.MemoryProtection.ReadWrite);
                if (pRemoteDll == IntPtr.Zero)
                {
                    break;
                }

                UIntPtr written = UIntPtr.Zero;
                if (Win32API.WriteProcessMemory(hProc, pRemoteDll, contents, (uint)(contents.Length + 1),
                                    out written) == false)
                {
                    break;
                }

                hKernel32 = Win32API.GetModuleHandle("kernel32.dll");

                UIntPtr pfnLoadLibrary = Win32API.GetProcAddress(hKernel32, "LoadLibraryA");
                if (pfnLoadLibrary == UIntPtr.Zero)
                {
                    break;
                }

                hThread = Win32API.CreateRemoteThread(hProc, NullPtr, 0, pfnLoadLibrary, pRemoteDll, 0, NullPtr);
                if (hThread == IntPtr.Zero)
                {
                    break;
                }

                Win32API.CloseHandle(hThread);

            } while (false);

            if (pRemoteDll != IntPtr.Zero)
            {
                Win32API.VirtualFreeEx(hProc, pRemoteDll, 0, Win32API.FreeType.Release);
                pRemoteDll = IntPtr.Zero;
            }

            if (hProc != IntPtr.Zero)
            {
                Win32API.CloseHandle(hProc);
                hProc = IntPtr.Zero;
            }
        }
    }
}

첨부된 파일에 동작되는 예제 코드를 구성했으니 참고하시고요. 기본 빌드 환경은 x64/Release로 되어 있고, Windows 8에서 테스트 해보았습니다.

빌드하고, /x64/Release/psexec2.exe를 실행하면 services.exe 프로세스에 "ALLTEST" 환경 변수의 값이 "TEST"로 새롭게 설정되는 것을 확인할 수 있습니다. (Process Explorer로 확인하시면 됩니다.)




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

[연관 글]






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

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

비밀번호

댓글 작성자
 



2020-07-03 04시22분
Vulnserver Exploit vs Windows Defender Exploit Guard
; https://chadduffey.com/2020/06/27/VulnServerVSExploitGuard.html

Exploit Guard vs Process (DLL) Injection
; https://chadduffey.com/2020/07/01/ExploitGuardImageLoads.html
정성태

... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11457정성태2/17/201824008.NET Framework: 732. C# - Task.ContinueWith 설명 [1]파일 다운로드1
11456정성태2/17/201829767.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법 [7]파일 다운로드1
11455정성태2/17/201818657오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201827539기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201819497오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201825013기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201819241디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201834518Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201821888오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201819404오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201820736.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201821757.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201819631.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201819726VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201820320VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201818119개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201816637오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201819919.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
11439정성태1/17/201824763기타: 69. C# - CPU 100% 부하 주는 프로그램파일 다운로드1
11438정성태1/17/201819500오류 유형: 446. Error CS0234 The type or namespace name 'ITuple' does not exist in the namespace
11437정성태1/17/201818829VS.NET IDE: 124. Platform Toolset 설정에 따른 Visual C++의 헤더 파일 기본 디렉터리
11436정성태1/16/201821075개발 환경 구성: 352. ASP.NET Core (EXE) 프로세스가 IIS에서 호스팅되는 방법 - ASP.NET Core Module(AspNetCoreModule) [4]
11435정성태1/16/201822174개발 환경 구성: 351. OWIN 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11434정성태1/15/201822547개발 환경 구성: 350. 사용자 정의 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11433정성태1/15/201820628개발 환경 구성: 349. dotnet ef 명령어 사용을 위한 준비
11432정성태1/11/201826382.NET Framework: 726. WPF + Direct2D + SharpDX 출력 C# 예제파일 다운로드2
... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...