Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (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 보안 모델에서의 개별 System.Security.Permissions 제어

요즘 같은 시기에 ^^ (.NET Framework 3.5 이하를 대상으로 한) CLR 2의 CAS 보안 모델에 대해 관심을 가지실 분은 거의 없겠지만 그래도 기록으로 남겨봅니다. 예전에도 한번 다루긴 했지만,

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

위의 글에서는 (만병통치약인) "FullTrust"에 대해 Assert를 시켰고, 이번에는 좀 더 작은 권한을 요구하는 사례로 다시 예제를 들겠습니다.




재현을 하면서 ^^ 실습해 볼까요? 우선 .NET Framework 3.5 Web Application 프로젝트 생성 후 web.config의 내용 중,

<?xml version="1.0" encoding="utf-8"?>

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

trust[@level] 값을 "Medium"으로 낮춘 다음, Default.aspx.cs에 다음과 같이 환경변수를 접근하는 코드를 추가하면,

using System;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string text = Environment.GetEnvironmentVariable("TEST_VALUE");
        }
    }
}

실행 시 이런 예외가 발생합니다.

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 for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Source Error:

Line 12:         protected void Page_Load(object sender, EventArgs e)
Line 13:         {
Line 14:             string text = Environment.GetEnvironmentVariable("TEST_VALUE");
Line 15:         }
Line 16:     }

Source File: C:\temp\WebApplication1\WebApplication1\Default.aspx.cs    Line: 14

Stack Trace:

[SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +54
   System.Environment.GetEnvironmentVariable(String variable) +135
   WebApplication1.Default.Page_Load(Object sender, EventArgs e) in C:\temp\WebApplication1\WebApplication1\Default.aspx.cs:14
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
   System.Web.UI.Control.OnLoad(EventArgs e) +132
   System.Web.UI.Control.LoadRecursive() +66
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +11174247
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +11173786
   System.Web.UI.Page.ProcessRequest() +91
   System.Web.UI.Page.ProcessRequest(HttpContext context) +240
   ASP.default_aspx.ProcessRequest(HttpContext context) in App_Web_obrtjrxc.0.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171

Version Information: Microsoft .NET Framework Version:2.0.50727.9174; ASP.NET Version:2.0.50727.9175

실제로 GetEnvironmentVariable 메서드 내부를 보면,

// Token: 0x06000A80 RID: 2688 RVA: 0x0001FEFC File Offset: 0x0001EEFC
public static string GetEnvironmentVariable(string variable)
{
    if (variable == null)
    {
        throw new ArgumentNullException("variable");
    }
    new EnvironmentPermission(EnvironmentPermissionAccess.Read, variable).Demand();
    StringBuilder stringBuilder = new StringBuilder(128);
    int i = Win32Native.GetEnvironmentVariable(variable, stringBuilder, stringBuilder.Capacity);
    if (i == 0 && Marshal.GetLastWin32Error() == 203)
    {
        return null;
    }
    while (i > stringBuilder.Capacity)
    {
        stringBuilder.Capacity = i;
        stringBuilder.Length = 0;
        i = Win32Native.GetEnvironmentVariable(variable, stringBuilder, stringBuilder.Capacity);
    }
    return stringBuilder.ToString();
}

EnvironmentPermissionAccess.Read 권한을 요청하고 있으며, ("FullTrust"가 아닌) Medium 신뢰 단계에서는 저 작업이 허용되지 않기 때문에 보안 예외가 발생하는 것입니다.




신뢰할 수 없는 응용 프로그램에서 이 동작이 가능하려면, GetEnvironmentVariable을 호출하는 코드를 별도 DLL로 분리하고,

using System;

namespace ClassLibrary1
{
    public class Class1
    {
        public static string GetEnvValue(string key)
        {
            return Environment.GetEnvironmentVariable(key);
        }
    }
}

이것을 (관리자 권한으로) GAC에 등록해야 합니다.

c:\temp> gacutil /i ClassLibrary1.dll

여기까지 마치고 다시 실행해 보면, 여전히 오류는 발생하지만 예외 메시지가 약간 바뀝니다.

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: That assembly does not allow partially trusted callers.

왜냐하면, GAC에 등록되었다고 해서 신뢰할 수 없는 클라이언트에서조차 호출하게 두는 것은 보안상 위험할 수 있기 때문입니다. 그래서, "FullTrust"가 아닌 어셈블리들도 GAC에 있는 기능을 이용할 수 있는 별도의 표시를 해야 하는데요, 바로 APTCA 특성이 그것입니다.

[assembly: AllowPartiallyTrustedCallers]

위의 옵션을 부여하고, 다시 GAC에 설치한 다음 실행해 보면... ^^; 그래도 여전히 이런 오류가 발생합니다.

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 for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

마지막으로 이것을 만족할 수 있도록, (최소한) 메시지에서 명시한 EnvironmentPermission 권한만큼은 다음과 같이 명시적으로 열어주면 됩니다.

using System;
using System.Security;
using System.Security.Permissions;

[assembly: AllowPartiallyTrustedCallers]

namespace ClassLibrary1
{
    public class Class1
    {
        public static string GetEnvValue(string key)
        {
            // 이렇게 아예 모든 권한을 현시점의 call stack에서 허용할 수도 있지만,
            // NamedPermissionSet ps = new NamedPermissionSet("FullTrust");
            // ps.Assert();

            // 정확하게 필요한 권한만 허용하는 것도 가능
            new EnvironmentPermission(EnvironmentPermissionAccess.Read, key).Assert();
            return Environment.GetEnvironmentVariable(key);
        }
    }
}




위와 같은 3개에 걸친 보안 단계를 어찌 보면 과하다고도 볼 수 있는데요, 이것을 여러분들이 .NET Framework의 BCL 라이브러리를 개발하고 있는 입장에서 보면 이해를 더 쉽게 할 수 있습니다.

예를 들어, 여러분이 (System.Object 타입을 정의한, 즉, 가장 기본적인) mscorlib.dll을 개발하고 있다고 가정해 보겠습니다. mscorlib.dll을 비롯해 사용자가 만든 수많은 DLL들이 GAC에 등록돼 있을 것입니다. 물론 마이크로소프트가 만든 DLL은 보안에 세심한 주의를 기울였겠지만, 3rd-party 업체 등에서 만든 DLL들은 그렇지 않을 수도 있습니다.

그런데, 신뢰할 수 없는 응용 프로그램들이, 즉 trust[@level] 값을 "Medium"으로 낮춘 닷넷 응용 프로그램이 GAC에 있는 어셈블리의 모든 기능을 사용할 수 있게 만들면 자칫 심각한 보안 결함에 노출될 수 있습니다. 이것을 방지하기 위해, 세심하게 보안에 신경 썼다는 의미로 GAC 어셈블리에 APTCA 특성을 명시하도록 합니다. APTCA 특성은 기본적으로 정의가 안 돼 있기 때문에, 사용자가 무심코 만든 DLL은 GAC에 등록되었어도 신뢰 등급이 낮은 응용 프로그램에서 그것을 로드할 수 없습니다.

mscorlib.dll은 너무나 기본적인 어셈블리이기 때문에, 신뢰 등급이 낮은 응용 프로그램들도 사용해야 하므로 당연히 APTCA 특성을 명시하고 있습니다.

그렇다면, 이것 나름대로 또 문제입니다. 왜냐하면 mscorlib.dll에는 시스템을 접근하는 대부분의 코드들이 제공되기 때문에 이대로는 신뢰 등급이 낮은 응용 프로그램이 시스템을 (물론, Win32 보안에 걸리지 않는 범위 내에서) 접근할 수 있습ㄴ다.

예를 들어, mscorlib.dll에 구현한 코드 중, 신뢰 등급이 낮은 응용 프로그램에게는 "환경 변수"를 읽고 쓰는 것에 제약을 두고 싶을 수 있습니다. 바로 이런 요구 사항을 충족시키는 것이, System.Environment.GetEnvironmentVariable 메서드 내의 "new EnvironmentPermission(EnvironmentPermissionAccess.Read, variable).Demand();" 코드입니다.

CAS에서 미리 정의된 보안에는 trust[@level]이 "FullTrust"가 아닌 경우에는 환경변수를 접근할 수 없다는 규칙을 만들어 두었기 때문에 저 코드로 인해 신뢰 등급이 낮은 응용 프로그램, 예를 들어 인터넷에서 다운로드해 실행하는 프로그램은 mscorlib.dll을 경유해 환경변수를 접근할 수 없는 것입니다. 만약, 그것을 원한다면 이 글의 본문에서 만든 것처럼 "중계 DLL"을 만들어 제공해야 합니다. 그리고, 그 "중계 DLL"은 반드시 GAC에 등록돼 있어야만 "FullTrust"의 권한을 가질 수 있어 mscorlib.dll의 "new EnvironmentPermission(EnvironmentPermissionAccess.Read, variable).Demand();" 보안을 넘을 수 있습니다.

"GAC에 등록"해야 한다는 것은, 달리 말해 "관리자 권한"이 있어야 하는 것을 의미합니다. 따라서, 인터넷에서 다운로드한 프로그램은 "관리자 권한"이 없기 때문에 GAC에 임의로 DLL을 등록할 수 없으므로 원천적으로 CAS가 정의한 보안 범위에 따라 사용자 PC의 "환경변수"를 마음대로 접근할 수 없는 것입니다.

어떠세요? 나름 꽤나 신경 쓴 보안 모델인데요, 복잡하다는 이유로 인해 .NET Core로 오면서 CAS 보안 모델은 완전히 배제되었습니다. 안 그래도 운영체제의 보안 모델만으로도 충분히 복잡한 상태니까요!!! ^^




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







[최초 등록일: ]
[최종 수정일: 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)
13367정성태6/10/20233694오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233448.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233158오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233994.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233578스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233549.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233887오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233241오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233567오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233978.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233811.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20234147DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20234086.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234250.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233900.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234397VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233665오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20234000.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233899.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234309.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234145오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235571.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236677.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234610디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234455.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234202닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...