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




CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가

부분 신뢰 유형의 .NET 4.0 응용 프로그램에서 SecurityCritical 메서드를 yield 구문과 함께 사용시 System.MethodAccessException 예외가 발생할 수 있습니다.

상황을 한번 재현해 볼까요? ^^

새로 예제를 만들 필요없이 다음의 글에 공개된 Net40Sec2.zip 예제에서 시작해 보겠습니다.

.NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1682

일단 다운로드 받은 파일을 실행시켜서 오류없이 잘 실행되는 것을 확인합니다.

그리고 나서, HostService 프로젝트의 SecurityService 클래스에 다음과 같이 문제 재현을 위한 작위적인 메서드를 하나 추가하겠습니다.

using System.Security;
using System.IO;
using System.Collections.Generic;

[assembly: AllowPartiallyTrustedCallers]

public class SecurityService
{
    // ... [생략: GetFileHandle] ...

    [SecuritySafeCritical]
    public static IEnumerable<long> GetList(FileStream fs)
    {
        yield return fs.Handle.ToInt64();
    }
}

코드에 대한 유용성은 무시하시고, 그냥 GetList 메서드가 yield return을 한다는 사실만 주목하시면 됩니다. 그다음 이 메서드를 UntrustedLib 프로젝트의 PlugInExtension 타입에서 (SecurityTransparent 권한의) AccessCritical 메서드에서 호출합니다.

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

[assembly: SecurityTransparent]

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

        public void AccessCritical()
        {
            try
            {
                using (FileStream file = new FileStream(@".\test.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    foreach (var item in SecurityService.GetList(file))
                    {
                        Console.WriteLine(item);
                    }

                    long fileHandle = SecurityService.GetFileHandle(file);
                    Console.WriteLine(fileHandle.ToString());
                }
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}

이렇게 변경하고 실행하면 다음과 같은 예외를 재현할 수 있습니다.

System.MethodAccessException: Attempt by security transparent method 'SecurityService+<GetList>d__0.MoveNext()' to access security critical method 'System.IO.FileStream.get_Handle()' failed.

Assembly 'HostService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2a9ed378705e40fd' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model.  Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.
   at SecurityService.<GetList>d__0.MoveNext() in d:\...\HostService\Class1.cs:line 20
   at UntrustedLib.PlugInExtension.AccessCritical() in d:\...\UntrustedLib\PlugInExtension.cs:line 22




왜 이런 예외가 발생할까요? 분명히 SecurityService.GetList 메서드에는 SecuritySafeCritical 특성을 부여했는데 그게 적용되지 않은 것입니다.

왜냐하면, yield return의 경우 C# 컴파일러에 의해 내부적으로 IEnumerable을 위한 타입이 정의되기 때문입니다. 이는 .NET Reflector를 통해 확인하면 쉽게 알 수 있습니다.

[CompilerGenerated]
private sealed class <GetList>d__0 : IEnumerable<long>, IEnumerable, IEnumerator<long>, IEnumerator, IDisposable
{
    // Fields
    private int <>1__state;
    private long <>2__current;
    public FileStream <>3__fs;
    private int <>l__initialThreadId;
    public FileStream fs;

    // Methods
    [DebuggerHidden]
    public <GetList>d__0(int <>1__state);
    private bool MoveNext();
    [DebuggerHidden]
    IEnumerator<long> IEnumerable<long>.GetEnumerator();
    [DebuggerHidden]
    IEnumerator IEnumerable.GetEnumerator();
    [DebuggerHidden]
    void IEnumerator.Reset();
    void IDisposable.Dispose();

    // Properties
    long IEnumerator<long>.Current { [DebuggerHidden] get; }
    object IEnumerator.Current { [DebuggerHidden] get; }
}

보시는 바와 같이 여기에 정의된 MoveNext는 SecuritySafeCritical 특성이 없기 때문에 SecurityTransparent로 평가되고, 그로 인해 보안 오류가 발생하는 것입니다.

어쩔 수 없습니다. 이 상황을 해결하려면 원론으로 돌아가서 IEnumerable을 직접 정의해야 합니다. 따라서 예제의 경우 다음과 같이 구현을 바꿉니다.

public static IEnumerable<long> GetList(FileStream fs)
{
    return new FileHandleEnumrable(fs);
}

private sealed class FileHandleEnumrable : IEnumerable<long>, IEnumerable, IEnumerator<long>, IEnumerator, IDisposable
{
    // Fields
    public FileStream _fs;
    public bool _first;

    public FileHandleEnumrable(FileStream fs)
    {
        _fs = fs;
        _first = true;
    }

    private bool MoveNext()
    {
        bool result = _first;
        _first = false;

        return result;
    }
    IEnumerator<long> IEnumerable<long>.GetEnumerator()
    {
        return this;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this;
    }

    bool IEnumerator.MoveNext()
    {
        return MoveNext();
    }

    void IEnumerator.Reset() { _first = true; }


    // Properties
    long IEnumerator<long>.Current
    {
        [SecuritySafeCritical]
        get { return _fs.Handle.ToInt64(); }
    }
        
    object IEnumerator.Current 
    {
        [SecuritySafeCritical]
        get { return _fs.Handle.ToInt64(); } 
    }

    public void Dispose() { }
}

보시는 바와 같이 원래의 GetList 메서드는 보안 속성을 제거해도 무방하고, 대신 내부적으로 IEnumerable/IEnumerator를 직접 구현한 클래스의 Current 속성에 직접 SecuritySafeCritical을 지정하는 것으로 해결했습니다.

물론, 이렇게 변경하고 실행하면 정상적으로 예외없이 동작합니다.

(첨부 파일은 위의 예제 코드를 포함하고 있습니다.)




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







[최초 등록일: ]
[최종 수정일: 6/28/2021]

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

비밀번호

댓글 작성자
 



2014-06-11 09시41분
[spowner] !_!
[guest]
2016-09-10 03시35분
CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
; http://www.sysnet.pe.kr/2/0/11041
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13610정성태4/28/2024232닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024257닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024457닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024647닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024792닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024858닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024890오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024970닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024987닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20241008닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241018닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024952닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024997닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20241005닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241122닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241075닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241099닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241095닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241234C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241210닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241091Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241197닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241557닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241403오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241634Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...