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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12251정성태7/1/202011040.NET Framework: 920. C# - 파일의 비동기 처리 유무에 따른 스레드 상황 [1]파일 다운로드2
12250정성태6/30/202013672.NET Framework: 919. C# - 닷넷에서의 진정한 비동기 호출을 가능케 하는 I/O 스레드 사용법 [1]파일 다운로드1
12249정성태6/29/20209816오류 유형: 625. Microsoft SQL Server 2019 RC1 Setup - 설치 제거 시 Warning 26003 오류 발생
12248정성태6/29/20208235오류 유형: 624. SQL 서버 오류 - service-specific error code 17051
12247정성태6/29/20209764.NET Framework: 918. C# - 불린 형 상수를 반환값으로 포함하는 3항 연산자 사용 시 단축 표현 권장(IDE0075) [2]파일 다운로드1
12246정성태6/29/202010565.NET Framework: 917. C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법
12245정성태6/24/202011042.NET Framework: 916. C# - Task.Yield 사용법 (2) [2]파일 다운로드1
12244정성태6/24/202010869.NET Framework: 915. ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용 [1]파일 다운로드1
12243정성태6/23/20208447VS.NET IDE: 147. Visual C++ 프로젝트 - .NET Core EXE를 "Debugger Type"으로 지원하는 기능 추가
12242정성태6/23/20209175오류 유형: 623. AADSTS90072 - User account '...' from identity provider 'live.com' does not exist in tenant 'Microsoft Services'
12241정성태6/23/202012528.NET Framework: 914. C# - Task.Yield 사용법파일 다운로드1
12240정성태6/23/202013823오류 유형: 622. 소켓 바인딩 시 "System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions" 오류 발생
12239정성태6/21/202010222Linux: 30. (윈도우라면 DLL에 속하는) .so 파일이 텍스트로 구성된 사례 [1]
12238정성태6/21/202010188.NET Framework: 913. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 라이브러리
12237정성태6/20/20209958.NET Framework: 912. 리눅스 환경의 .NET Core에서 "test".IndexOf("\0")가 0을 반환
12236정성태6/19/202010350오류 유형: 621. .NET Standard 대상으로 빌드 시 dynamic 예약어에서 컴파일 오류 - error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
12235정성태6/19/20209969오류 유형: 620. Windows 10 - Inaccessible boot device 블루 스크린
12234정성태6/19/20209693개발 환경 구성: 494. NuGet - nuspec의 패키지 스키마 버전(네임스페이스) 업데이트 방법
12233정성태6/19/20209373오류 유형: 619. SQL 서버 - The transaction log for database '...' is full due to 'LOG_BACKUP'. - 두 번째 이야기
12232정성태6/19/20208326오류 유형: 618. SharePoint - StoreBusyRetryLater 오류
12231정성태6/15/202010748.NET Framework: 911. Console/Service Application을 위한 SynchronizationContext - AsyncContext
12230정성태6/15/202010113오류 유형: 617. IMetaDataImport::GetMethodProps가 반환하는 IL 코드 주소(RVA) 문제
12229정성태6/13/202011983.NET Framework: 910. USB/IP PROJECT를 이용해 C#으로 USB Keyboard + Mouse 가상 장치 만들기 [1]
12228정성태6/12/202012079.NET Framework: 909. C# - Source Generator를 적용한 XmlCodeGenerator파일 다운로드1
12227정성태6/12/202016043오류 유형: 616. Visual Studio의 느린 업데이트 속도에 대한 원인 분석 [5]
12226정성태6/11/202013343개발 환경 구성: 493. OpenVPN의 네트워크 구성 [4]파일 다운로드1
... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...