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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12309정성태9/3/202010092개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011336개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202012118오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202010309오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202011161Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/202010124개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010292개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202010215.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202010506오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/20209920.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202010843.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
12298정성태8/27/202010584오류 유형: 640. livekd - Could not resolve symbols for ntoskrnl.exe: MmPfnDatabase
12297정성태8/25/20209787개발 환경 구성: 503. SHA256 테스트 인증서 생성 방법
12296정성태8/24/202010205.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger파일 다운로드1
12295정성태8/24/20209653오류 유형: 639. Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket ,,,
12293정성태8/24/202010985Windows: 171. "Administered port exclusions" 설명
12292정성태8/20/202012277.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202011187오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
12290정성태8/11/202011855.NET Framework: 931. C# - IP 주소에 따른 국가별 위치 확인 [8]파일 다운로드1
12289정성태8/6/20209374개발 환경 구성: 502. Portainer에 윈도우 컨테이너를 등록하는 방법
12288정성태8/5/20209375오류 유형: 637. WCF - The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.
12287정성태8/5/20209842오류 유형: 636. C# - libdl.so를 DllImport로 연결 시 docker container 내에서 System.DllNotFoundException 예외 발생
12286정성태8/5/202010699개발 환경 구성: 501. .NET Core 용 container 이미지 만들 때 unzip이 필요한 경우
12285정성태8/4/202011101오류 유형: 635. 윈도우 10 업데이트 - 0xc1900209 [2]
12284정성태8/4/202010399디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
12283정성태8/3/202010900디버깅 기술: 168. windbg - 필터 드라이버 확인하는 확장 명령어(!fltkd) [2]
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...