Microsoft MVP성태의 닷넷 이야기
.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람 [링크 복사], [링크+제목 복사],
조회: 12791
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)
(시리즈 글이 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/1338

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

위의 코드에서 걸리는 점이 있다면, 포인터에 대해 직접 offset 값을 취해 정보를 얻는다는 것입니다. 그런데 최근에 다음의 글을 읽게 되었는데,

Reversing Windows Internals (Part 1) - Digging Into Handles, Callbacks & ObjectTypes
; https://rayanfam.com/topics/reversing-windows-internals-part1/

저 글에서 소개한 소스 코드를 보면 정식적인 구조체를 이용해 해결하고 있습니다.

SinaKarvandi/Process-Magics
; https://github.com/SinaKarvandi/Process-Magics

Process-Magics/EnumAllHandles/EnumAllHandles/
; https://github.com/SinaKarvandi/Process-Magics/tree/master/EnumAllHandles/EnumAllHandles

이참에, 찾아 보니 그런대로 이미 구조체들이 공식 문서화된 것들이 있습니다. ^^

NtQueryObject function (winternl.h)
; https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryobject

PUBLIC_OBJECT_TYPE_INFORMATION structure (ntifs.h)
; https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-__public_object_type_information
typedef struct _PUBLIC_OBJECT_BASIC_INFORMATION {
    ULONG Attributes;
    ACCESS_MASK GrantedAccess;
    ULONG HandleCount;
    ULONG PointerCount;
    ULONG Reserved[10];    // reserved for internal use
 } PUBLIC_OBJECT_BASIC_INFORMATION, *PPUBLIC_OBJECT_BASIC_INFORMATION;

PUBLIC_OBJECT_TYPE_INFORMATION structure (ntifs.h)
; https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-__public_object_type_information
typedef struct __PUBLIC_OBJECT_TYPE_INFORMATION {
    UNICODE_STRING TypeName;
    ULONG Reserved [22];    // reserved for internal use
} PUBLIC_OBJECT_TYPE_INFORMATION, *PPUBLIC_OBJECT_TYPE_INFORMATION;

ObQueryNameString function - ntifs.h (include FltKernel.h, Ntifs.h)
; https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-obquerynamestring

typedef struct _OBJECT_NAME_INFORMATION {
  UNICODE_STRING Name;
} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;

한 가지 아쉬운 점은, NtQuerySystemInformation 함수를 통해 모든 핸들 정보를 구하는 SystemHandleInformation 관련 구조체는 (사실상 documented에 가깝지만 ^^;) 여전히 undocumented 상태라는 점입니다.




그런데, 이 코드를 실행해 보면 dropbox가 설치된 컴퓨터에서 다음의 코드를 실행 시 hang 현상이 발생합니다.

// GetHandleName 함수
while (NtQueryObject(*DUP_HANDLE, ObjectNameInformation, OBJECT_NAME, GuessSize, &RequiredSize) == STATUS_INFO_LENGTH_MISMATCH)

문제가 되는 핸들을 알아내 Process Explorer에서 살펴보면 항상 다음의 Handle에서 멈추는 것을 확인할 수 있는데,

Type: File
Name: \Device\NamedPipe\DropboxDataPipe

이 외에도 몇몇 Handle에서 멈춤 현상이 동일하게 발생합니다. 그때마다 "DropboxDataPipe"와 동일한 것은 해당 핸들의 "속성" 창으로 보안 정보를 보려고 했을 때,

handle_enum_1.png

The requested security information is either unavailable or can't be displayed.

위와 같이 조회가 안 되지만, 저렇게 보안 정보가 안 보이는 것이라고 해도 모든 핸들의 정보가 NtQueryObject에서 hang 현상이 발생하지는 않습니다. 예를 들어, "\Device\CNG"가 예외인 경우였습니다.

관련해서 검색해 보면,

MPC-HC causes a freeze
; https://github.com/erengy/taiga/issues/270

이런 글이 나오고 그런 현상을 예외로 걸러내기 위해 다음과 같은 조건을 포함하고 있습니다.

// https://github.com/tamentis/psutil/blob/master/psutil/arch/mswindows/process_handles.c

// Skip access codes that can cause NtDuplicateObject() or NtQueryObject()
// to hang
if (handle.GrantedAccess == 0x00100000 ||
    handle.GrantedAccess == 0x00120189 ||
    handle.GrantedAccess == 0x0012019f ||
    handle.GrantedAccess == 0x001a019f ||
    handle.GrantedAccess == 0x0012008D)
  continue;

// 또는,
// https://github.com/erengy/anisthesia/blob/master/src/win/open_files.cpp

if (!(access_mask & FILE_READ_DATA))
    return false;

// We further assume that media players do not have any kind of write access
// to video files:
if ((access_mask & FILE_APPEND_DATA) ||
    (access_mask & FILE_WRITE_EA) ||
    (access_mask & FILE_WRITE_ATTRIBUTES)) {
    return false;
}

문제는, 저게 요행히 맞을 수는 있어도 GrantedAccess/access_mask 값이 hang 현상과 직접적인 연관은 없다는 점입니다. 게다가 hang이 발생했던 "\Device\NamedPipe\DropboxDataPipe"의 경우 제 시스템에서는 GrantedAccess 값이 0x120089였고, 그와 동일한 GrantedAccess 값을 가지고 있던 다른 Handle(예, "\Device\DeviceApi")에 대해서는 NtQueryObject 조회가 정상적으로 실행되었습니다.

다른 글을 보면,

C# (CSharp) SYSTEM_HANDLE_INFORMATION Examples
; https://csharp.hotexamples.com/examples/-/SYSTEM_HANDLE_INFORMATION/-/php-system_handle_information-class-examples.html

이렇게도 비교하는데,

//skip special NamedPipe handle (this may cause hang up with NtQueryObject function)
if (targetHandleInfo.AccessMask.ToInt64() == 0x0012019F)
{
    return String.Empty;
}

그나마 주석에서 얻은 한 가지 힌트라면 "특별한 NamedPipe"라고 가정을 하지만 그렇다고 해서 크게 도움이 되지는 않습니다. 왜냐하면 AccessMark == 0x0012019F를 가진 핸들 중에서 그것이 "File"인지, "특별한 NamedPipe"인지 구별할 수 있는 방법이 없기 때문입니다.

반면, "Process Explorer"는 hang 현상 없이 정확히 해당 정보를 가져오는 걸로 봐서 아마도 Kernel driver 영역에서나 가능하지 않을까 예상해 봅니다. (혹시 User 모드에서 해당 방법을 아시는 분은 덧글 부탁드립니다. ^^)




그러니까... 이 문제는 우회적으로 피해 가야 합니다. 예를 들어 지난 글에서 설명한,

C# - (핸들을 이용하여) 모든 열린 파일을 열람
; https://www.sysnet.pe.kr/2/0/1338

코드에서는 이를 회피하기 위해 별도의 스레드에 작업을 맡긴 후 EventWaitHandle.WaitOne(timeout)을 호출하는 방식으로 해결하고 있습니다.

private static bool GetFileNameFromHandle(IntPtr handle, out string fileName, int wait)
{
    using (FileNameFromHandleState f = new FileNameFromHandleState(handle))
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(GetFileNameFromHandle), f);
        if (f.WaitOne(wait))
        {
            fileName = f.FileName;
            return f.RetValue;
        }
        else
        {
            fileName = string.Empty;
            return false;
        }
    }
}

심지어 ProcessHacker 소스 코드에서도,

processhacker/phlib/hndlinfo.c
; https://github.com/processhacker/processhacker/blob/master/phlib/hndlinfo.c

PhpGetObjectName에 보면, PhCallNtQueryObjectWithTimeout과 NtQueryObject를 섞어 쓰고 있습니다.




이렇게 해서 소스 코드를 "C# - (핸들을 이용하여) 모든 열린 파일을 열람" 글에서 사용했던 것에 비해 좀 더 개선을 했습니다.

DotNetSamples/WinForms/EnumHandles/
; https://github.com/stjeong/DotNetSamples/tree/master/WinForms/EnumHandles

그래서 새롭게 변경한 소스 코드를 활용하면 다음과 같은 식으로 원하는 프로세스의 핸들을 열람할 수 있습니다.

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

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

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

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

다음 화면은 Process Explorer의 출력 결과(왼쪽)와 첨부한 예제 프로젝트의 실행 결과를 보여줍니다.

handle_enum_2.png

속도는 Process Explorer보다 느리지만, 상황에 따라 쓸만할 것입니다. ^^




당연한 이야기겠지만, GetFileNameFromHandle에서 hang 현상을 피하기 위해 ThreadPool.QueueUserWorkItem을 사용함으로써 만약 저 기능을 계속해서 호출하면 "hang 현상에 걸린 스레드"가 지속적으로 누적될 수 있습니다. 다음은 Visual Studio의 디버그 모드로 해당 스레드들이 누적되어 있는 것을 보여줍니다.

handle_enum_3.png





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/22/2023]

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)
11226정성태6/19/201711232오류 유형: 401. Microsoft Edge를 실행했는데 입력 반응이 없는 경우
11225정성태6/19/201710403오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
11224정성태6/13/201712412.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201711080개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201714214오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201711358오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201715934.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201712625.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201715180개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201711139오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201713270오류 유형: 396. Activation context generation failed
11215정성태6/1/201713377오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201711570오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201715408오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201715474오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201714239오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201714592기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201755453Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201720825오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201721017Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201714653오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201714359.NET Framework: 658. C#의 tail call 구현은?
11204정성태5/22/201724297개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201713327오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201713534오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201716004오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
... 91  92  93  94  95  96  [97]  98  99  100  101  102  103  104  105  ...