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)
12210정성태4/20/202012546.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202010586오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/20209996Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20209008스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011314오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208692스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208512스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010557오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013149개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010935오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011396VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209229오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202012008오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011133VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20209056오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010806.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202013078오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209796개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012242개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012601개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208714오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013566개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015890Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208523오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209628오류 유형: 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/202010339오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...