Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면?
; https://www.sysnet.pe.kr/2/0/12733

.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션
; https://www.sysnet.pe.kr/2/0/13159

.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
; https://www.sysnet.pe.kr/2/0/13160

.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성)
; https://www.sysnet.pe.kr/2/0/13161




C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성)

지난 글에 설명한,

C# - PublishSingleFile과 관련된 옵션
; https://www.sysnet.pe.kr/2/0/13159

C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
; https://www.sysnet.pe.kr/2/0/13160

닷넷 6 환경의 PublishSingleFile 및 몇몇 옵션을 적용한 바이너리 결과물은 겉으로만 봐서는 managed/native 모듈인지 모를 정도라고 했습니다. 그렇다면 혹시 역어셈블과의 관계는 어떨까요?

가령 다음과 같은 옵션으로 배포한 실행 모듈은,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>

        <PublishSingleFile>true</PublishSingleFile>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <DebugType>embedded</DebugType>
        <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
    </PropertyGroup>

</Project>

당연히 dnSpy.exe와 같은 도구로는,

net_single_file_0.png

역어셈블할 수 없습니다. 오호~~~ 뜻하지 않은 보안 효과가 있습니다. ^^ 이런 식이라면 웬만한 상황에서는 굳이 난독화 처리를 하지 않아도 될 정도입니다.




재미있는 건, 실행 중인 파일을 Windbg와 같은 디버거로 attach 시켜도 분석이 잘 안 된다는 점입니다. 실제로 windbg에서는 해당 모듈이 닷넷 이미지임을 알 수 없어 sos 확장 DLL을 자동으로 로드하지도 못합니다. ("dotnet-dump ps"가 닷넷 프로세스라는 것을 인식하는 걸 보면, windbg도 나중에는 이에 대한 개선이 있지 않을까... 예상해 봅니다.)

그래서 Windbg의 경우 실행 중인 프로세스를 분석하려면, 애당초 배포한 실행 모듈을 만들었을 당시의 mscordaccore.dll 파일을 함께 제공해야 합니다. 예를 들어, 배포 파일이 다음의 경로에 있다면,

.\net6_pubone_sample\bin\Debug\net6.0\win-x64\publish\net6_pubone_sample.exe

저 배포 파일을 빌드하기 위해 만든 managed + native 재료들이 ".\net6_pubone_sample\bin\Debug\net6.0\win-x64" 디렉터리에 위치하는데요, 그 안에 보면 mscordaccore.dll이 있습니다.

즉, 실행 파일을 만든 측에서 그것을 빌드한 닷넷 런타임과 일치하는 mscordaccore.dll을 함께 배포해줘야 하는 것입니다. 물론, 그런 경우는 거의 없을 것이므로 windbg로 닷넷 6+ 실행 모듈을 분석하기란 쉽지 않습니다. 하지만, 불가능한 것은 아닙니다. 왜냐하면 지금까지 배포된 닷넷 런타임을 버전 별로 모두 설치한 다음, 그 런타임들에 포함된 mscordaccore.dll을 일일이 시도해 보면 되기 때문입니다. 약간 귀찮을 뿐... 가능하다는 이야깁니다.

어떤 식으로든 mscordaccore.dll을 구했다면 ".cordll" 명령어를 이용해 직접 로드/분석이 가능합니다.

// C:\temp\mscordaccore.dll 경로에 있는 경우,

0:007> .cordll -lp "C:\temp"
CLR DLL status: Loaded DLL C:\ProgramData\Dbg\sym\mscordaccore.dll\625708C0145000\mscordaccore.dll

0:007> !threads
ThreadCount:      2
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       0
Hosted Runtime:   no
                                                                                                            Lock  
 DBG   ID     OSID ThreadOBJ           State GC Mode     GC Alloc Context                  Domain           Count Apt Exception
   0    1     f208 000001F5287198E0    2a020 Preemptive  000001F52A3F91B8:000001F52A3FA008 000001f5286bd6b0 -00001 MTA 
   6    2     d8f4 000001F528744B10    21220 Preemptive  0000000000000000:0000000000000000 000001f5286bd6b0 -00001 Ukn (Finalizer) 

0:007> ~0s
ntdll!NtReadFile+0x14:
00007ffc`f32ceec4 c3              ret

0:000> !clrstack
OS Thread Id: 0x43a4 (0)
        Child SP               IP Call Site
000000AEB417E448 00007ffcf32ceec4 [InlinedCallFrame: 000000aeb417e448] Interop+Kernel32.ReadFile(IntPtr, Byte*, Int32, Int32 ByRef, IntPtr)
000000AEB417E448 00007ff667b16da2 [InlinedCallFrame: 000000aeb417e448] Interop+Kernel32.ReadFile(IntPtr, Byte*, Int32, Int32 ByRef, IntPtr)
000000AEB417E410 00007ff667b16da2 ILStubClass.IL_STUB_PInvoke(IntPtr, Byte*, Int32, Int32 ByRef, IntPtr)
000000AEB417E4E0 000002329941c742 System.ConsolePal+WindowsConsoleStream.ReadFileNative(IntPtr, System.Span`1, Boolean, Int32 ByRef, Boolean) [/_/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @ 1163]
000000AEB417E550 000002329941c5db System.ConsolePal+WindowsConsoleStream.Read(System.Span`1) [/_/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @ 1123]
000000AEB417E590 0000023299420627 System.IO.ConsoleStream.Read(Byte[], Int32, Int32) [/_/src/libraries/System.Console/src/System/IO/ConsoleStream.cs @ 34]
000000AEB417E600 00000001803a6be5 System.IO.StreamReader.ReadBuffer()
000000AEB417E680 00000001803a7317 System.IO.StreamReader.ReadLine() [/_/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs @ 801]
000000AEB417E6D0 0000023299420bf0 System.IO.SyncTextReader.ReadLine() [/_/src/libraries/System.Console/src/System/IO/SyncTextReader.cs @ 76]
000000AEB417E720 0000023299418a0c System.Console.ReadLine() [/_/src/libraries/System.Console/src/System/Console.cs @ 721]
000000AEB417E750 00007ff667b12cc8 net6_pubone_sample.Program.Main(System.String[]) [C:\net6_pubone_sample\net6_pubone_sample\Program.cs @ 7]

따라서, 아쉽게도 이전에 만약 난독화를 하고 있는 중이었다면 이런 이유로 인해 여전히 난독화는 계속되어야 합니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/14/2022]

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

비밀번호

댓글 작성자
 



2022-11-27 12시29분
[hong] dnspy에서는 디컴파일이 안되지만, ILSpy에서는 디컴파일이 잘되서 나오네요. ILSpy는 알아서 분석해서 디컴파일을 해주나봅니다.
[guest]
2022-11-27 12시38분
좋은 정보 감사합니다. ^^

이력을 보니까 dnSpy는 이제 거의 죽은 프로젝트가 된 듯하군요. 반면, ILSpy는 여전히 활발하게 업그레이드가 되는 중이고.

.NET Decompiler with support for PDB generation, ReadyToRun, Metadata (&more) - cross-platform!
; https://github.com/icsharpcode/ILSpy

제목으로 봐서는 "PublishReadyToRun" 옵션으로 빌드한 바이너리도 Managed 모듈의 부분을 찾아서 역어셈블해주는 것 같습니다. 저도 이참에 ILSpy로 갈아타야겠습니다. ^^
정성태
2022-12-25 08시48분
[문우영] dotnet publish -c Release -r linux-arm64 -p:PublishTrimmed=true -p:PublishSingleFile=true -p:ReadyToRun=true -p:selfcontained=true

이렇게 까지 했을 경우 linux나 ios에서 dotnet 설치 없이 실행 가능해서 좋으나 ILSpy에서도 Disassembler 해주더라구요

https://github.com/dotnet/runtime/issues/36590
https://github.com/icsharpcode/ILSpy/tree/master/ILSpy.ReadyToRun

~.deps.json 파일로 runtime dll찾는거 까지 확인 하였습니다. Disassembler 방지 하게 할 수 있는 방법이 있을듯 하긴 합니다.
Obfuscation 없이 Disassembler 방지 하는거 연구 중에 있습니다.

형님 잘지내 시지는지? 여전히 좋은글 많이 작성 해주시네요~
[guest]
2022-12-26 02시03분
재미있는 시도군요. ^^ 일반적인 C# 컴파일러로 만든 모듈이라면 disassemble을 못하게 하는 방법은 없을 듯합니다. 왜냐하면, 어차피 모든 DLL을 포함하는 형식이기 때문입니다. 아마도 disassemble을 방해하고 싶다면 C# 컴파일러를 사용자 정의해서 ILSpy가 기대하는 "포함된 DLL을 해석하는 방식"을 쓰지 않도록 해야 할 것입니다. 암튼, 완성되고 나면 후기 좀 남겨주세요. ^^
정성태

... 46  47  48  49  50  51  52  53  54  55  56  57  58  [59]  60  ...
NoWriterDateCnt.TitleFile(s)
12166정성태3/4/202011398개발 환경 구성: 470. Windows Server 컨테이너 - DockerMsftProvider 모듈을 이용한 docker 설치
12165정성태3/2/202011050.NET Framework: 900. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 네 번째 이야기(Monitor.Enter 후킹)파일 다운로드1
12164정성태2/29/202011903오류 유형: 598. Surface Pro 6 - Windows Hello Face Software Device가 인식이 안 되는 문제
12163정성태2/27/202010367.NET Framework: 899. 익명 함수를 가리키는 delegate 필드에 대한 직렬화 문제
12162정성태2/26/202013217디버깅 기술: 166. C#에서 만든 COM 객체를 C/C++로 P/Invoke Interop 시 메모리 누수(Memory Leak) 발생 [6]파일 다운로드2
12161정성태2/26/20209823오류 유형: 597. manifest - The value "x64" of attribute "processorArchitecture" in element "assemblyIdentity" is invalid.
12160정성태2/26/202010518개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
12159정성태2/26/20208633오류 유형: 596. Visual Studio - The project needs to include ATL support
12158정성태2/25/202010512디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202010480디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/20209782오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/20209011오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
12154정성태2/25/20208815오류 유형: 593. warning LNK4070: /OUT:... directive in .EXP differs from output filename
12153정성태2/23/202011575.NET Framework: 898. Trampoline을 이용한 후킹의 한계파일 다운로드1
12152정성태2/23/202011319.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)파일 다운로드1
12151정성태2/22/202011795.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)파일 다운로드1
12150정성태2/21/202011675.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 [1]파일 다운로드1
12149정성태2/20/202011445.NET Framework: 894. eBEST C# XingAPI 래퍼 - 연속 조회 처리 방법 [1]
12148정성태2/19/202012686디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법 [1]
12147정성태2/19/202011337디버깅 기술: 162. x86/x64의 기계어 코드 최대 길이
12146정성태2/18/202011536.NET Framework: 893. eBEST C# XingAPI 래퍼 - 로그인 처리파일 다운로드1
12145정성태2/18/202010757.NET Framework: 892. eBEST C# XingAPI 래퍼 - Sqlite 지원 추가파일 다운로드1
12144정성태2/13/202010797.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기파일 다운로드1
12143정성태2/13/20208827.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64파일 다운로드1
12142정성태2/12/202010649.NET Framework: 889. C# 코드로 접근하는 MethodDesc, MethodTable파일 다운로드1
12141정성태2/10/202010219.NET Framework: 888. C# - ASP.NET Core 웹 응용 프로그램의 출력 가로채기 [2]파일 다운로드1
... 46  47  48  49  50  51  52  53  54  55  56  57  58  [59]  60  ...