Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
[TestApp.zip]    

(시리즈 글이 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 CLR4 보안 모델 - 2. 샌드박스(Sandbox)을 이용한 보안

지난 글에서 .NET 4부터 도입된 "Security Level 2" 모델의 SecurityTransparent, SecuritySafeCritical, SecurityCritical 호출 관계가 어떻게 되는지 살펴봤습니다. 또한 SecurityTransparent를 이용해 어떻게 외부 업체들에게 안전한 어셈블리를 강제할 수 있는지 설명했습니다.

그래도 여전히 별도의 AppDomain을 만들어 보안을 강제하는 것이 필요할 때가 있습니다.

가령, 지난번 글에서 SecurityTransparent 특성을 적용하는 방법에서는 3rd-party 업체들이 SecurityTransparent 특성을 정의하도록 소스코드를 변경해야 하는 어려움(?)이 따릅니다. SecurityTransparent를 적용하지 않으면 외부 업체에서 제공하는 모든 코드들이 SecurityCritical로 분류되기 때문에 비록 내부적으로 보안에 위반하는 코드를 호출하지 않더라도 그에 상관없이 실행 자체가 안되는 사태가 발생합니다.

이 외에도, AppDomain을 이용하는 경우 보다 더 세밀한 보안 제어를 할 수 있다는 장점이 있습니다.

자, 그럼 직접 테스트를 한번 해볼까요? ^^

샌드박싱을 하는 전형적인 코드는 다음에 이미 공개되어 있으므로 이를 가져다 쓰도록 하겠습니다.

How to: Run Partially Trusted Code in a Sandbox
; https://learn.microsoft.com/en-us/dotnet/framework/misc/how-to-run-partially-trusted-code-in-a-sandbox

그래서 우리가 만드는 TestApp 호스트 측의 소스 코드는 다음과 같이 작성됩니다.

using System;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;
using System.Security;
using System.Security.Policy;

class Program
{
    static void Main(string[] args)
    {
        AppDomainSetup adSetup = new AppDomainSetup();
        adSetup.ApplicationBase = ".";

        Evidence ev = new Evidence();
        ev.AddHostEvidence(new Zone(SecurityZone.MyComputer));

        PermissionSet permSet = SecurityManager.GetStandardSandbox(ev);

        StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();
        AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

        ObjectHandle handle = Activator.CreateInstanceFrom(
            newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
            typeof(Sandboxer).FullName);
        
        Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

        string untrustedAssembly = typeof(Class1).Assembly.FullName;
        string untrustedClass = typeof(Class1).FullName;
        string entryPoint = "DoMethod";
        object [] parameters = null;

        newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters);

        entryPoint = "DoCriticalMethod";
        newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters);

        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("any key to exit ...");
        Console.ReadLine();
    }
}

class Sandboxer : MarshalByRefObject
{
    public void ExecuteUntrustedCode(string assemblyName, string typeName, string entryPoint, Object[] parameters)
    {
        MethodInfo target = Assembly.Load(assemblyName).GetType(typeName).GetMethod(entryPoint);

        try
        {
            target.Invoke(null, parameters);
        }
        catch (Exception ex)
        {
            Console.WriteLine("SecurityException caught:\n{0}", ex.ToString());
        }
    }
}

그렇습니다. 샌드박싱은 별도의 AppDomain 기능을 이용하기 때문에 MarshalByRefObject의 도움이 필요합니다.

여기서는 일단 테스트 결과를 비교할 수 있도록 보안 셋을 완전 신뢰(Full Trust)가 되는 SecurityZone.MyComputer를 기반으로 구성해 보았습니다. 즉, 전혀 보안이 되지 않는 Full Trust 샌드박스를 구현합니다.

다음은 호스트 측에서 로드할 외부 업체의 add-on이 될 TestLib 라이브러리 코드입니다.

using System;
using System.IO;

public class Class1
{
    public static void DoMethod()
    {
        Console.WriteLine("DoMethod called!");
    }

    public static void DoCriticalMethod()
    {
        try
        {
            using (FileStream file = new FileStream(@".\test.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                Console.WriteLine(file.Handle.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

이렇게 작성하고 실행하면, 당연히 정상적으로 DoMethod와 DoCriticalMethod가 잘 실행됩니다. 왜냐하면 샌드박싱을 제공하는 AppDomain의 보안 셋이 .NET 2.0 CAS 모델의 MyComputer Zone이기 때문입니다.

자, 그럼 보안을 제한하기 위해 "Partial Trust" 수준의 샌드박싱이 될 AppDomain을 만들기 위해 호스트 측의 코드를 다음과 같이 수정합니다.

ev.AddHostEvidence(new Zone(SecurityZone.Intranet));

CAS 모델의 Intranet Zone에 해당하는 보안 셋만 허용하므로 이제 AppDomain의 보안 수준은 "Partial Trust"가 됩니다. 이 상태에서 실행해 보면 DoCriticalMethod 실행 단계에서 다음과 같은 오류가 발생합니다.

System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,FileShare share)
   at Class1.DoCriticalMethod()
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.FileIOPermission
The Zone of the assembly that failed was:
MyComputer

제가 전에 샌드박싱을 구현한 AppDomain에서는 보다 더 세밀한 보안 제어가 가능하다고 했지요? ^^ 바로 이 결과가 그 증거입니다. 즉, 우리가 현재 만든 Intranet 수준의 샌드박스에서는 파일 접근 조차 허용되지 않게 보안을 제어한 것입니다. 이 상태에서 파일 제어를 허용하고 싶다면 다음과 같이 보안 셋을 추가해 주면 됩니다.

using System.Security.Policy;

// ... 생략...

PermissionSet permSet = SecurityManager.GetStandardSandbox(ev);
permSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

이제 빌드하고 실행하면 오류 메시지는 다음과 같이 바뀝니다.

System.MethodAccessException: Attempt by security transparent method 'Class1.DoCriticalMethod()' to access security critical method 'System.IO.FileStream.get_Handle()' failed.

Assembly 'TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=feef41772217d3e6' is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself.  In order to access security critical code, this assembly must be fully trusted.
   at Class1.DoCriticalMethod()

이것은 전에 ".NET CLR4 보안 모델 - 1. "Security Level 2"란?"글에서 설명한 상황과 같습니다.

즉, partial trust에서 로드되는 모든 타입 및 그 코드들은 무조건 SecurityTransparent로 분류됩니다. 다시 말하면 해당 어셈블리에 "[assembly: SecurityTransparent]" 속성이 지정된 것이나 다름없는 상태가 되는 것입니다.

이 때문에 샌드박싱된 AppDomain에서 실행되는 모든 외부 업체들의 DLL들은 보안에 민감한 작업을 함부로 할 수 없게 되는 것입니다.

(첨부된 파일은 위의 코드를 테스트한 프로젝트입니다.)




참고로, CLR4 응용 프로그램에서 기존의 CLR2 기반의 보안 모델로 돌아가고 싶은 경우 app.config에 다음의 설정을 해주면 됩니다.

<NetFx40_LegacySecurityPolicy> Element
; https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element

<configuration>
   <runtime>
      <NetFx40_LegacySecurityPolicy enabled="true"/>
   </runtime>
</configuration>

하지만, 위의 설정은 EXE 측에서나 가능하므로 라이브러리 업체 측에서 DLL에 대한 보안 권한을 CLR2로 내리기 위해서는 다음의 설정을 포함시키면 됩니다.

[assembly: SecurityRules(SecurityRuleSet.Level1)]

당연한 이야기겠지만, 위의 옵션들은 미처 .NET 4 보안에 대비하지 못해 문제가 발생한 경우 급하게 땜방으로 처리하는 용도로 생각하시고, 장기적인 관점에서 CLR4 보안 모델에 맞게 변경하는 것이 권장됩니다. (실은, 제니퍼 닷넷 제품도 ^^ 초기에 잠시 SecurityRuleSet.Level1로 설정했지만 이제는 CLR4 보안에 맞게 변경되었습니다.)




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







[최초 등록일: ]
[최종 수정일: 2/15/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-08-17 10시26분
[Lyn] 와.... 닷넷 너무어렵네요
[guest]
2014-08-18 12시09분
보안은 어디나 어려운 것 같습니다. ^^ (사실, 위의 닷넷 보안을 이해하고 있는 사람은 국내에서 손꼽지 않을까 싶습니다.)
정성태

1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13348정성태5/10/20234033.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234399.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234245오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235692.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236803.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234700디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234559.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234312닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234425오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20235227닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234608닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20235087Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234909.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234961.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234572Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20234064Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20234110Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20234072오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233763Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20234046Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233657VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20234034VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235555.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234774스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234603.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234557개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...