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)
11049정성태9/24/201620932오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201621954VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625783기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627411개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620082Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620328VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621742.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619905오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619394.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626688.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623206오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625048VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628280.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624768개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620402오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624426개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622276오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621498개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617745오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620303VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627429.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621515오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622572.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623564Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622267개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621561오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...