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
정성태

... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11224정성태6/13/201718144.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716825개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720549오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717511오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722904.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718215.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721018개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716914오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719020오류 유형: 396. Activation context generation failed
11215정성태6/1/201719950오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717694오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722471오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721815오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720854오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721295기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768217Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727943오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728242Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721542오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721267.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730804개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718737오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719807오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722550오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719327오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201721151.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...