Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 8개 있습니다.)

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...
NoWriterDateCnt.TitleFile(s)
12904정성태1/8/20228699개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227290.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227352오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227386오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20229068개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228569개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20229142.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20228013.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210858.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219331.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
12894정성태12/30/20217279.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20218856.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/20216843기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/20216783스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/20216936VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/20219344.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/20217504.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/20219574오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/20217494스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/20217747오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20216804개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/20217653오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/20216762개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/20217267개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/20217054VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202113296오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...