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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...
NoWriterDateCnt.TitleFile(s)
12186정성태3/12/20209629오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010341오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011736오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010071오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011302.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202012075기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208693오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202020114개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011651개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011239개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010639개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010757개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010295개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011296개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
12172정성태3/7/202016181개발 환경 구성: 474. docker - container에서 root 권한 명령어 실행(sudo)
12171정성태3/6/202011209VS.NET IDE: 143. Visual Studio - ASP.NET Core Web Application의 "Enable Docker Support" 옵션으로 달라지는 점 [1]
12170정성태3/6/20209809오류 유형: 599. "Docker Desktop is switching..." 메시지와 DockerDesktopVM CPU 소비 현상
12169정성태3/5/202011809개발 환경 구성: 473. Windows nanoserver에 대한 docker pull의 태그 사용 [1]
12168정성태3/5/202012505개발 환경 구성: 472. 윈도우 환경에서의 dockerd.exe("Docker Engine" 서비스)가 Linux의 것과 다른 점
12167정성태3/5/202011731개발 환경 구성: 471. C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (3) - ibmcom/db2express-c 컨테이너 사용
12166정성태3/4/202011359개발 환경 구성: 470. Windows Server 컨테이너 - DockerMsftProvider 모듈을 이용한 docker 설치
12165정성태3/2/202011026.NET Framework: 900. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 네 번째 이야기(Monitor.Enter 후킹)파일 다운로드1
12164정성태2/29/202011850오류 유형: 598. Surface Pro 6 - Windows Hello Face Software Device가 인식이 안 되는 문제
12163정성태2/27/202010328.NET Framework: 899. 익명 함수를 가리키는 delegate 필드에 대한 직렬화 문제
12162정성태2/26/202013166디버깅 기술: 166. C#에서 만든 COM 객체를 C/C++로 P/Invoke Interop 시 메모리 누수(Memory Leak) 발생 [6]파일 다운로드2
12161정성태2/26/20209777오류 유형: 597. manifest - The value "x64" of attribute "processorArchitecture" in element "assemblyIdentity" is invalid.
... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...