Microsoft MVP성태의 닷넷 이야기
.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람 [링크 복사], [링크+제목 복사],
조회: 12181
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12338정성태9/21/20209292오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202010616오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202013135.NET Framework: 942. C# - WOL(Wake On Lan) 구현
12335정성태9/21/202022503Linux: 31. 우분투 20.04 초기 설정 - 고정 IP 및 SSH 설치
12334정성태9/21/20207908오류 유형: 652. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter"
12333정성태9/20/20208377.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
12332정성태9/18/202010434.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드파일 다운로드1
12331정성태9/18/20209579오류 유형: 651. repadmin /syncall - 0x80090322 The target principal name is incorrect.
12330정성태9/18/202010619.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 [2]파일 다운로드1
12329정성태9/16/202012524오류 유형: 650. ASUS 메인보드 관련 소프트웨어 설치 후 ArmouryCrate.UserSessionHelper.exe 프로세스 무한 종료 현상
12328정성태9/16/202012751VS.NET IDE: 150. TFS의 이력에서 "Get This Version"과 같은 기능을 Git으로 처리한다면?
12327정성태9/12/202010336.NET Framework: 938. C# - ICS(Internet Connection Sharing) 제어파일 다운로드1
12326정성태9/12/20209825개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/20209342개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202010604개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209480오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202010568개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/20208809오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/202010035개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/20209789오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/20209282오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
12317정성태9/9/202011621개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/202010033디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
12315정성태9/7/202012332개발 환경 구성: 510. Logstash - FileBeat을 이용한 IIS 로그 처리 [2]
12314정성태9/7/202010865오류 유형: 645. IIS HTTPERR - Timer_MinBytesPerSecond, Timer_ConnectionIdle 로그
12313정성태9/6/202012068개발 환경 구성: 509. Logstash - 사용자 정의 grok 패턴 추가를 이용한 IIS 로그 처리
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...