Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법

지난 몇 개의 글에 걸쳐 강력한 이름의 어셈블리와 지연 서명된 어셈블리에 관해 설명했는데요.

지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법  
; https://www.sysnet.pe.kr/2/0/11259

지연 서명된 DLL과 서명된 DLL의 차이점
; https://www.sysnet.pe.kr/2/0/11258

bypassTrustedAppStrongNames 옵션 설명 
; https://www.sysnet.pe.kr/2/0/11257

windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법
; https://www.sysnet.pe.kr/2/0/11256

사실, 그 모든 것들이 이번 글을 쓰기 위한 사전 작업에 해당하는 것이었습니다. 아마도 이 글을 읽지 않고서도 위의 글들을 이해했다면 그 방법을 눈치채셨을 수도 있습니다. ^^




windbg의 "!savemodule" 명령어를 이용해 저장한 닷넷 DLL/EXE 파일의 경우 간혹 디버깅을 위해 저장된 모듈의 코드를 바꿔야 하는 경우가 종종 있습니다. 가령, dnSpy를 통해 IL 코드 수준에서 변경하거나 .NET Reflector 등의 도구를 이용해 소스 코드 상태의 프로젝트로 복원해 변경해 볼 수 있는데요.

이런 경우, 상황에 따라 다음과 같은 문제가 발생합니다.

  1. dnSpy 등으로 IL 코드를 변경한 경우: 서명이 깨짐
  2. .NET Reflector 등의 도구를 통해 소스 코드로 복원 후 빌드한 경우: 해당 DLL을 사용하는 또 다른 DLL이 있는 경우 그 프로젝트까지 소스 코드 상태로 복원해 다시 빌드하는 식으로 연쇄적인 소스 코드 복원 작업이 이어짐.

간단한 예를 들기 위해 웹 애플리케이션을 하나 만들고 거기서 강력한 이름의 어셈블리를 2개 참조해 보겠습니다.

// WebApplication2 프로젝트의 default.aspx.cs
using System;

namespace WebApplication2
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
            this.Literal1.Text = cl.Do();

            ClassLibrary2.Class1 cl2 = new ClassLibrary2.Class1();
            this.Literal1.Text += cl2.Do();
        }
    }
}

// ClassLibrary1 프로젝트의 Class1.cs - 강력한 이름의 어셈블리
namespace ClassLibrary1
{
    public class Class1
    {
        public string Do()
        {
            return "OK";
        }
    }
}

// ClassLibrary2 프로젝트의 Class1.cs - 강력한 이름의 어셈블리 (ClassLibrary1.dll을 참조)
namespace ClassLibrary2
{
    public class Class1
    {
        public string Do()
        {
            ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
            return "OK," + cl.Do();
        }
    }
}

이를 (iisexpress.exe로) 실행하고 풀 덤프 파일을 받습니다. 그다음 windbg로 열어 !savemodule로,

windbg - 풀 덤프 파일로부터 .NET DLL을 추출/저장하는 방법
; https://www.sysnet.pe.kr/2/0/10943

라이브러리 2개를 추출해 저장합니다.

0:000> .loadby sos clr

0:000> !name2ee *!Any
Module:      6dbe1000
Assembly:    SMDiagnostics.dll
--------------------------------------
...[생략]...
--------------------------------------
Module:      08ba4e60
Assembly:    ClassLibrary1.dll
--------------------------------------
Module:      08ba5354
Assembly:    ClassLibrary2.dll
--------------------------------------
Module:      0946e4e4
Assembly:    Microsoft.VisualStudio.Web.PageInspector.HtmlParser.dll

0:000> !savemodule 08ba4e60 c:\temp\ClassLibrary1.dll
3 sections in file
section 0 - VA=2000, VASize=8b8, FileAddr=200, FileSize=a00
section 1 - VA=4000, VASize=398, FileAddr=c00, FileSize=400
section 2 - VA=6000, VASize=c, FileAddr=1000, FileSize=200

0:000> !savemodule 08ba5354 c:\temp\ClassLibrary2.dll
3 sections in file
section 0 - VA=2000, VASize=930, FileAddr=200, FileSize=a00
section 1 - VA=4000, VASize=398, FileAddr=c00, FileSize=400
section 2 - VA=6000, VASize=c, FileAddr=1000, FileSize=200

이제 저 DLL 중에서 필요에 의해 변경하는 것을 가정하고 ClassLibrary1.dll 파일의 IL 코드 조작을 dnSpy.exe를 이용해 다음과 같이 한 후,

using System;

namespace ClassLibrary1
{
    // Token: 0x02000002 RID: 2
    public partial class Class1
    {
        // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
        public string Do()
        {
            return "FAILED";
        }
    }
}

간단한 웹 사이트 프로젝트를 만들어 참조해서 사용하려고 시도하면,

// 덤프 파일로부터 추출한 DLL을 테스트하기 위해 만든 웹 애플리케이션
using System;

namespace WebApplication1
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
            this.Literal1.Text = cl.Do();

            ClassLibrary2.Class1 cl2 = new ClassLibrary2.Class1();
            this.Literal1.Text += cl2.Do();
        }
    }
}

익숙한 그 예외가 발생합니다.

Could not load file or assembly 'ClassLibrary1' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)


또는, ClassLibrary1.dll을 디컴파일해서 소스 코드로부터 다시 빌드해 DLL을 만드는 경우 ClassLibrary2.dll에서 강력한 이름이었던 ClassLibrary1.dll을 참조하고 있었기 때문에 역시 문제가 발생합니다. 이런 경우에도 해결하려면 ClassLibrary2.dll 마저 디컴파일해서 복원해야 합니다. 하지만 이게 현실적으로 어려운 부분이 많은데 풀 덤프를 받게 되는 대부분의 응용 프로그램이 복잡한 참조 관계의 DLL들로 구성되어 있기 때문에 그 모든 것을 다 복원하려면 시간이 꽤나 걸리게 됩니다.




자, 그럼 복잡한 DLL들의 참조 관계를 유지하면서 저 변조된 DLL을 정상적으로 로드하는 방법을 이전 글들의 내용과 함께 조합해 보겠습니다.

우선, 지난 글에서 설명했듯이 강력한 이름의 어셈블리는 우회할 수 없지만 지연 서명된 어셈블리를 우회할 수 있었던 것에 착안해 dnSpy.exe를 이용해 "Edit Assembly Attributes" 기능으로 다음의 코드를 넣어주고,

[assembly:AssemblyDelaySignAttribute(true)]

컴파일한 후 저장합니다. 그럼, dnspy.exe는 StrongNameSignature RVA 위치로부터 StrongNameSignature Size 만큼의 영역을 모두 0으로 채웁니다.

그다음 ClassLibrary1.dll 파일을 CFF Explorer 같은 도구를 이용해 "Flags" 값에서 StrongNameSigned를 제외합니다. 변경 사항을 저장하고 나면 ClassLibrary1.dll 파일은 결과적으로 지연 서명된 어셈블리와 다를 바 없는 상태가 됩니다.

마지막으로 지연 서명된 어셈블리를 로드할 수 있도록 (관리자 권한의) sn.exe 명령어를 다음과 같이 실행해 줍니다.

sn.exe -Vr ClassLibrary1.dll

이제 다시 WebApplication1 프로젝트를 실행하면 정상적으로 default.aspx가 실행되는 것을 볼 수 있습니다. 아울러 ClassLibrary1.dll 자체를 지연 서명으로 인식시켰지만 여전히 public key token은 변함이 없기 때문에 ClassLibrary2.dll에서의 참조 사용도 허용이 됩니다.


[2020-07-24: 업데이트] 이 글에서 쓴 방법보다 DEVPATH를 이용하는 것이 더 쉬울 수 있습니다.



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/24/2020]

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)
11845정성태3/15/201914282Linux: 5. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) [3]
11844정성태3/14/201915114개발 환경 구성: 434. Visual Studio 2019 - 리눅스 프로젝트를 이용한 공유/실행(so/out) 프로그램 개발 환경 설정 [1]파일 다운로드1
11843정성태3/14/201910858기타: 75. MSDN 웹 사이트를 기본으로 영문 페이지로 열고 싶다면?
11842정성태3/13/201910267개발 환경 구성: 433. 마이크로소프트의 CoreCLR 프로파일러 예제를 Visual Studio CMake로 빌드하는 방법 [1]파일 다운로드1
11841정성태3/13/201910231VS.NET IDE: 132. Visual Studio 2019 - CMake의 컴파일러를 기본 g++에서 clang++로 변경
11840정성태3/13/201911336오류 유형: 526. 윈도우 10 Ubuntu App 환경에서는 USB 외장 하드 접근 불가
11839정성태3/12/201914107디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201916852.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201926573기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201914410오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201914181.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201913071개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913833개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910864오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910454오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910243오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912142개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918553개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912460오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912343오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917206개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201912014오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913501오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911632오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912088오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915232오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...