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)
13399정성태8/9/20233633닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234527스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20234064닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233819스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233626개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233589오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233878닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233746오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233811닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233630스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233678개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233912오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233967오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20234089Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20234279Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233987.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233739개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233779.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20234197오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233593스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233629스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233518오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237430오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233797.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233463스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233593오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...