Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)
(시리즈 글이 5개 있습니다.)
.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약
; https://www.sysnet.pe.kr/2/0/12665

.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출
; https://www.sysnet.pe.kr/2/0/12666

.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결
; https://www.sysnet.pe.kr/2/0/12667

.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제
; https://www.sysnet.pe.kr/2/0/12670

COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법
; https://www.sysnet.pe.kr/2/0/12679




Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약

남정현 님이 nuget에 공개한 Wslhub.Sdk 패키지는,

Wslhub.Sdk
; https://www.nuget.org/packages/Wslhub.Sdk/

Windows 10에 설치된 WSL의 다양한 기능을 래핑해 아래와 같이 사용법을 제공합니다.

using Wslhub.Sdk;

// Place the code Wsl.InitializeSecurityModel() at the top of your application's Main() method.
Wsl.InitializeSecurity();

// Assert WSL installation status
Wsl.AssertWslSupported();

// Enumerate distro list
var distros = Wsl.GetDistroListFromRegistry();

// Query distro informations
var queryResults = Wsl.GetDistroQueryResult();

// Run a command
var result = Wsl.RunWslCommand(distroName, "cat /etc/passwd");

// Run a command with default distro
var defaultDistro = Wsl.GetDefaultDistro();
var result = defaultDistro.RunWslCommand("cat /etc/passwd");
Stream Redirection
using var outputStream = new MemoryStream();

var defaultDistro = Wsl.GetDefaultDistro();
defaultDistro.RunWslCommand("ls /dev | gzip -", outputStream);

outputStream.Seek(0L, SeekOrigin.Begin);
using var gzStream = new GZipStream(outputStream, CompressionMode.Decompress, true);
using var streamReader = new StreamReader(gzStream, new UTF8Encoding(false), false);
var content = streamReader.ReadToEnd();

Console.Out.WriteLine(content);

이 중에서 Wsl.InitializeSecurity() 메서드는,

wsl-sdk-dotnet/src/Wslhub.Sdk/Wsl.cs /
; https://github.com/wslhub/wsl-sdk-dotnet/blob/main/src/Wslhub.Sdk/Wsl.cs#L19

public static void InitializeSecurityModel()
{
    var result = NativeMethods.CoInitializeSecurity(
        IntPtr.Zero, // [in, optional] PSECURITY_DESCRIPTOR pSecDesc
        (-1),
        IntPtr.Zero,
        IntPtr.Zero,
        NativeMethods.RpcAuthnLevel.Default,
        NativeMethods.RpcImpLevel.Impersonate,
        IntPtr.Zero,
        NativeMethods.EoAuthnCap.StaticCloaking,
        IntPtr.Zero);

    if (result != 0)
        throw new COMException("Cannot complete CoInitializeSecurity.", result);
}

CoInitializeSecurity Win32 API 함수를 호출하는데요, 엄밀히는 Console App 프로젝트에서 저걸 호출하지 않아도 WslHub 패키지는 잘 동작합니다.

var defaultDistro = Wsl.GetDefaultDistro();
var result = defaultDistro.RunWslCommand("cat /etc/passwd"); // 정상 동작

그런데 굳이 CoInitializeSecurity를 명시적으로 호출하는 이유는, 이것의 적용이 Process(EXE) 전역적으로 단 한 번의 호출만 허용된다는 특징을 가지기 때문입니다. 이에 대해서는 이미 아래의 논의에서 나왔는데요,

CoInitializeSecurity를 제대로 부르고 싶으면 결국은 네이티브의 힘을 빌릴 수밖에 없는 걸까요?
; https://forum.dotnetdev.kr/t/coinitializesecurity/1002

간단하게 예를 들어, Console App 프로젝트를 만들어 2번 연속 호출해 보면,

using System;
using WslSdk.Interop;

// Install-Package Wslhub.Sdk
class Program
{
    static void Main(string[] args)
    {
        var result = NativeMethods.CoInitializeSecurity(
            IntPtr.Zero,
            (-1),
            IntPtr.Zero,
            IntPtr.Zero,
            NativeMethods.RpcAuthnLevel.Default,
            NativeMethods.RpcImpLevel.Impersonate,
            IntPtr.Zero,
            NativeMethods.EoAuthnCap.StaticCloaking,
            IntPtr.Zero);

        Console.WriteLine(result);

        result = NativeMethods.CoInitializeSecurity(
            IntPtr.Zero,
            (-1),
            IntPtr.Zero,
            IntPtr.Zero,
            NativeMethods.RpcAuthnLevel.Default,
            NativeMethods.RpcImpLevel.Impersonate,
            IntPtr.Zero,
            NativeMethods.EoAuthnCap.StaticCloaking,
            IntPtr.Zero);

        Console.WriteLine(result);
    }
}

/* 출력 결과
0
-2147417831
*/

처음 호출은 0(S_OK)을 반환하지만, 두 번째 호출은 0x80010119(-2147417831) 값으로 RPC_E_TOO_LATE - "Security must be initialized before any interfaces are marshalled or unmarshalled. It cannot be changed once initialized." 오류를 의미합니다.

따라서, 응용 프로그램 사용 중에 누군가 CoInitializeSecurity를 다른 옵션을 적용해 초기화하게 되면 이후의 WslHub 메서드들이 정상 동작하지 않을 수 있으므로 미리 WslHub의 요구 사항에 맞게 호출해 두는 것뿐입니다. (그렇다면, 반대로 다른 응용 프로그램들이 CoInitializeSecurity를 호출했을 때 의도했던 목적으로의 사용은 실패하게 될 것입니다.)




그런데, WSL Win32 API 호출과 CoInitializeSecurity가 무슨 관계가 있을까요?

이에 대해서도 "CoInitializeSecurity를 제대로 부르고 싶으면 결국은 네이티브의 힘을 빌릴 수밖에 없는 걸까요?" 질문에서 설명이 나옵니다.

즉, WSL의 기능들은 내부적으로 (svchost.exe로 호스팅 중인) lxssmanager.dll에서 제공하는 CLSID_LxssUserSession/IID_ILxssSession COM 개체를 통해 노출이 되는데, WSL Win32 API 함수들은 그 COM 개체 사용을 래퍼하는 층에 불과합니다. (확인하지는 않았습니다. ^^)

결국 여러분의 프로세스에서 호출하는 Win32 API는 svchost.exe로의 RPC 호출이 되고 이 과정에서 원격 호출을 위한 자격 전달의 기본 모드를 CoInitializeSecurity로 설정할 수 있었던 것입니다. 여기서 WSL API 사용과 관계해 중요한 것은 Impersonate 인자인데요,

var result = NativeMethods.CoInitializeSecurity(
    IntPtr.Zero,
    (-1),
    IntPtr.Zero,
    IntPtr.Zero,
    NativeMethods.RpcAuthnLevel.Default,
    NativeMethods.RpcImpLevel.Impersonate,
    IntPtr.Zero,
    NativeMethods.EoAuthnCap.StaticCloaking,
    IntPtr.Zero);

만약 이 값을 Identify나 Anonymous로 바꾸면 실행 시 다음과 같은 식의 오류가 발생합니다.

Unhandled Exception: System.Exception: Ubuntu20.04 is not registered distro.
   at Wslhub.Sdk.Wsl.RunWslCommand(String distroName, String commandLine, Int32 bufferLength)
   at WinFormInit.Program.Main(String[] args)

왜냐하면, 호출 측의 자격 증명(예를 들어 로컬 컴퓨터의 testusr 계정)이 서비스 측(svchost.exe)으로 전달되지 않기 때문에 서버는 현재 호출의 사용자 계정 문맥을 확인할 수 없고, 이는 "Ubuntu20.04"가 설치된 testusr 계정에 대한 정보를 알 수 없는 결과를 낳기에 저런 오류가 발생하게 됩니다.

정리하면, svchost.exe에서 실행하는 코드를 현재 우리가 실행 중인 프로그램(ConsoleApp1.exe)을 구동한 사용자 계정의 문맥으로 실행할 수 있어야 정상적인 WSL Win32 API들이 동작할 수 있습니다. 그리고, 이를 위해서는 (기본값으로 Impersonate가 가능하기 때문에) CoInitializeSecurity 호출을 아예 하지 않거나, Impersonate가 가능한 모드로 CoInitializeSecurity를 호출해야 한다는 전제 조건이 필요합니다.

(첨부 파일은 이 글의 예제 프로젝트를 포함합니다.)




(업데이트: 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출)

참고로, "CoInitializeSecurity를 제대로 부르고 싶으면 결국은 네이티브의 힘을 빌릴 수밖에 없는 걸까요?" 글에서는 STAThread가 붙은 경우 CoInitializeSecurity가 모두 성공했다고 하지만 제가 테스트한 바에 따르면 달랐습니다. 즉, 다음의 코드를,

using System;
using WslSdk.Interop;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var result = NativeMethods.CoInitializeSecurity(
            IntPtr.Zero,
            (-1),
            IntPtr.Zero,
            IntPtr.Zero,
            NativeMethods.RpcAuthnLevel.None,
            NativeMethods.RpcImpLevel.Impersonate,
            IntPtr.Zero,
            NativeMethods.EoAuthnCap.StaticCloaking,
            IntPtr.Zero);

        Console.WriteLine(result);
    }
}

.NET Framework에서 실행하면 -2147417831(RPC_E_TOO_LATE) 값이 반환되고 .NET Core에서 실행하면 0이 반환됩니다.




C# - CoCreateInstance 관련 Inteop 오류 정리
; https://www.sysnet.pe.kr/2/0/12678

Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약
; https://www.sysnet.pe.kr/2/0/12665

별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출
; https://www.sysnet.pe.kr/2/0/12666

COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결
; https://www.sysnet.pe.kr/2/0/12667

ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법
; https://www.sysnet.pe.kr/2/0/12676

역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석
; https://www.sysnet.pe.kr/2/0/12677

C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작
; https://www.sysnet.pe.kr/2/0/12668

DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제
; https://www.sysnet.pe.kr/2/0/12670

CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법
; https://www.sysnet.pe.kr/2/0/12679




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/3/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
12106정성태1/8/202019576VC++: 136. C++ - OSR Driver Loader와 같은 Legacy 커널 드라이버 설치 프로그램 제작 [1]
12105정성태1/8/202018071디버깅 기술: 153. C# - PEB를 조작해 로드된 DLL을 숨기는 방법
12104정성태1/7/202019243DDK: 9. 커널 메모리를 읽고 쓰는 NT Legacy driver와 C# 클라이언트 프로그램 [4]
12103정성태1/7/202022345DDK: 8. Visual Studio 2019 + WDK Legacy Driver 제작- Hello World 예제 [1]파일 다운로드2
12102정성태1/6/202018737디버깅 기술: 152. User 권한(Ring 3)의 프로그램에서 _ETHREAD 주소(및 커널 메모리를 읽을 수 있다면 _EPROCESS 주소) 구하는 방법
12101정성태1/5/202018921.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/202016402.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202019228디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202018974.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/202017076디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201919815디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201921483VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201919211.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201918785.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201917639디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201919912디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201920014.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201918904디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201917890Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201918318디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201920759디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201918765오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201919222디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201922205Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201920506오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201922353개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...