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)
13450정성태11/21/20232665닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232809개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20233074닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20233040닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232961닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20233225Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232984닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232893개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232663개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20233102닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232655Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20233306닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232910닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20233063닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233279닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233212닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20233025스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232612스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232818오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20233207스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20233011닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233212닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233375닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233563닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233660스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233438닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...