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)
13520정성태1/10/20242179오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242219닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242480닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242295스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242398닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242718닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242379개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242302닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242253개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242259닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242173닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242249오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242305오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242978닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232559닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20233127닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232692닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232579Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232634닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232384개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232516디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233186닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232591오류 유형: 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/20232676Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232620Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232717Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...