Microsoft MVP성태의 닷넷 이야기
.NET Framework: 439. .NET CLR4 보안 모델 - 1. "Security Level 2"란? [링크 복사], [링크+제목 복사],
조회: 14804
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)
(시리즈 글이 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 보안 모델 - 1. "Security Level 2"란?

.NET 3.5 SP1부터 이미 네트워크 공유로부터 실행되는 응용 프로그램의 권한이 Full Trust로 바뀌면서 사실 대부분의 닷넷 프로그래머들은 이로 인해 그동안 겪었던 숱한 보안 오류를 피할 수 있었습니다.

하지만, 마이크로소프트는 .NET 4부터 기존의 보안 모델을 업그레이드하는 작업을 합니다. (CAS가 없어진 것이 아니라 업그레이드입니다. 내부적으로 CAS는 여전히 살아 있습니다.) 이름하여 "Security Level 2" 모델입니다.

What's New in Code Access Security in .NET Framework 4.0 - Part I
; https://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-i/

What's New in Code Access Security in .NET Framework 4.0 - Part 2
; https://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-2/

"Security Level 2" 모델의 동작 방식은 굉장히 간단합니다. 코드는 SecurityTransparent, SecuritySafeCritical, SecurityCritical 이렇게 딱 3가지로 부류로만 나뉘고 그 사이에는 다음과 같은 호출 규칙이 있습니다.

  • SecurityTransparent 코드는 SecurityCritical을 제외하고 호출 가능
  • SecuritySafeCritical, SecurityCritical 코드는 모든 부류의 코드를 호출 가능

이를 간단히 정리하면 다음과 같은 한 가지 제약을 발견할 수 있습니다.

[출처: What's New in Code Access Security in .NET Framework 4.0 - Part I]
net4_sec_model_1.png

즉, SecurityCritical로 분류된 코드는 SecurityTransparent 측에서 호출하려면 반드시 그 중간에 SecuritySafeCritical에 해당하는 코드를 마련해 줘야 합니다.

원칙은 간단하지만, 이게 어떻게 보안과 관계있는지 감이 안 오는데요. 대략 어떤 것인지 테스트를 통해 체험해 보는 것이 좋겠지요. ^^

우선 라이브러리 프로젝트를 하나 만들고,

using System;

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

이를 사용하는 콘솔 프로젝트를 만듭니다. (물론 모두 .NET 4.0 대상으로 합니다.)

class Program
{
    static void Main(string[] args)
    {
        Class1 cl = new Class1();
        cl.DoMethod();
    }
}

실행하면 당연히 잘 되겠지요. ^^

자, 이제 현실적인 문제 상황을 가정합니다. 여러분이 만든 프로그램이 있고, 그 프로그램에 누구든지 만들 수 있는 Plug-in을 로드해서 사용하는 기능이 있다고 가정해 보겠습니다. .NET 2.0 시절에는 이런 상황에서 보안이 축소된 별도의 AppDomain을 만들고 그 안에서 plug-in을 로드해야 했습니다. 그런데, 이렇게 구현하다 보면 사실 문제가 많습니다. AppDomain간의 호출이므로 MarshalByRefObject 상속도 처리해야 하고 개별 개체의 Serialize 문제도 고려해야 합니다.

그런데, .NET 4.0부터는 이를 아주 간단하게 해결할 수 있습니다.

AppDomain 생성 과정없이 단지 plug-in을 로드하는 코드를 별도의 DLL에 만들고 그것에 SecurityTransparent 특성을 부여하기만 하면 됩니다. 실제로 어떻게 동작하는지 한번 테스트 해볼까요? 이를 위해 다음과 같이 3개의 프로젝트를 만들고,

  • HostApp (콘솔 프로젝트: 우리가 만드는 응용 프로그램)
  • LoadLib (라이브러리 프로젝트: 3rd-party 라이브러리를 로드해서 그 기능을 호출하는 클래스를 정의)
  • UntrustedLib (라이브러리 프로젝트: 3rd-party에서 제작한 라이브러리라고 가정)

HostApp의 소스 코드는 이렇게,

class Program
{
    static void Main(string[] args)
    {
        LoadManager lm = new LoadManager();
        lm.DoFunc();
    }
}

LoadLib는 이렇게,

using UntrustedLib;
using System.Security;

[assembly: SecurityTransparent]

public class LoadManager
{
    public void DoFunc()
    {
        PlugInExtension plugin = new PlugInExtension();
        plugin.NormalMethod();
    }
}

마지막으로 UntrustedLib 코드는 이렇게 합니다.

using System;
using System.IO;
using System.Security;

namespace UntrustedLib
{
    public class PlugInExtension
    {
        public void NormalMethod()
        {
            Console.WriteLine("NormalMethod");
        }
    }
}

물론, 현실적으로 보면 LoadLib 어셈블리가 UntrustedLib 어셈블리를 동적으로 Assembly.Load를 이용하는 것이 보통이겠지만 여기서는 (어차피 결과는 같으므로) 테스트를 간단히 하기 위해 직접 참조해서 사용하겠습니다.

위와 같이 구성하고 실행하면 다음과 같은 예외가 발생합니다.

Unhandled Exception: System.MethodAccessException: Attempt by security transparent method 'LoadManager.DoFunc()' to access security critical method 'UntrustedLib.PlugInExtension..ctor()' failed.
   at LoadManager.DoFunc() in d:\...\LoadLib\LoadManager.cs:line 9
   at Program.Main(String[] args) in d:\...\HostApp\Program.cs:line 7

오류 메시지의 의미는, DoFunc 메서드는 (그것이 정의된 어셈블리에 [assembly: SecurityTransparent] 특성을 정의했으므로) SecurityTransparent에 속하지만, 그 내부에서 사용하는 PlugInExtension은 SecurityCritical에 속하므로 호출할 수 없다는 것입니다.

PlugInExtension 타입이 정의된 UntrustedLib에는 [assembly: SecurityTransparent]를 설정하지 않았으므로 기본적으로 모든 타입의 코드가 SecurityCritical 부류에 속합니다.

이 문제를 해결하려면 어떻게 해야 할까요? PlugInExtension 타입에 SecuritySafeCritical을 적용하면 될까요?

using System;
using System.IO;
using System.Security;

namespace UntrustedLib
{
    [SecuritySafeCritical]
    public class PlugInExtension
    {
        [SecuritySafeCritical]
        public void NormalMethod()
        {
            Console.WriteLine("NormalMethod");
        }
    }
}

상식적으로 생각해 봅시다. Host 프로그램 측에서 보안을 적용하기 위해 SecurityTransparent가 적용된 LoadLib 어셈블리를 경유해 UntrustedLib 어셈블리를 사용하는데, UntrustedLib 스스로 SecurityCritical을 호출할 수 있는 상태로 만드는 것이 허용된다면 이것은 절대 보안이라고 부를 수 없습니다.

이런 경우, .NET 4.0 CLR은 UntrustedLib 어셈블리 내부에 적용된 "Security Level 2"의 모든 속성을 무시하고 무조건 SecurityCritical로 여깁니다.

따라서, PlugInExtension 타입을 정상적으로 사용하려면 그것이 정의된 UntrustedLib 어셈블리도 "[assembly: SecurityTransparent]" 특성이 정의되어야 합니다. 그럼 UntrustedLib 어셈블리에 정의된 모든 타입은 SecurityTransparent에 속하게 됩니다. 이렇게 변경하고 빌드를 한 후 실행하면 이제 정상적으로 NormalMethod 메서드가 호출됩니다.

이 상태에서 PlugInExtension 타입에 다음의 메서드를 추가해 볼까요?

using System;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;

[assembly: SecurityTransparent]

namespace UntrustedLib
{
    public class PlugInExtension
    {
        // ... 생략: NormalMethod

        public void AccessCritical()
        {
            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());
            }
        }
    }
}

이전에 설명한대로 "[assembly: SecurityTransparent]" 특성이 적용되었으므로 PlugInExtension 타입 및 그 내부에 구현된 모든 메서드들은 SecurityTransparent 부류에 속하므로 AccessCritical 메서드 역시 SecurityTransparent에 속합니다. 그리고 그 내부에서 호출되는 코드를 보니 2개의 메서드가 있습니다.

  • FileStream 생성자
  • FileStream.Handle 공용 속성의 get 메서드

FileStream 생성자를 .NET Reflector나 Visual Studio 2013의 F12(Go To Definition) 기능을 이용해 들어가 보면 우리가 사용한 생성자 정의를 볼 수 있습니다.

[SecuritySafeCritical]
public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, 0x1000, FileOptions.None, Path.GetFileName(path), false)
{
}

그렇군요. 우리가 호출한 FileStream 생성자는 SecuritySafeCritical에 속하므로 SecurityTransparent의 AccessCritical 메서드에서 정상적으로 호출할 수 있었습니다.

그다음, FileStream.Handle의 get 메서드 정의를 볼까요?

public virtual IntPtr Handle
{
    [SecurityCritical, SecurityPermission(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
    get { // ... }
}

오호... get_Handle 메서드는 SecurityTransparent측에서 호출이 불가능한 SecurityCritical에 속하는 군요. 그래서 이 상태에서 빌드하고 실행하면 Handle 속성을 접근하는 단계에서 보안 에러가 발생합니다.

System.MethodAccessException: Attempt by security transparent method 'UntrustedLib.PlugInExtension.AccessCritical()' to access security critical method 'System.IO.FileStream.get_Handle()' failed.
   at UntrustedLib.PlugInExtension.AccessCritical() in d:\...\UntrustedLib\PlugInExtension.cs:line 25

즉, UntrustedLib 어셈블리를 제공하는 3rd-party들은 plug-in 제작시 자신의 어셈블리에 "[assembly: SecurityTransparent]" 특성을 적용해야 하고, 이 때문에 그 스스로 내부에서 SecurityCritical에 속한, 보안에 민감한 메서드를 호출할 수 없는 것입니다.

결국, SecurityTransparent의 강제성으로 인해 그 이후로 호출되는 모든 어셈블리들이 보안에 위반하는 코드를 호출할 수 없다는 것이 보장됩니다.

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






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

[연관 글]






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

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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13241정성태2/3/20234002디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234165디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233845디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235958.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235640.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235171개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234764개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235870개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237243오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234945스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233954오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234317개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235321.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235455.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235124개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234806.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20234006개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234439Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234607오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234299개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234465Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234558오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234167Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20234081VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234696디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234954디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...