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)
13298정성태3/27/20234218Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234787Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20234168Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234406Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234573.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234583오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234770Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20235106.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234619.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233854Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233988Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20234135Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234612Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20234137Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234378Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233811오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20234127Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20234150Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234898개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234362오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234423개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20235139개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234794.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20235012.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234597.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234344.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...