Microsoft MVP성태의 닷넷 이야기
.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2) [링크 복사], [링크+제목 복사],
조회: 14374
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13236정성태1/29/20235127개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234690개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235777개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237162오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234897스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233870오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234235개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235258.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235350.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235029개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234736.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233924개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234322Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234513오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234210개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234394Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234499오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234060Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20234002VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234616디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234855디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236489Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235970.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235463오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235224기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235244웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...