Microsoft MVP성태의 닷넷 이야기
.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2) [링크 복사], [링크+제목 복사],
조회: 14367
글쓴 사람
정성태 (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)
13515정성태1/6/20242620닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242306개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242223닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242176개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242197닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242120닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242169오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242219오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242865닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232454닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232982닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232571닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232441Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232555닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232321개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232413디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233100닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232494오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232484Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232415Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232583Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232712닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232383개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232267Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...