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)
12405정성태11/8/202010472.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202010979.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011036.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011617.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010544VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207576오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011209.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209686오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/20209817.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208189VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209504오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20207922오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208394오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012538.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010702디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010577.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/20209967오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010732.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202010991Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20208744오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/20209957오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202010943.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208552오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010224VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207696오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010658.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...