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

비밀번호

댓글 작성자
 




... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13148정성태10/26/20225947오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20225024오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225876.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20226162오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20226068.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226570오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20225886도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20227190.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226508C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20226207.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227601.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225903.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226478.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226765.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225452오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225815Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225723스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20228517.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225399.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225703.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20228381C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226857Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227468.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227703.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20227491.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/20227854.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...