Microsoft MVP성태의 닷넷 이야기
.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2) [링크 복사], [링크+제목 복사],
조회: 14370
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
.NET Framework: 439. .NET CLR4 보안 모델 - 1. "Security Level 2"란?
; https://www.sysnet.pe.kr/2/0/1680

.NET Framework: 440. .NET CLR4 보안 모델 - 2. 샌드박스(Sandbox)을 이용한 보안
; https://www.sysnet.pe.kr/2/0/1681

.NET Framework: 441. .NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1682

오류 유형: 228. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가
; https://www.sysnet.pe.kr/2/0/1683

.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2)
; https://www.sysnet.pe.kr/2/0/10804

.NET Framework: 573. .NET CLR4 보안 모델 - 4. CLR4 보안 모델에서의 조건부 APTCA 역할
; https://www.sysnet.pe.kr/2/0/10947

.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
; https://www.sysnet.pe.kr/2/0/11041

닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
; https://www.sysnet.pe.kr/2/0/13565




.NET CLR2 보안 모델에서의 APTCA 역할 (2)

지난 글에서,

.NET CLR2 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1679

APTCA 역할을 설명했는데요. 간단히 말하면 "부분 신뢰를 받는 응용 프로그램"에게 "보안에 민감한 코드를 실행할 수 있는 방법"을 제공하는 것이 바로 APTCA입니다. 그럼, 어떻게 그것이 가능한지 한번 실습과 함께 살펴보겠습니다. ^^




우선, .NET Framework 2.0 대상으로 "빈 웹 프로젝트"를 하나 만들고 web.config에 다음과 같은 설정을 추가합니다.

<configuration>
    <!-- 생략 -->
  <system.web>
    <!-- 생략 -->
    <trust level="Medium"/>
  </system.web>
</configuration>

그럼 해당 웹 애플리케이션은 "부분 신뢰"만 받는 닷넷 응용 프로그램으로 동작합니다. (즉, 보안에 민감한 닷넷 코드를 실행할 수 없습니다.)

그런 다음, 역시 .NET Framework 2.0 대상으로 DLL 라이브러리 프로젝트(ClassLibrary1)를 하나 만들고 컴파일한 후 그 DLL 파일 경로를 이용해 직접 웹 응용 프로그램에서 로드하는 코드를 작성합니다.

using System;
using System.Reflection;

namespace WebApplication1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             Assembly asm = Assembly.LoadFile(@"E:\ClassLibrary1\bin\Debug\ClassLibrary1.dll");
        }
    }
}

이 상태에서 실행해 주면, Assembly.LoadFile 코드에서 예외가 발생합니다. 왜냐하면 부분 신뢰 응용 프로그램은 Assembly.LoadFile 메서드를 이용해 동적으로 외부 어셈블리를 로드할 수 없기 때문입니다. 스스로는 보안에 관한 어떠한 일도 할 수 없기 때문에, 만약 응용 프로그램이 필요한 범위내에서 보안관련 기능을 접근하고 싶다면 해당 코드를 DLL로 분리해서 반드시 GAC에 등록해야 합니다.

따라서 ClassLibrary1.dll을 강력한 이름으로 서명하고 gacutil.exe를 이용해 GAC에 등록한 후,

gacutil /i ClassLibrary1.dll

Assembly.Load 메서드를 이용해 다시 로드해보면,

using System;
using System.Reflection;

namespace WebApplication1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Assembly load = Assembly.Load("ClassLibrary1, Version=1.0.0.2, Culture=neutral, PublicKeyToken=07504c71c752bda2");
        }
    }
}

이제는 정상적으로 Assembly.Load에서 어셈블리를 로드하는 것을 확인할 수 있습니다. 자, 그럼 ClassLibrary1 프로젝트에 Class1.cs 파일을 추가하고 DoTest 메서드 하나만을 만들어 줍니다.

using System;
using System.Collections;

namespace ClassLibrary1
{
    public class Class1
    {
        public static void DoTest()
        {
            System.Diagnostics.Trace.WriteLine("DoTest Called");
        }
    }
}

그리고 웹 프로젝트에서는 Class1.DoTest 메서드를 Reflection을 이용해 호출하는 코드를 작성합니다.

using System;
using System.Reflection;

namespace WebApplication1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Assembly load = Assembly.Load("ClassLibrary1, Version=1.0.0.2, Culture=neutral, PublicKeyToken=07504c71c752bda2");

            Type type = load.GetType("ClassLibrary1.Class1");
            if (type != null)
            {
                MethodInfo mi = type.GetMethod("DoTest", BindingFlags.Public | BindingFlags.Static);
                if (mi != null)
                {
                    mi.Invoke(null, null);
                }
            }
        }
    }
}

GAC에 변경된 ClassLibrary1 어셈블리를 다시 등록해 주고 실행해 보면, 이번에는 mi.Invoke 호출에서 DoTest 메서드의 내용에 상관없이 다음과 같은 오류가 발생하는 것을 볼 수 있습니다.

Security Exception 
  Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. 

 Exception Details: System.Security.SecurityException: That assembly does not allow partially trusted callers.

Source Error: 

Line 22:                 if (mi != null)
Line 23:                 {
Line 24:                     mi.Invoke(null, null);
Line 25:                 }
Line 26:             }

 Source File:  c:\temp\WebApplication1\WebApplication1\default.aspx.cs    Line:  24 

Stack Trace: 

[SecurityException: That assembly does not allow partially trusted callers.]
   System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) +212
   System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags) +0
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +513
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +51
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +48
   WebApplication1._default.Page_Load(Object sender, EventArgs e) in e:\WebApplication1\default.aspx.cs:24
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +37
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +91
   System.Web.UI.Control.OnLoad(EventArgs e) +148
   System.Web.UI.Control.LoadRecursive() +122
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6488
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +320
   System.Web.UI.Page.ProcessRequest() +129
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +46
   System.Web.UI.Page.ProcessRequest(HttpContext context) +156
   ASP.default_aspx.ProcessRequest(HttpContext context) in App_Web_ceeysaib.0.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +867
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +120

즉, 부분 신뢰 응용 프로그램에서는 GAC 어셈블리를 로드할 수는 있지만 그것이 제공하는 코드는 실행할 수 없는 것입니다. 이것을 가능하게 하려면 APTC 특성을 ClassLibrary1 프로젝트에 적용해 주면 됩니다.

[assembly: AllowPartiallyTrustedCallers]

다시 ClassLibrary1 프로젝트를 빌드하고 GAC에 등록 후 "부분 신뢰 웹 응용 프로그램"을 실행하면 mi.Invoke 메서드가 호출되고 Class1.DoTest 메서드가 실행되는 것을 확인할 수 있습니다.




자... 그럼 이제 "부분 신뢰 응용 프로그램"에서 보안에 민감한 코드를 담은 메서드를 호출할 수 있게 되었으니 Class1.DoTest 메서드에 다음과 같이 코드를 추가한 후 (다시 GAC에 등록하고) 웹 응용 프로그램을 시작합니다.

public static void DoTest()
{
    System.Diagnostics.Trace.WriteLine("DoTest Called");

    CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
    if (codeProvider == null)
    {
        return;
    }
}

그런데, 이번에는 다음과 같은 예외가 발생합니다.

Server Error in '/' Application.

Security Exception 
  Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. 

 Exception Details: System.Security.SecurityException: Request failed.

Source Error: 

 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 

[SecurityException: Request failed.]
   System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags) +0
   System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +377
   System.Reflection.ConstructorInfo.Invoke(Object[] parameters) +45
   System.CodeDom.Compiler.CompilerInfo.CreateProvider() +222
   System.CodeDom.Compiler.CodeDomProvider.CreateProvider(String language) +56
   ClassLibrary1.Class1.DoTest() +44

이유는 간단합니다. 분명히 GAC에 등록된 어셈블리는 FullTrust 권한이 적용되지만 APTC 특성이 붙으면 기본적으로는 보안이 닫힌 채 코드가 실행됩니다. (원래 1.x 시절에는 GAC에 등록되어도 FullTrust가 아니었지만 2.0부터는 FullTrust로 바뀌었습니다. 참조: Does Being in the GAC Grant FullTrust?)

불편할 것 같지만 이것이 맞습니다. 해당 라이브러리 개발자가 "열어 줘야 할 코드"를 가장 잘 알고 있기 때문에 필요없는 부분까지 모두 "부분 신뢰 응용 프로그램"에게 호출되도록 할 필요는 없기 때문입니다.

그럼, 어떻게 원하는 코드 부분을 "열어 줄 수 있는 걸까요"?

GAC에 등록된 어셈블리는 FullTrust를 받고 있기 때문에 자신이 원하는 부분은 Assert 메서드를 이용해 해당 콜스택 이후에 대해서만 부분적으로 잠시 보안 기능을 열 수 있습니다. 따라서, Class1.DoTest 메서드에서 CodeDomProvider을 수행하기 전 그것이 필요로 하는 보안을 열어주면 됩니다.

그럼 어떤 권한을 열어줘야 하는 걸까요? 이는 CodeDomProvider 도움말을 가보면, (또는 .NET Reflector 등을 통해서 보면)

CodeDomProvider Class
; https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider

다음의 정의를 볼 수 있습니다.

[ComVisibleAttribute(true)]
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
public abstract class CodeDomProvider : Component

통크게... 일부 보안 기능만 요구하는 것이 아니고 "FullTrust"를 요구(LinkDemand)하고 있군요. ^^; 그래서 DoTest 메서드를 다음과 같이 변경해 주면 됩니다.

public static void DoTest()
{
    System.Diagnostics.Trace.WriteLine("DoTest Called");

    NamedPermissionSet ps = new NamedPermissionSet("FullTrust");
    ps.Assert();

    CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
    if (codeProvider == null)
    {
        return;
    }
}

그럼, Assert를 호출한 콜스택 이후로 누적되는 메서드에 대해서는 FullTrust 권한을 부여받아 코드를 실행하게 되므로 (다시 GAC에 등록하고 테스트를 해보면) 정상적으로 CodeDomProvider 코드가 동작합니다.




참고로, "Assert를 호출한 콜스택 이후"라는 의미가 중요합니다. 만약 해당 Assert 코드를 재사용하고 싶다고 해서 다음과 같은 식으로 별도 메서드로 분리해 호출하면,

using System.CodeDom.Compiler;
using System.Collections;
using System.Security;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {
        public static void DoTest()
        {
            System.Diagnostics.Trace.WriteLine("DoTest Called");

            AssertFullTrust();

            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            if (codeProvider == null)
            {
                return;
            }
        }

        private static void AssertFullTrust()
        {
            NamedPermissionSet ps = new NamedPermissionSet("FullTrust");
            ps.Assert();
        }
    }
}

CodeDomProvider.CreateProvider에서 오류가 발생합니다. 왜냐하면 AssertFullTrust 메서드 내에서 Assert가 되었고 그 메서드를 벗어나면서 콜스택은 DoTest로 한 단계 내려갔기 때문에 그 메서드는 여전히 부분 신뢰 권한만 갖고 있기 때문입니다. 따라서, 재사용하고 싶다면 다음과 같은 식으로 호출해야 합니다.

using System.CodeDom.Compiler;
using System.Collections;
using System.Security;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {
        public static void DoTest()
        {
            System.Diagnostics.Trace.WriteLine("DoTest Called");

            AssertFullTrust().Assert();

            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            if (codeProvider == null)
            {
                return;
            }
        }

        private static NamedPermissionSet AssertFullTrust()
        {
            NamedPermissionSet ps = new NamedPermissionSet("FullTrust");
            return ps;
        }
    }
}




이로써 .NET 2.0 CLR 보안 모델의 Assert와 LinkDemand관계도 이해하셨을 것이고 어떻게 APTCA 어셈블리에 적용되는지 알게 되었습니다.

여기까지 이해하셨으면 새롭게 변경된 .NET CLR 4 보안 모델도 별반 다르지 않음을 알 수 있습니다.

.NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1682

결국 2가지 보안 모델 모두 보안에 민감한 코드를 개발자가 선택해서 노출할 수 있는 권한(과 책임)을 주는 것입니다. 단지 CLR 4의 보안 모델이 좀 더 쉬운 방법을 제공하는 정도의 차이일 뿐!

(첨부 파일은 위의 2가지 프로젝트를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 2/23/2024]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13362정성태6/1/20233400.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233826오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233200오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233508오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233856.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233651.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233977DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233909.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234148.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233769.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234282VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233547오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233859.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233771.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234193.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234033오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235426.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236569.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234459디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234365.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234056닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234162오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234954닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234347닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234862Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234686.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...