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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  [116]  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11025정성태8/12/201622359개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621670오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201623225개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201623875개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201620898오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201623638VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201640299기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201624773.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201626899웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201624033개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201622278오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201623066오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
11013정성태8/6/201633869개발 환경 구성: 290. Windows 10에서 경험해 보는 Windows Containers와 docker [4]
11012정성태8/6/201623927오류 유형: 346. Windows 10에서 Windows Containers의 docker run 실행 시 encountered an error during CreateContainer failed in Win32 발생
11011정성태8/6/201625558기타: 59. outlook.live.com 메일 서비스의 아웃룩 POP3 설정하는 방법
11010정성태8/6/201622885기타: 58. Outlook에 설정한 SMTP/POP3(예:천리안 메일) 계정 암호를 잊어버린 경우
11009정성태8/3/201628079개발 환경 구성: 289. 2016-08-02부터 시작된 윈도우 10 1주년 업데이트에서 Bash Shell 사용 [8]
11008정성태8/1/201621926오류 유형: 345. 2의 30승 이상의 원소를 갖는 경우 버그가 발생하는 이진 검색(Binary Search) 코드
11007정성태8/1/201623659오류 유형: 344. RDP ActiveX 컨트롤로 특정 PC에 연결할 수 없을 때, 오류 상황을 해결하기 위한 팁파일 다운로드1
11006정성태7/22/201626601개발 환경 구성: 288. SSL 인증서를 Azure Cloud Service에 적용하는 방법
11005정성태7/22/201625260개발 환경 구성: 287. Let's Encrypt 인증서 업데이트 주기: 90일
11004정성태7/22/201620095오류 유형: 343. Invalid service definition or service configuration. Please see the Error List for more details.
11003정성태7/20/201627378VS.NET IDE: 110. Visual Studio 2015에서 .NET Core 응용 프로그램 개발 [1]
11002정성태7/20/201620854개발 환경 구성: 286. Microsoft Azure 서비스의 구독은 반드시 IE로!
11001정성태7/19/201631941.NET Framework: 599. .NET Core/SDK 설치 및 기본 사용법 [6]
11000정성태7/16/201620631오류 유형: 342. Microsoft Visual Studio 2010 Tools for Office Runtime (x86 and x64) 설치 시 오류
... 106  107  108  109  110  111  112  113  114  115  [116]  117  118  119  120  ...