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을 해석하는 방식"을 쓰지 않도록 해야 할 것입니다. 암튼, 완성되고 나면 후기 좀 남겨주세요. ^^
정성태

... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11150정성태2/21/201719351.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201723054오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201721967.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201721206오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201719896오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201721349.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201724744.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201722107.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201730129.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201724415.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201720164.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201722883.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201721164VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201719848Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201719031오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201720038Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면? [1]
11134정성태1/20/201727443.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201723556.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201735068.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201723995.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201724516.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201728893.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201723295.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201722870기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201727589기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201724446개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...