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

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13768정성태10/15/20245396C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20244771오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20244553C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20245264오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20245631Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20244985Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20245010Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20244914오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20245448Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20246366C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20245578오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/20245521닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/20245626오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20246025닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20245578닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20245594Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20246280닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20245407C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20245293C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20245536닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20245743닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20245592닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20245687오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20245550Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245980닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20246427닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...