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)
13475정성태12/7/20232682닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232543개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232819닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232457C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232644Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232864닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232748닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232496닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232754오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232894닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232655개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232674닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232529오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232538오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232622닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232678닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232684닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232694닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232666VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232966닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232854닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20233211닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232634오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232707닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232847닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232662닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...