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




COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결

이전에 설명한 데로,

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

CoInitializeSecurity는 EXE 프로세스 전역에 걸쳐 단 한 번만 호출할 수 있습니다. 그런데 "CoInitializeSecurity를 제대로 부르고 싶으면 결국은 네이티브의 힘을 빌릴 수밖에 없는 걸까요?" 질문에서 나왔던 것처럼, LINQPAD나 PowerShell, WebBrowser 컨트롤을 호스팅하는 Windows Forms 등의 응용 프로그램에서는 내부적으로 CoInitializeSecurity를 (WSL Win32 API 호출에 부합하지 않는 옵션으로) 호출하기 때문에 이런 환경에서의 WslHub 패키지 사용을 방해하게 되는 문제가 있습니다.

간단한 테스트로, Windows Forms 응용 프로그램에 WebBrowser 컨트롤을 얹고 다음과 같이 Form1_Load 이벤트 코드를 작성하면,

using System;
using System.Windows.Forms;
using Wslhub.Sdk;

namespace WindowsFormsApp1
{
    // Install-Package Wslhub.Sdk
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Navigate("https://forum.dotnetdev.kr");

            Wsl.InitializeSecurityModel();

            string distroName = Wsl.GetDefaultDistro().DistroName;
            MessageBox.Show(Wsl.RunWslCommand(distroName, "cat /etc/passwd"));
        }

    }
}

Wsl.InitializeSecurityModel() 호출에서 "System.Runtime.InteropServices.COMException (0x80010119): Cannot complete CoInitializeSecurity." 예외가 발생합니다. 또는 Wsl.InitializeSecurityModel 호출을 제거하고 Wsl 관련 메서드를 호출하면 자격 증명을 전달할 수 없어 오동작을 하게 됩니다. (아마도 svchost.exe의 Local SYSTEM 계정에 해당하는 환경으로 WSL Win32 API들이 실행될 것입니다.)




이 제약을 벗어나기 위해 WslHub 저작자는 Local Server 형식의 COM 개체를 선택했습니다.

C#으로만 만든 Out-of-process 타입의 COM 서버
; https://forum.dotnetdev.kr/t/c-out-of-process-com/1072

wslhub/wsl-sdk-com
; https://github.com/wslhub/wsl-sdk-com

물론, 저 방법도 좋은 선택인데 ^^ 다양성을 위해 이번에는 COM+로 이를 해결하는 방법을 설명해 보겠습니다. 사실 COM+의 서버 유형 프로그램이 바로 이런 용도로 사용할 수 있기도 합니다.

Client-Side Requirements for Impersonation
; https://learn.microsoft.com/en-us/windows/win32/cossdk/client-side-requirements-for-impersonation

COM+ applications can always act as clients, of course. When the COM+ application makes a call to another application or resource, it expresses an impersonation level. For COM+ server applications, you can set an impersonation level administratively. COM+ library applications cannot set their own impersonation level; they use that of the host process instead. To learn how to set impersonation for a COM+ application, see Setting an Impersonation Level.


실제로 한 번 해볼까요? ^^

간단하게 COM+를 위한 DLL 프로젝트를 하나 만들고 WslHub.Sdk를 호스팅하기 위한 COM 타입을 이렇게 정의합니다.

// Install-Package Wslhub.Sdk

namespace WslProxy
{
    [System.Runtime.InteropServices.Guid("41AC8568-9230-4E63-B7C5-CAAD997EE207")]
    public class WslServiceProxy : ServicedComponent
    {
        public WslServiceProxy()
        {
        }    

        public bool IsDistroRegistered(string distroName)
        {
            return NativeMethods.WslIsDistributionRegistered(distroName);
        }

        public DistroRegistryInfo GetDefaultDistro()
        {
            return Wsl.GetDefaultDistro();
        }

        public string[] GetDistroList()
        {
            return Wsl.GetDistroListFromRegistry().Select(x => x.DistroName).ToArray();
        }

        public string RunWslCommand(string distroName, string commandLine)
        {
            return Wsl.RunWslCommand(distroName, commandLine);
        }
    }
}

그런 다음, 이에 대해 COM+ 서버 응용 프로그램으로 등록하라고 assembly 수준의 특성을 추가해,

[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationAccessControl(false)]
[assembly: ApplicationName("WslProxy")]
[assembly: ComVisible(true)]

regsvcs를 이용해 등록해 주면,

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe" WslProxy.dll

이후, WslProxy.dll을 다른 프로젝트에서 참조해 사용하면 됩니다. 가령, 위의 문제가 되었던 (WebBrowser 컨트롤을 포함한) Windows Forms 예제에서도 다음과 같이 사용할 수 있습니다.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Navigate("https://forum.dotnetdev.kr");

            try
            {
                Guid guid = new Guid("{41AC8568-9230-4E63-B7C5-CAAD997EE207}");
                Type type = Type.GetTypeFromCLSID(guid);
                ActivateInstance(type);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private static void ActivateInstance(Type type)
        {
            object comObject = Activator.CreateInstance(type);

            WslProxy.WslServiceProxy wsl = comObject as WslProxy.WslServiceProxy;

            foreach (string text in wsl.GetDistroList())
            {
                Console.WriteLine(text);
            }

            string distroName = wsl.GetDefaultDistro().DistroName;
            MessageBox.Show(wsl.RunWslCommand(distroName, "cat /etc/passwd"));
        }
    }
}

그런데, 아직은 위의 코드를 수행하면 다음과 같은 예외가 발생합니다.

System.Runtime.Serialization.SerializationException: Type 'WslSdk.DistroRegistryInfo' in Assembly 'WslProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=465ff3ec4fc809d7' is not marked as serializable.
   at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
   at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
   at System.EnterpriseServices.ComponentSerializer.MarshalToBuffer(Object o, Int64& numBytes)
   at System.EnterpriseServices.ComponentServices.ConvertToString(IMessage reqMsg)
   at System.EnterpriseServices.ServicedComponent.RemoteDispatchHelper(String s, Boolean& failed)
   at System.EnterpriseServices.ServicedComponent.System.EnterpriseServices.IRemoteDispatch.RemoteDispatchNotAutoDone(String s)
   at System.EnterpriseServices.IRemoteDispatch.RemoteDispatchNotAutoDone(String s)
   at System.EnterpriseServices.RemoteServicedComponentProxy.Invoke(IMessage reqMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at WslProxy.WslServiceProxy.GetDefaultDistro()
   at WindowsFormsApp2.Form1.ActivateInstance(Type type)
   at WindowsFormsApp2.Form1.Form1_Load(Object sender, EventArgs e)

오류 메시지에 따라, DistroRegistryInfo 타입의 직렬화 문제가 발생한 것이므로 소스 코드에서 이를 추가해야 합니다.

[ComVisible(true)]
[Serializable]
public class DistroRegistryInfo
{
    // ...[생략]...
}

여기까지 변경해서 regsvcs.exe로 COM+ 개체를 등록하면 이제 어느 환경에서나 WSL 관련 Win32 API를 호출하는 데 아무런 문제가 없습니다.




COM+ 서버 유형에서 이런 작업이 가능한 데에는 Security 탭에 있는 "Impersonation Level"의 기본값으로 "Impersonate"가 지정돼 있기 때문입니다.

coinitsec_complus_1.png

바로 저 옵션이 COM+ DLL을 호스팅하는 dllhsot.exe의 기본 CoInitializeSecurity 호출에 대한 RpcImpLevel 값이 됩니다. 그렇다면, COM+ 서버 프로세스(dllhost.exe)는 어떤 계정으로 WSL 원격 프로세스(svchost.exe)에 impersonation을 시도할까요?

아쉽게도, 해당 COM+를 호출한 프로세스의 계정이 아닌, COM+ 서버의 Identity로 설정된 계정으로 된다는 작은 문제점이 있습니다.

coinitsec_complus_2.png

따라서, 프로세스를 다른 사용자 계정으로 테스트하면 여전히 윈도우에 로그온 된 사용자 계정의 문맥으로 WSL 결과를 반환하게 됩니다. 예를 들어, 다음과 같이 간단하게 (WslProxy COM+ 개체를 사용하는) ConsoleApp을 만들고,

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Guid guid = new Guid("{41AC8568-9230-4E63-B7C5-CAAD997EE207}");
                Type type = Type.GetTypeFromCLSID(guid);
                ActivateInstance(type);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }

        private static void ActivateInstance(Type type)
        {
            object comObject = Activator.CreateInstance(type);

            WslProxy.WslServiceProxy wsl = comObject as WslProxy.WslServiceProxy;

            foreach (string text in wsl.GetDistroList())
            {
                Console.WriteLine(text);
            }

            string distroName = wsl.GetDefaultDistro().DistroName;
            Console.WriteLine(adminCode.RunWslCommand(distroName, "cat /etc/passwd"));
        }
    }
}

psexec의 도움을 받아,

SYSTEM 권한으로 UI 프로그램 실행하는 방법
; https://www.sysnet.pe.kr/2/1/1153

SYSTEM 계정으로 응용 프로그램을 실행해도,

C:\temp> psexec -s -i C:\temp\ConsoleApp2.exe

여전히 현재 로그인한 사용자의 계정으로 등록된 WSL 정보를 가져오게 됩니다. 현실적으로, WSL 구성 요소가 Windows 10에 설치되고 단일 사용자가 로그인해 작업한다는 가정으로 이것이 큰 제약이 되지는 않겠지만, 약간 아쉬운 것은 사실입니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/30/2023]

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

비밀번호

댓글 작성자
 




... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11272정성태8/21/201724725VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201719155VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201730588.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201721387디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201720971디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201725071.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201724848.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201753111기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
11264정성태8/9/201723978오류 유형: 414. UWP app을 signtool.exe로 서명 시 0x8007000b 오류 발생
11263정성태8/9/201719452오류 유형: 413. The C# project "..." is targeting ".NETFramework, Version=v4.0", which is not installed on this machine. [3]
11262정성태8/5/201718189오류 유형: 412. windbg - SOS does not support the current target architecture. [3]
11261정성태8/4/201720759디버깅 기술: 91. windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법
11260정성태8/3/201718855.NET Framework: 670. C# - 실행 파일로부터 공개키를 추출하는 방법
11259정성태8/2/201718124.NET Framework: 669. 지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법
11258정성태8/1/201718883.NET Framework: 668. 지연 서명된 DLL과 서명된 DLL의 차이점파일 다운로드1
11257정성태7/31/201719111.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201720559디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201723153디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201719467개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201719711Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201718409오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201717049디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201720655디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718445오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201724886오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201719208오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...