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




.NET CLR4 보안 모델 - 4. CLR4 보안 모델에서의 조건부 APTCA 역할

지난 글까지 이해한 것을 전제로,

.NET CLR4 보안 모델 - 1. "Security Level 2"란?
; https://www.sysnet.pe.kr/2/0/1680

.NET CLR4 보안 모델 - 2. 샌드박스(Sandbox)을 이용한 보안
; https://www.sysnet.pe.kr/2/0/1681

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

.NET CLR4 보안 모델 - 4. CLR4 보안 모델에서의 조건부 APTCA 역할 
; https://www.sysnet.pe.kr/2/0/10947

이번에는 "조건부 APTCA"라는 것을 설명해 보겠습니다.

The Conditional APCTA
; https://www.simple-talk.com/dotnet/.net-framework/code-access-security-in-asp.net-4.0/

이게 뭐냐면??? 우리가 만든 APTCA 적용 DLL을 기본적으로는 로드되지 않도록 한다는 것입니다. 로드하려면 해당 DLL을 '알고 로드하겠다.'는 명시적인 설정을 해줘야 합니다.

테스트를 한번 해볼까요? ^^

".NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할" 글에 포함된 TestApp2.zip 예제를 이용해 볼텐데요.

예제 프로젝트는 3개의 프로젝트를 포함합니다.

TestApp - 샌드 박싱 환경을 만들고 TestLib를 호출

TestLib - 일반적인 DLL 라이브러리
          2개의 메서드(DoMethod, DoCriticalMethod)가 구현되어 있는데,
          DoCriticalMethod 메서드에서 HostService 라이브러리에 구현된 
          SecuritySafeCritical 특성의 GetFileHandle 메서드를 호출

HostService - APTCA가 적용된 DLL 라이브러리, SecuritySafeCritical 특성이 적용된 GetFileHandle 메서드를 제공

일단 빌드하고 실행해 보면 이전 글에서 설명한 대로 DoCriticalMethod 메서드 호출 시 다음과 같은 예외가 발생합니다.

System.MethodAccessException: Attempt by security transparent method 'SecurityService.GetFileHandle(System.IO.FileStream
)' to access security critical method 'System.IO.FileStream.get_Handle()' failed.

Assembly 'HostService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2a9ed378705e40fd' is partially trusted, which ca
uses the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself.
  In order to access security critical code, this assembly must be fully trusted.
   at SecurityService.GetFileHandle(FileStream fs)
   at Class1.DoCriticalMethod()

이유도 지난 글에서 설명했지만, 샌드 박싱 환경에서 GAC에 등록되지 않은 APTCA의 SecuritySafeCritical 류의 메서드를 호출했기 때문입니다. 따라서, 오류를 없애기 위해 GAC에 HostService.dll을 등록해 줍니다.

여기까지가, 지난 글에서 설명한 보안 모델인데 이제 "조건부 APTCA"가 뭔지 테스트를 해보겠습니다.

기존의 (GAC에 등록된) "APTCA" DLL을 "조건부 APTCA" DLL로 기존의 APTC 특성을 다음과 같이 바꿔주기만 하면 됩니다.

// [assembly: AllowPartiallyTrustedCallers]

[assembly: AllowPartiallyTrustedCallers(PartialTrustVisibilityLevel = PartialTrustVisibilityLevel.NotVisibleByDefault)]

이렇게 변경하고 HostService 프로젝트를 빌드한 후 다시 GAC에 등록하고 실행하면 이번엔 다음과 같은 예외가 발생합니다.

System.MethodAccessException: Attempt by security transparent method 'Class1.DoCriticalMethod()' to access security critical method 'SecurityService.GetFileHandle(System.IO.FileStream)' failed.

Assembly 'TestLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=feef41772217d3e6' is partially trusted, which causes the CLR to make it entirely security transparent regardless of any transparency annotations in the assembly itself. In order to access security critical code, this assembly must be fully trusted.

Assembly 'HostService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2a9ed378705e40fd' is a conditionally APTCA assembly which is not enabled in the current AppDomain. To enable this assembly to be used by partial trust or security transparent code, please add assembly name 'HostService, PublicKey=002400000...[생략]...10C273F71D42DC0651F96BA' to the the PartialTrustVisibleAssemblies list when creating the AppDomain. at Class1.DoCriticalMethod()


저렇게 상세한 오류가 남는 경우는 운이 좋은 편에 속하고, 어떨 때는 내부적으로 예외가 '씹히는 경우'라면 단순히 디버그 출력 창에서 다음과 같은 식의 메시지로만 확인이 가능합니다.

CLR:(C:\Windows\Microsoft.Net\assembly\GAC_MSIL\HostService\v4.0_4.0.0.0__2a9ed378705e40fd\HostService.dll) Rejecting code sharing because a dependent assembly did not match the conditional APTCA share mode


오류 메시지의 의미는 간단합니다. HostService 어셈블리가 "conditionally APTCA"로 지정되었기 때문에 이 어셈블리를 로드하려면 명시적으로 이를 허락하겠다는 표시를 해야 한다는 것입니다.

이 글에서 다루는 예제 프로젝트는 샌드 박싱 환경을 직접 구성하고 있기 때문에 AppDomain.CreateDomain 메서드에 전달되는 AppDomainSetup.PartialTrustVisibleAssemblies 속성 값을 다음과 같이 채워놓아야 합니다.

AppDomainSetup adSetup = new AppDomainSetup();
// ...[생략]...
adSetup.PartialTrustVisibleAssemblies = new string[]
{
    "HostService, PublicKey=002400000...[생략]...DC0651F96BA"
};

// ...[생략]...

AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

주의할 것은, 어셈블리 이름 지정 시 PublicKeyToken 값이 아닌 PublicKey가 쓰인다는 점입니다. 이 값을 구하려면 예외 메시지에 나온 PublicKey 값을 써도 되지만 만약 표시되지 않은 경우에는 해당 어셈블리로부터 sn.exe를 이용해 다음과 같이 구할 수 있습니다.

C:\Program Files (x86)\Microsoft Visual Studio 14.0>sn -Tp C:\...[생략]...\TestApp2\HostService\bin\Debug\HostService.dll

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key (hash algorithm: sha1):
002400000480000094000000060200000024000052534131000400000100010015508e3d344333
7e6c58ae5eca494a8fb5ff8c92538de1756779a1e199f00d1931690e02ccd7db671100051cca6e
877a258b919e466c3f7723bd3dd499a5e9bf4bd8861894f8bbbff8dba79c49d0006d6b46fda009
38c026d73360979454b08aa19507ebc03b858e11cc1d438904fe46db8758ae010c273f71d42dc0
651f96ba

Public key token is 2a9ed378705e40fd

이제, 다시 한번 예제 프로젝트를 실행하면 이번에는 정상적으로 실행되는 것을 확인할 수 있습니다.

물론, 이 제약은 샌드박싱 환경에서만 유효합니다. 즉, 보안을 제약하지 않은 일반 응용 프로그램이거나 "<trust level="Full" />"이 기본값인 웹 응용 프로그램에서는 '조건부 APTCA'가 설정된 어셈블리를 partialTrustVisibleAssemblies로 굳이 등록해줄 필요가 없습니다.

(첨부한 파일은 이 글의 예제 코드를 포함합니다.)




참고로, 이미 호스팅 환경이 구성된 ASP.NET 웹 응용 프로그램에서라면 '조건부 APTCA'가 지정된 어셈블리를 사용하기 위해 web.config에 다음과 같은 식으로 등록해 줄 수 있습니다.

<configuration> 

    ...[생략]...

    <system.web>

        ...[생략]...

        <partialTrustVisibleAssemblies> 
            <add assemblyName="HostService" publicKey="002400000...[생략]...DC0651F96BA" />
        </partialTrustVisibleAssemblies>
    </system.web>

    ...[생략]...

</configuration>




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







[최초 등록일: ]
[최종 수정일: 4/13/2017]

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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12101정성태1/5/202011106.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209130.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011427디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011020.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209586디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911598디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201912955VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911107.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911141.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910549디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201912078디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910720.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911452디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910419Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201910894디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201912922디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910623오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201911273디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201912538Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201912408오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201914131개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201912050.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201913276오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201913231Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201912731Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201910942디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...