Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 5개 있습니다.)
.NET Framework: 335. C# - (핸들을 이용하여) 모든 열린 파일을 열람
; https://www.sysnet.pe.kr/2/0/1338

.NET Framework: 525. C# - 닷넷에서 프로세스가 열고 있는 파일 목록을 구하는 방법
; https://www.sysnet.pe.kr/2/0/10833

.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
; https://www.sysnet.pe.kr/2/0/12080

.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12107

.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12195




C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기

지난 글에서,

C# - 프로세스의 모든 핸들을 열람
; https://www.sysnet.pe.kr/2/0/12080

시스템의 모든 프로세스에 대한 윈도우 핸들을 열람하는 것을 알아봤는데요.

// Install-Package KernelStructOffset

using (WindowsHandleInfo whi = new WindowsHandleInfo())
{
    for (int i = 0; i < whi.HandleCount; i++)
    {
        SYSTEM_HANDLE_ENTRY she = whi[i];

        if (she.UniqueProcessId != processId)
        {
            continue;
        }

        string objName = she.GetName(out string handleTypeName);

        Console.WriteLine($"{handleTypeName}: {objName}");
    }
}

재미있는 것은, 특정 프로세스가 권한도 충분한데 열람이 안 되는 문제가 있었습니다. 왜냐하면 SYSTEM_HANDLE_ENTRY의,

[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_HANDLE_ENTRY
{
    public int UniqueProcessId;
    public byte ObjectType;
    public byte HandleFlags;
    public short HandleValue;
    public IntPtr ObjectPointer;
    public int AccessMask;
}

UniqueProcessId가 실은 int 형이 아닌,

[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_HANDLE_ENTRY
{
    public short UniqueProcessId;
    public short CreatorBackTraceIndex;
    public byte ObjectType;
    public byte HandleFlags;
    public short HandleValue;
    public IntPtr ObjectPointer;
    public int AccessMask;
}

2개의 필드를 하나로 합친 것으로써 원래는 short형이었기 때문입니다. 그래서 PID가 65535보다 크면 overflow가 발생해 정상적인 조회가 안 된 것입니다. 다행히 이에 대해서 검색해 보면 해법이 나오는데요,

Why can't get process id that more than 65535 by 'ntQuerySystemInformation' in Win7 64bit?
; https://stackoverflow.com/questions/23951043/why-cant-get-process-id-that-more-than-65535-by-ntquerysysteminformation-in-w

따라서 NtQuerySystemInformation에 SYSTEM_EXTENDED_HANDLE_INFORMATION == 64 값을 전달하고,

NativeMethods.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemExtendedHandleInformation, ptr, guessSize, out requiredSize);

반환받은 버퍼의 구조는 다음과 같은 구조로,

[StructLayout(LayoutKind.Sequential)]
public struct _SYSTEM_HANDLE_INFORMATION_EX
{
    public IntPtr HandleCount;
    public IntPtr Reserved;
    public _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles; /* Handles[0] */

    public int NumberOfHandles
    {
        get { return HandleCount.ToInt32(); }
    }
}

IntPtr.Size * 2만큼의 위치부터 새로운 _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX 구조체로 받아오면 됩니다.

[StructLayout(LayoutKind.Sequential)]
public struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
{
    public IntPtr ObjectPointer;
    public IntPtr UniqueProcessId;
    public IntPtr HandleValue;
    public uint GrantedAccess;
    public ushort CreatorBackTraceIndex;
    public ushort ObjectTypeIndex;
    public uint HandleAttributes;
    public uint Reserved;

    public int OwnerPid
    {
        get { return UniqueProcessId.ToInt32(); }
    }
}

(DotNetSamples/WinConsole/Debugger/KernelStructOffset/WindowsHandleInfo.cs의 코드는 위의 변경 사항이 적용된 것입니다.)




열거된 핸들이 다른 프로세스에 있는 경우, 해당 핸들의 정보를 조회하기 위해서는 현재 프로세스 핸들 목록에 복사해 놓아야 합니다. 핸들 복사는 다음과 같은 식으로 하면 되는데요.

{
    IntPtr targetHandle = ...[다른 프로세스의 Handle]...;
    int targetPid = ...[targetHandle 핸들을 소유하고 있는 ProcessId]...;
    IntPtr targetProcessHandle = OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, false, targetPid);

    IntPtr currentProcess = NativeMethods.GetCurrentProcess();
    IntPtr duplicatedHandle;

    bool dupResult = DuplicateHandle(
        targetProcessHandle, targetHandle, currentProcess, out duplicatedHandle
        , 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS);
}

대개의 경우, 원본 핸들과 동일한 권한(DUPLICATE_SAME_ACCESS)으로 복사하면 문제가 없는데 간혹 Process 타입의 핸들인 경우 GetModuleFileNameEx로 호출했을 때,

StringBuilder sb = new StringBuilder(4096);
int length = GetModuleFileNameEx(duplicatedHandle, IntPtr.Zero, sb, sb.Capacity);

length == 0이 나오면서 StringBuilder 버퍼에는 3개의 문자 정도가 다음과 같은 쓰레기 값으로 채워져 있습니다.

[0] 0x0050 'P'  char
[1] 0x0001 '\u0001' char
[2] 0xfffd ''   char

이런 문제가 발생하는 Process 타입 핸들은 권한을 조회해 보면 SYNCHRONIZE(0x00100000)만 가지고 있는 것을 볼 수 있습니다. 따라서 위의 결과를 반환하는 핸들은 DuplicateHandle 시 다음과 같은 옵션으로 복제해야 합니다.

// PROCESS_VM_READ = 0x10,
// PROCESS_QUERY_INFORMATION = 0x0400,

int addAccessRights = (int)(ProcessAccessRights.PROCESS_VM_READ | ProcessAccessRights.PROCESS_QUERY_INFORMATION);
bool dupResult = DuplicateHandle(targetProcessHandle, targetHandle, currentProcess, out duplicatedHandle
        , addAccessRights, false, 0);

다른 타입의 핸들도 이런 식으로 그 타입에 맞는 권한을 조정해야 하는데 이게 좀 애매합니다. 왜냐하면, 해당 핸들의 타입을 알기 위해서는 DuplicateHandle을 해야 하는데 그때 미리 access rights를 부여하는 것이 올바른 동작인지에 대해서는 보장할 수 없기 때문입니다. 예를 들어 프로세스인 경우 PROCESS_QUERY_INFORMATION = 0x0400이지만 스레드인 경우에는 THREAD_QUERY_INFORMATION = 0x0040이 되므로 어떤 핸들을 복사해야 하느냐에 따라 권한을 위한 상수도 달라집니다.

결국 한 번은 핸들의 타입을 알기 위해 복제를 해야 하고, 이후 다시 한번 타입에 따른 권한 설정을 위해 복제를 해야만 하는 식입니다.




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







[최초 등록일: ]
[최종 수정일: 1/11/2020]

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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11463정성태3/15/201820288.NET Framework: 733. 스레드 간의 read/write 시에도 lock이 필요 없는 경우파일 다운로드1
11462정성태3/14/201823892개발 환경 구성: 354. HTTPS 호출에 대한 TLS 설정 확인하는 방법 [1]
11461정성태3/13/201826247오류 유형: 454. 윈도우 업데이트 설치 오류 - 0x800705b4 [1]
11460정성태3/13/201818347디버깅 기술: 112. windbg - 닷넷 메모리 덤프에서 전역 객체의 내용을 조사하는 방법
11459정성태3/13/201819581오류 유형: 453. Debug Diagnostic Tool에서 mscordacwks.dll을 찾지 못하는 문제
11458정성태2/21/201820473오류 유형: 452. This share requires the obsolete SMB1 protocol, which is unsafe and could expose your system to attack. [1]
11457정성태2/17/201824628.NET Framework: 732. C# - Task.ContinueWith 설명 [1]파일 다운로드1
11456정성태2/17/201830719.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법 [7]파일 다운로드1
11455정성태2/17/201819942오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201828901기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201820707오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201826091기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201819906디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201836167Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201822824오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201820918오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201822195.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201822510.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201820806.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201820345VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201821797VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201818829개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201817286오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201820605.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
11439정성태1/17/201826282기타: 69. C# - CPU 100% 부하 주는 프로그램파일 다운로드1
11438정성태1/17/201820186오류 유형: 446. Error CS0234 The type or namespace name 'ITuple' does not exist in the namespace
... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...