Microsoft MVP성태의 닷넷 이야기
.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2) [링크 복사], [링크+제목 복사],
조회: 14369
글쓴 사람
정성태 (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)
13565정성태2/23/20241691닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241939Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241959디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241988오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242071닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242113디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242946오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242189닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241923Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241980Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242130닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241864VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241949닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241900닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242095닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242210Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242515개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242340개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242108개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241975Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241877닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241894오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241923Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241920오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241980VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242113Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...