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)
13494정성태12/20/20232704Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232900닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232555개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232348Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232494개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232257개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232234오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232521개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232325개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232193오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232319개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232472닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233149닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232469개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232868개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232506개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232743닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232500닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232577닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232397개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232680닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232328C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232523Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232771닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232619닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232423닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...