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)
13577정성태3/9/20242472닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241927닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20242108닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241997닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241889닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241916닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241971닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241908닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241823닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241948닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241905오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241971오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241838닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20242056Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20242015디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20242038오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242152닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242161디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20243021오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242263닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20242010Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20242073Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242401닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20242093VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20242147닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20242050닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...