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)
13468정성태12/1/20232423닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232593오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232744닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232512개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232599닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232491오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232479오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232559닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232537닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232533닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232545닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232465VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232805닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232690닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20233012닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232414오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232510닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232639닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232459닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232599개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232953닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232852닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232771닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20233092Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232802닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232832개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...