Microsoft MVP성태의 닷넷 이야기
닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제 [링크 복사], [링크+제목 복사]
조회: 2488
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 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




C# - 다른 프로세스의 환경변수 읽는 예제

마침 아래의 글이 있군요. ^^

Read Environment Strings of Remote Process
; https://www.codeproject.com/Articles/25647/Read-Environment-Strings-of-Remote-Process

위의 글은 32비트를 대상으로 하는데 64비트도 거의 유사하게 추적할 수 있습니다. 우선, _TEB 주소를 구해야 하는데, 이것은 GS:[0x30]에 위치하고 있습니다.

0:003> dt _TEB
ntdll!_TEB
   +0x000 NtTib            : _NT_TIB
   ...[생략]...

0:003> dt _NT_TIB
ntdll!_NT_TIB
   +0x000 ExceptionList    : Ptr64 _EXCEPTION_REGISTRATION_RECORD
   +0x008 StackBase        : Ptr64 Void
   +0x010 StackLimit       : Ptr64 Void
   +0x018 SubSystemTib     : Ptr64 Void
   +0x020 FiberData        : Ptr64 Void
   +0x020 Version          : Uint4B
   +0x028 ArbitraryUserPointer : Ptr64 Void
   +0x030 Self             : Ptr64 _NT_TIB

이렇게 구한 TEB의 위치에서 PEB를 구하는데 이것은 0x60에 위치합니다.

0:003> dt _TEB
ntdll!_TEB
   +0x000 NtTib            : _NT_TIB
   +0x038 EnvironmentPointer : Ptr64 Void
   +0x040 ClientId         : _CLIENT_ID
   +0x050 ActiveRpcHandle  : Ptr64 Void
   +0x058 ThreadLocalStoragePointer : Ptr64 Void
   +0x060 ProcessEnvironmentBlock : Ptr64 _PEB
   ...[생략]...

PEB를 구했으면 그것의 0x20 위치에 ProcessParameters가 위치하고,

0:003> dt _PEB
ntdll!_PEB
   +0x000 InheritedAddressSpace : UChar
   +0x001 ReadImageFileExecOptions : UChar
   ...[생략]...
   +0x010 ImageBaseAddress : Ptr64 Void
   +0x018 Ldr              : Ptr64 _PEB_LDR_DATA
   +0x020 ProcessParameters : Ptr64 _RTL_USER_PROCESS_PARAMETERS
   ...[생략]...

마지막으로, 0x80 위치에서 환경변수 목록을 구할 수 있습니다.

0:003> dt _RTL_USER_PROCESS_PARAMETERS
ntdll!_RTL_USER_PROCESS_PARAMETERS
   +0x000 MaximumLength    : Uint4B
   ...[생략]...
   +0x050 DllPath          : _UNICODE_STRING
   +0x060 ImagePathName    : _UNICODE_STRING
   +0x070 CommandLine      : _UNICODE_STRING
   +0x080 Environment      : Ptr64 Void
   +0x088 StartingX        : Uint4B

자, 그럼 이 과정을 그대로 C# + P/Invoke 호출을 이용해 구현하면 됩니다. ^^




하지만 실제 소스코드 구현에서는 위의 설명 과정에서 TEB로부터 PEB를 구하는 과정은 생략합니다. 왜냐하면, 처음부터 PEB를 구할 수 있기 때문인데요, "Read Environment Strings of Remote Process" 글의 소스코드에 잘 나와 있습니다. 그리고 아래는 그것을 C#으로 포팅한 예제입니다.

using System.Diagnostics;
using System.Runtime.InteropServices;
using static ConsoleApp1.NativeMethods;

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        int pid = 52436;

        foreach (var item in GetRemoteEnvironmentVariables(pid))
        {
            Console.WriteLine($"{item.Key}={item.Value}");
        }
    }

    public unsafe static Dictionary<string, string> GetRemoteEnvironmentVariables(int pid)
    {
        Dictionary<string, string> envVariables = new Dictionary<string, string>();

        PROCESS_BASIC_INFORMATION processInformation = new PROCESS_BASIC_INFORMATION();
        IntPtr processHandle = Process.GetProcessById(pid).Handle;
        int requireLength = 0;

        int pbiSize = Marshal.SizeOf<PROCESS_BASIC_INFORMATION>();
        int ntStatus = NtQueryInformationProcess(processHandle, PROCESSINFOCLASS.BasicInformation, ref processInformation, pbiSize, ref requireLength);
        if (ntStatus != 0)
        {
            Console.WriteLine("failed to get PEB address");
            return envVariables;
        }

        byte[] buffer = new byte[pbiSize];
        ulong readLength = 0;
        ReadProcessMemory(processHandle, processInformation.PebBaseAddress, buffer, pbiSize, &readLength);
        if (readLength == 0)
        {
            Console.WriteLine("failed to read PEB");
            return envVariables;
        }

        IntPtr pProcessParameters;
        // read int64 from buffer at offset 0x20
        fixed (byte* p = buffer)
        {
            pProcessParameters = Marshal.ReadIntPtr(new IntPtr(p + 0x20));
            if (pProcessParameters == IntPtr.Zero)
            {
                Console.WriteLine("failed to get _RTL_USER_PROCESS_PARAMETERS address");
                return envVariables;
            }
        }

        buffer = new byte[0x80 + 8];
        ReadProcessMemory(processHandle, pProcessParameters, buffer, buffer.Length, &readLength);
        if (readLength == 0)
        {
            Console.WriteLine("failed to read _RTL_USER_PROCESS_PARAMETERS");
            return envVariables;
        }

        IntPtr pEnvironment;
        fixed (byte* p = buffer)
        {
            pEnvironment = Marshal.ReadIntPtr(new IntPtr(p + 0x80));
            if (pEnvironment == IntPtr.Zero)
            {
                Console.WriteLine("failed to get environment address");
                return envVariables;
            }
        }

        int envSize = GetRegionSize(processHandle, pEnvironment);
        buffer = new byte[envSize];
        ReadProcessMemory(processHandle, pEnvironment, buffer, envSize, &readLength);
        if (readLength == 0)
        {
            Console.WriteLine("failed to read environment");
            return envVariables;
        }

        fixed (byte* p = buffer)
        {
            char* pEnv = (char*)p;

            while (true)
            {
                if (*pEnv == '\0') // double null terminated
                {
                    break;
                }

                string text = new string(pEnv);

                pEnv = pEnv + text.Length;
                if (*pEnv != '\0') // must be '\0';
                {
                    break;
                }

                pEnv++;

                string [] nameValue = text.Split('=');
                if (nameValue.Length < 2)
                {
                    continue;
                }

                envVariables.Add(nameValue[0], nameValue[1]);
            }
        }

        return envVariables;
    }

    static int GetRegionSize(IntPtr hProcess, IntPtr pAddress)
    {
        _MEMORY_BASIC_INFORMATION64 mbi = new _MEMORY_BASIC_INFORMATION64();
        uint mbiSize = (uint)Marshal.SizeOf<_MEMORY_BASIC_INFORMATION64>();
        int readBytes = NativeMethods.VirtualQueryEx(hProcess, pAddress, ref mbi, mbiSize);

        if (mbi.Protect == PAGE_NOACCESS ||
            mbi.Protect == PAGE_EXECUTE)
        {
            return 0;
        }

        if (readBytes != mbiSize)
        {
            return 0;
        }

        ulong diff = (ulong)pAddress - (ulong)mbi.BaseAddress;

        return (int)mbi.RegionSize - (int)diff;
    }
}

위에서, 재미있는 부분이 하나 있다면, 환경변수 주소를 가져온 다음 그 영역을 읽어내는 것입니다. 사실, _RTL_USER_PROCESS_PARAMETERS 구조체에는 환경변수 주소만 있고 그 크기에 대한 정보가 없습니다.

"Read Environment Strings of Remote Process" 글에서는 이 부분을 VirtualQueryEx를 통해 해결하고 있는데요,

BOOL CProcessEnvReader::HasReadAccess( HANDLE hProcess,
                                        void* pAddress, int& nSize )
{
    MEMORY_BASIC_INFORMATION memInfo;
    __try
    {
        VirtualQueryEx( hProcess, pAddress,&memInfo,sizeof(memInfo));
        if( PAGE_NOACCESS == memInfo.Protect ||
        PAGE_EXECUTE == memInfo.Protect )
        {
            nSize = 0;
            return FALSE;
        }
        nSize = memInfo.RegionSize;
        return TRUE;
    }
    __except( SHOW_ERR_DLG( _T("Failed to query memory access")))
    {
    }
    return FALSE;
} 

전에 저도 이 함수를 이용해 스택 메모리의 상태 출력을 한 적이 있습니다.

C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력
; https://www.sysnet.pe.kr/2/0/13174

그런데, 위의 소스 코드에는 문제가 하나 있습니다. 환경변수를 가리키는 pAddress로 전달한 주소가 해당 Region의 시작 주소와 일치하지 않기 때문에 전체 RegionSize를 반환해 버리면 저 영역을 넘어선 부분까지 읽기 시도를 할 수가 있습니다.

아마도 저 소스코드는 32비트에서 테스트해서 운이 좋게 다음 Region도 commit 영역이었을 확률이 높지만 x64의 광활한 메모리 공간에서는 오류 확률이 매우 높게 됩니다.

따라서, BaseAddress로부터 pAddress가 떨어진 만큼의 크기를 RegionSize에서 빼서 반환하는 보정을 거쳐야 합니다.

static int GetRegionSize(IntPtr hProcess, IntPtr pAddress)
{
    _MEMORY_BASIC_INFORMATION64 mbi = new _MEMORY_BASIC_INFORMATION64();
    uint mbiSize = (uint)Marshal.SizeOf<_MEMORY_BASIC_INFORMATION64>();
    int readBytes = NativeMethods.VirtualQueryEx(hProcess, pAddress, ref mbi, mbiSize);

    if (mbi.Protect == PAGE_NOACCESS ||
        mbi.Protect == PAGE_EXECUTE)
    {
        return 0;
    }

    if (readBytes != mbiSize)
    {
        return 0;
    }

    ulong diff = (ulong)pAddress - (ulong)mbi.BaseAddress;8
    return (int)mbi.RegionSize - (int)diff;
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)

참고로, PEB, _RTL_USER_PROCESS_PARAMETERS의 offset 위치가 운영체제/패치마다 다를 수도 있습니다. 아마도 환경변수 영역은 거의 변하지 않을 거라 예상은 하지만 그래도 안전하게 하고 싶다면 "KernelStructOffset" 등의 도움을 받으면 됩니다.




보통, TEB를 가져오기 위한 용도로 (x64의 경우) GS 세그먼트를 사용한 연산을 합니다. 일례로, Visual C++의 __readgsqword 함수를 사용하면 이렇게 TEB를 가져올 수 있는데요,

unsigned __int64 fsSelf = __readgsqword(0x30);

기계어로는 다음과 같이 번역됩니다.

mov         rax,qword ptr gs:[30h]  
mov         qword ptr [fsReg],rax 

그런데 재미있는 건, 0x30h의 값이 바로 TEB 자신의 주솟값이라는 것입니다.

lkd> dt _TEB
nt!_TEB
   +0x000 NtTib            : _NT_TIB
   +0x038 EnvironmentPointer : Ptr64 Void
   +0x040 ClientId         : _CLIENT_ID
   +0x050 ActiveRpcHandle  : Ptr64 Void
...[생략]...

lkd> dt _NT_TIB
nt!_NT_TIB
   +0x000 ExceptionList    : Ptr64 _EXCEPTION_REGISTRATION_RECORD
   +0x008 StackBase        : Ptr64 Void
   +0x010 StackLimit       : Ptr64 Void
   +0x018 SubSystemTib     : Ptr64 Void
   +0x020 FiberData        : Ptr64 Void
   +0x020 Version          : Uint4B
   +0x028 ArbitraryUserPointer : Ptr64 Void
   +0x030 Self             : Ptr64 _NT_TIB

재미있지 않나요? ^^ 그냥 gs 레지스터가 가리키는 값을 가져오면 될 텐데, 왜 굳이 gs:[0x30]으로 가는 방식으로 정해서 구조체에까지 영향을 주는 식으로 정의를 했을까요?

사실 GS는 일반적인 레지스터가 아닌 세그먼트 레지스터라서 그것 자체의 값은 주소가 아닙니다.

0:007> r gs
gs=002b

그리고 저 Selector에 해당하는 정보를 구하면,

0:007> dg gs
                                                    P Si Gr Pr Lo
Sel        Base              Limit          Type    l ze an es ng Flags
---- ----------------- ----------------- ---------- - -- -- -- -- --------
002B 00000000`00000000 00000000`ffffffff Data RW Ac 3 Bg Pg P  Nl 00000cf3

의외로 Base 주솟값이 00000000`00000000으로 나옵니다. 아니, 그렇다면 gs:[0x30]은 결국 0x30 가상 주소를 가리키는 것과 같을 텐데요, 당연히 이 영역은 null 주소에 가까운 페이지라서 커밋이 안 돼 있는 영역입니다.

0:007> dd 0x30 L4
00000000`00000030  ???????? ???????? ???????? ????????

이게 가능한 이유는,

windbg - Why does the GS register resolve to offset 0x0?
; https://reverseengineering.stackexchange.com/questions/21033/windbg-why-does-the-gs-register-resolve-to-offset-0x0

특별히, gs의 경우에는 MSR(Model Specific Registers)에 보관된 값을 base address로 사용하기 때문이라고 합니다.

SWAPGS
; https://wiki.osdev.org/SWAPGS

위의 문서에 보면,

(IA32_FS_BASE) FSBase is MSR 0xC0000100, 
(IA32_GS_BASE) GSBase is 0xC0000101, 
(IA32_KERNEL_GS_BASE) and KernelGSBase is 0xC0000102.

// 그 외, IA32_DS_AREA, IA32_L-STAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP

MSR에서 GS가 참조하는 주솟값이 나옵니다.




마지막으로, 다음과 같이 코딩을 하면,

; gs_register.asm
; MASM - "ml64.exe /c /nologo /Zi /Fo"x64\Debug\gs_register.obj" /W3 /errorReport:prompt  /Tags_register.asm"

    .code

get_gs_addr proc
    mov rax, ds:[20]    
    ret

get_gs_addr endp

end

"error A2202: illegal use of segment register" 오류가 발생합니다. 검색해 보면, 64비트 모드에서 CS/DS/ES/SS를 오버라이드할 수는 있지만 실제로는 무시되기 때문에 MASM의 경우에는 아예 지정하지 못하게 막았고, 다른 어셈블러들은 허용했다고 합니다. 그래도 이게 아주 쓸모없지는 않은 게, CS/DS/ES/SS로 지정함으로써 명령어 길이를 늘려 메모리 정렬을 맞추기 위한 패딩 용도로 쓴다고 합니다.

반면, 원래 이 글에서 우리가 원했던 표현은,

mov rax, gs:0 // error A2027: operand must be a memory expression

GS가 명시된 경우 오퍼랜드로 가능한 것은 반드시 메모리 (주솟값 자체가 아닌) 참조만 가능하다고 합니다. 만약 저 표현이 가능했다면 "mov rax, gs:[0x30]" 코드는 필요 없었을 것입니다.




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







[최초 등록일: ]
[최종 수정일: 12/28/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13331정성태4/27/20233885오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233529Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233723Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233398VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233807VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235231.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234525스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234356.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234287개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235063VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233890개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233867개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234307개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234142개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234234오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233562오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233760Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233847개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233934개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233945Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234459C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234043C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234219.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234117스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233881.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233675Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...