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)
13374정성태6/20/20233593오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234871오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233396개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233530개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233669개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233480개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233629개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233821오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233588.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233211오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20234081.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233654스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233654.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233981오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233341오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233645오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20234116.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233930.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20234257DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20234181.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234309.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20234016.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234488VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233788오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20234123.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20234029.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...