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)
12343정성태9/24/202019738.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202010963디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
12341정성태9/23/202010064.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/20209792.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/20209841오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/20209368오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202010705오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202013195.NET Framework: 942. C# - WOL(Wake On Lan) 구현
12335정성태9/21/202022571Linux: 31. 우분투 20.04 초기 설정 - 고정 IP 및 SSH 설치
12334정성태9/21/20207986오류 유형: 652. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter"
12333정성태9/20/20208396.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
12332정성태9/18/202010488.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드파일 다운로드1
12331정성태9/18/20209626오류 유형: 651. repadmin /syncall - 0x80090322 The target principal name is incorrect.
12330정성태9/18/202010668.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 [2]파일 다운로드1
12329정성태9/16/202012578오류 유형: 650. ASUS 메인보드 관련 소프트웨어 설치 후 ArmouryCrate.UserSessionHelper.exe 프로세스 무한 종료 현상
12328정성태9/16/202012795VS.NET IDE: 150. TFS의 이력에서 "Get This Version"과 같은 기능을 Git으로 처리한다면?
12327정성태9/12/202010373.NET Framework: 938. C# - ICS(Internet Connection Sharing) 제어파일 다운로드1
12326정성태9/12/20209867개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/20209457개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202010724개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209597오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202010684개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/20208908오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/202010089개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/20209878오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/20209334오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...