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)
11249정성태7/12/201718473오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201724964오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201719277오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
11246정성태7/11/201718077VS.NET IDE: 118. Visual Studio - 다중 폴더에 포함된 파일들에 대한 "Copy to Output Directory"를 한 번에 설정하는 방법
11245정성태7/10/201723658개발 환경 구성: 321. Visual Studio Emulator for Android 소개 [2]
11244정성태7/10/201723206오류 유형: 407. Visual Studio에서 ASP.NET Core 실행할 때 dotnet.exe 프로세스의 -532462766 오류 발생 [1]
11243정성태7/10/201719899.NET Framework: 666. dotnet.exe - 윈도우 운영체제에서의 .NET Core 버전 찾기 규칙
11242정성태7/8/201720230제니퍼 .NET: 27. 제니퍼 닷넷 적용 사례 (7) - 노후된 스토리지 장비로 인한 웹 서비스 Hang (멈춤) 현상
11241정성태7/8/201718969오류 유형: 406. Xamarin 빌드 에러 XA5209, APT0000
11240정성태7/7/201721873.NET Framework: 665. ClickOnce를 웹 브라우저를 이용하지 않고 쿼리 문자열을 전달하면서 실행하는 방법 [3]파일 다운로드1
11239정성태7/6/201723384.NET Framework: 664. Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법 [5]파일 다운로드1
11238정성태7/6/201720885오류 유형: 405. NT 서비스 시작 시 "Error 1067: The process terminated unexpectedly." 오류 발생 [2]
11237정성태7/5/201722521.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법파일 다운로드1
11236정성태7/4/201725775.NET Framework: 662. C# - VHD/VHDX 가상 디스크를 마운트하지 않고 파일을 복사하는 방법파일 다운로드1
11235정성태6/29/201719935Math: 20. Matlab/Octave로 Gram-Schmidt 정규 직교 집합 구하는 방법
11234정성태6/29/201717290오류 유형: 404. SharePoint 2013 설치 과정에서 "The username is invalid The account must be a valid domain account" 오류 발생
11233정성태6/28/201717174오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201718158Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
11231정성태6/28/201718800디버깅 기술: 86. windbg의 mscordacwks DLL 로드 문제 - 세 번째 이야기 [1]
11230정성태6/28/201717948제니퍼 .NET: 26. 제니퍼 닷넷 적용 사례 (6) - 잦은 Recycle 문제
11229정성태6/27/201719174오류 유형: 402. Windows Server Backup 관리 콘솔이 없어진 경우
11228정성태6/26/201716709개발 환경 구성: 320. Visual Basic .NET 프로젝트에서 내장 Manifest 자원을 EXE 파일로부터 제거하는 방법파일 다운로드1
11227정성태6/19/201724441개발 환경 구성: 319. windbg에서 python 스크립트 실행하는 방법 - pykd [6]
11226정성태6/19/201716323오류 유형: 401. Microsoft Edge를 실행했는데 입력 반응이 없는 경우
11225정성태6/19/201715601오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
11224정성태6/13/201718097.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
... 106  [107]  108  109  110  111  112  113  114  115  116  117  118  119  120  ...