Microsoft MVP성태의 닷넷 이야기
닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx) [링크 복사], [링크+제목 복사]
조회: 1911
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)

그러고 보니, 제 블로그에서 난독화를 다룬 적이 한 번도 없었군요. ^^; 사실, 개인적으로 지금까지의 경력에서 난독화를 써야 할 프로젝트는 단 한 번도 없었습니다. 그보다는, 난독화가 필요하다면 오히려 중요한 부분만 C/C++ 프로그램으로 대체해 본 적은 있습니다.

경험은 없지만, 그래도 이번 글에서는 간략하게 난독화 도구에 대해 소개해 봅니다. 친절하게도 .NET 환경을 위한 난독화 도구만 모아놓은 링크가 있는데요,

NotPrab/.NET-Obfuscator
; https://github.com/NotPrab/.NET-Obfuscator

제 게시판에서도 질문이 있었던 ConfuserEx도 있으니, 반가운 김에 이걸로 예를 들어보겠습니다. ^^

yck1509/ConfuserEx
; https://github.com/yck1509/ConfuserEx

위의 프로젝트는 .NET Framework만 지원하고 현재 archive 상태인데요, 어차피 마이크로소프트 측의 .NET Framework 지원도 비슷한 상황이므로 적어도 .NET Framework을 대상으로 한다면 여전히 쓸만하다고 생각됩니다. 게다가 난독화 관련한 대부분의 기능을 제공하고 있어 이런 유의 제품들에 대한 이해를 쉽게 할 수 있을 것입니다.




예제로 직접 설명해 보는 게 좋겠지요. ^^

우선, .NET Framework 4.8 클래스 라이브러리 유형으로 다음의 코드를 작성해 주고,

using System;
using System.Reflection;

namespace ClassLibrary1
{
    public class Class1
    {
        public void MyPublicMethod(string arg)
        {
            Console.WriteLine($"MyPublicMethod: {nameof(arg)}: {arg}");
            MyPrivateMethod(arg);
            MyPrivateMethod2(arg);
        }

        private void MyPrivateMethod(string arg)
        {
            Console.WriteLine($"{nameof(Class1.MyPrivateMethod)}: {nameof(arg)}: {arg}");
        }

        [Obfuscation(Exclude = true)]
        private void MyPrivateMethod2(string arg)
        {
            Console.WriteLine($"{nameof(Class1.MyPrivateMethod2)}: {nameof(arg)}: {arg}");
        }
    }
}

그다음, 이를 사용하는 .NET Framework 4.8 Console 프로젝트를 만듭니다.

using System;
using System.Reflection;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
            cl.MyPublicMethod("TEST");

            {
                MethodInfo mi = typeof(ClassLibrary1.Class1).GetMethod("MyPublicMethod");
                Console.WriteLine($"MyPublicMethod: {mi}");
            }

            {
                MethodInfo mi = typeof(ClassLibrary1.Class1).GetMethod("MyPrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic);
                Console.WriteLine($"MyPrivateMethod: {mi}");
            }

            {
                MethodInfo mi = typeof(ClassLibrary1.Class1).GetMethod("MyPrivateMethod2", BindingFlags.Instance | BindingFlags.NonPublic);
                Console.WriteLine($"MyPrivateMethod2: {mi}");
            }
        }
    }
}

현재 위의 프로그램을 실행하면 이런 결과가 나옵니다.

Hello, World!
MyPublicMethod: arg: TEST
MyPrivateMethod: arg: TEST
MyPrivateMethod2: arg: TEST
MyPublicMethod: Void MyPublicMethod(System.String)
MyPrivateMethod: Void MyPrivateMethod(System.String)
MyPrivateMethod2: Void MyPrivateMethod2(System.String)

자, 이제 난독화 도구를 돌려볼까요? ^^ ConfuserEx의 경우 난독화 설정을 담은 프로젝트 파일을 하나 만들어 줘야 하는데요, Q&A에서 나온 예제 파일을 따라 제 경우에는 다음과 같이 만들어줬습니다.

<?xml version="1.0" encoding="utf-8"?>
<project baseDir="C:\temp\ConsoleApp2\ConsoleApp2" outputDir="c:\Confused" xmlns="http://confuser.codeplex.com">
    <rule preset="none" pattern="true">
        <protection id="anti debug" />
        <protection id="anti dump" />
        <protection id="anti ildasm" />
        <protection id="anti tamper" />
        <protection id="constants" />
        <protection id="ctrl flow" />
        <protection id="invalid metadata" />
        <protection id="ref proxy" />
        <protection id="rename" />
        <dprotection id="resources" />
    </rule>
    <module path="C:\temp\ConsoleApp2\ConsoleApp2\bin\Debug\ClassLibrary1.dll" />
    <module path="C:\temp\ConsoleApp2\ConsoleApp2\bin\Debug\ConsoleApp2.exe" />
</project>

끝입니다. 이제 위의 내용을 담은 test.crproj 파일을 Confuser.CLI 실행 파일에 인자로 넘겨주면,

C:\temp\ConsoleApp2> Confuser.CLI test.crproj
 [INFO] ConfuserEx v1.0.0 Copyright (C) Ki 2014
 [INFO] Running on Microsoft Windows NT 6.2.9200.0, .NET Framework v4.0.30319.42000, 64 bits
[DEBUG] Discovering plugins...
 [INFO] Discovered 10 protections, 1 packers.
[DEBUG] Resolving component dependency...
 [INFO] Loading input modules...
 [INFO] Loading 'C:\temp\ConsoleApp2\ConsoleApp2\bin\Debug\ClassLibrary1.dll'...
 [INFO] Loading 'C:\temp\ConsoleApp2\ConsoleApp2\bin\Debug\ConsoleApp2.exe'...
 [INFO] Initializing...
[DEBUG] Building pipeline...
 [INFO] Resolving dependencies...
...[생략]...

test.crproj 파일 내에 명시한 outputDir, 위의 경우에는 "c:\Confused\bin\Debug" 하위에 난독화 처리된 ClassLibrary1.dll, ConsoleApp2.exe 파일이 생성됩니다. 그리고 그것을 실행하면,

c:\Confused\bin\Debug> ConsoleApp2.exe
Hello, World!
MyPublicMethod: arg: TEST
MyPrivateMethod: arg: TEST
MyPrivateMethod2: arg: TEST
MyPublicMethod: Void MyPublicMethod(System.String)
MyPrivateMethod:
MyPrivateMethod2: Void MyPrivateMethod2(System.String)

차이점이 딱 하나 눈에 띄죠? ^^ 바로 NonPublic 멤버에 대한 Reflection 조회가 안 된 것입니다. 왜냐하면, Public을 제외한 모든 멤버들의 이름을 무의미한 이름으로 바꿔서 처리하기 때문입니다. 그리고 만약 특정 멤버가 꼭 Reflection 조회 등에서 필요하다면 그 멤버에 대해서는 System.Reflection.ObfuscationAttribute를 명시해 Exclude 속성을 true로 설정할 수 있습니다.




test.crproj에 있던 protection 명세를 다시 한번 볼까요? ^^

<protection id="anti debug" />
<protection id="anti dump" />
<protection id="anti ildasm" />
<protection id="anti tamper" />
<protection id="constants" />
<protection id="ctrl flow" />
<protection id="invalid metadata" />
<protection id="ref proxy" />
<protection id="rename" />
<dprotection id="resources" />

VM 계열의 바이너리에 대한 난독화의 기본은 "rename"입니다. 의미를 알 수 없는 이름으로 마구 바꿔버리는 바람에 소스코드 해석을 어렵게 하는 것인데요, 그 외에도 위의 목록에서처럼 나름의 기법들이 더 있습니다.

이런 옵션들 덕분에 역어셈블러 제품들이 소스코드를 보는 것조차 힘들게 만드는 효과가 있는데요, (아마도 "invalid metadata"일 듯한데) 실제로 dnSpy와 같은 프로그램으로 난독화된 ClassLibrary1.dll을 보면 이런 결과가 나옵니다.

using System;

namespace ClassLibrary1
{
    // Token: 0x0200000D RID: 13
    public class Class1
    {
        // Token: 0x0600005D RID: 93 RVA: 0x00007B74 File Offset: 0x00005F74
        public void MyPublicMethod(string arg)
        {
        }

        // Token: 0x0600005E RID: 94 RVA: 0x00007BDC File Offset: 0x00005FDC
        private void \u202A\u206E\u202D\u206B\u206F\u206D\u200D\u206C\u200B\u200C\u206D\u202A\u206B\u202C\u206B\u206B\u206C\u206A\u202A\u206D\u200D\u200B\u202B\u200B\u200F\u206C\u206C\u200F\u206F\u206F\u202E\u206B\u202E\u202C\u206E\u202B\u206F\u200B\u206C\u200D\u202E(string)
        {
        }

        // Token: 0x0600005F RID: 95 RVA: 0x00008048 File Offset: 0x00006248
        private void MyPrivateMethod2(string arg)
        {
            Console.WriteLine("MyPrivateMethod2: arg: " + arg);
        }

        // Token: 0x06000060 RID: 96 RVA: 0x00007C44 File Offset: 0x00006044
        public Class1()
        {
            /*
An exception occurred when decompiling this method (06000060)

ICSharpCode.Decompiler.DecompilerException: Error decompiling System.Void ClassLibrary1.Class1::.ctor()

 ---> System.ArgumentOutOfRangeException: Non-negative number required. (Parameter 'length')
   at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
   at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length)
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.StackSlot.ModifyStack(StackSlot[] stack, Int32 popCount, Int32 pushCount, ByteCode pushDefinition) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 48
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.StackAnalysis(MethodDef methodDef) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 387
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.Build(MethodDef methodDef, Boolean optimize, DecompilerContext context) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 269
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(IEnumerable`1 parameters, MethodDebugInfoBuilder& builder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 112
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(MethodDef methodDef, DecompilerContext context, AutoPropertyProvider autoPropertyProvider, IEnumerable`1 parameters, Boolean valueParameterIsKeyword, StringBuilder sb, MethodDebugInfoBuilder& stmtsBuilder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 88
   --- End of inner exception stack trace ---
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(MethodDef methodDef, DecompilerContext context, AutoPropertyProvider autoPropertyProvider, IEnumerable`1 parameters, Boolean valueParameterIsKeyword, StringBuilder sb, MethodDebugInfoBuilder& stmtsBuilder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 92
   at ICSharpCode.Decompiler.Ast.AstBuilder.<>c__DisplayClass90_0.<AddMethodBody>b__0() in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstBuilder.cs:line 1519
*/;
        }

        // Token: 0x06000061 RID: 97 RVA: 0x00003978 File Offset: 0x00001D78
        static string \u200D\u200B\u206B\u206E\u200F\u206D\u200C\u202E\u200F\u206F\u200C\u202D\u206F\u202D\u206A\u206B\u206D\u200C\u200C\u200D\u206F\u200D\u200F\u200C\u202C\u200F\u206C\u206A\u200F\u200D\u200D\u206C\u200F\u200E\u206A\u200E\u200E\u200F\u206F\u206A\u202E(string, string)
        {
        }

        // Token: 0x06000062 RID: 98 RVA: 0x00007C58 File Offset: 0x00006058
        static void \u206E\u206A\u200D\u202C\u202A\u200B\u202C\u200E\u206A\u202E\u200B\u202B\u206B\u200C\u200B\u200D\u202C\u200B\u202C\u202C\u206A\u200C\u206C\u200F\u202D\u200B\u206E\u200B\u206A\u206C\u200F\u200D\u206B\u202D\u202D\u200C\u206F\u206F\u206F\u202E(string)
        {
            /*
An exception occurred when decompiling this method (06000062)

ICSharpCode.Decompiler.DecompilerException: Error decompiling System.Void ClassLibrary1.Class1::‍‬‪​‬‎‮​‫‌​‍‬​‬‬‌‏‭​​‏‍‭‭‌‮(System.String)

 ---> System.ArgumentOutOfRangeException: Non-negative number required. (Parameter 'length')
   at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
   at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length)
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.StackSlot.ModifyStack(StackSlot[] stack, Int32 popCount, Int32 pushCount, ByteCode pushDefinition) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 48
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.StackAnalysis(MethodDef methodDef) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 387
   at ICSharpCode.Decompiler.ILAst.ILAstBuilder.Build(MethodDef methodDef, Boolean optimize, DecompilerContext context) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\ILAst\ILAstBuilder.cs:line 269
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(IEnumerable`1 parameters, MethodDebugInfoBuilder& builder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 112
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(MethodDef methodDef, DecompilerContext context, AutoPropertyProvider autoPropertyProvider, IEnumerable`1 parameters, Boolean valueParameterIsKeyword, StringBuilder sb, MethodDebugInfoBuilder& stmtsBuilder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 88
   --- End of inner exception stack trace ---
   at ICSharpCode.Decompiler.Ast.AstMethodBodyBuilder.CreateMethodBody(MethodDef methodDef, DecompilerContext context, AutoPropertyProvider autoPropertyProvider, IEnumerable`1 parameters, Boolean valueParameterIsKeyword, StringBuilder sb, MethodDebugInfoBuilder& stmtsBuilder) in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstMethodBodyBuilder.cs:line 92
   at ICSharpCode.Decompiler.Ast.AstBuilder.<>c__DisplayClass90_0.<AddMethodBody>b__0() in D:\a\dnSpy\dnSpy\Extensions\ILSpy.Decompiler\ICSharpCode.Decompiler\ICSharpCode.Decompiler\Ast\AstBuilder.cs:line 1519
*/;
        }
    }
}

보는 바와 같이, ICSharpCode.Decompiler가 해석할 수 없는 메타데이터로 인해 (Obfuscation Exclude=true를 설정했던) MyPrivateMethod2 메서드를 제외한 모든 메서드들의 소스 코드가 보이지 않습니다.

public이 아닌 "MyPrivateMethod" 메서드의 이름도 "\u202A\u206E\u202D...[생략]...\u200D\u202E" 식의 이름으로 바뀌어서 이게 어떤 역할을 하는 메서드인지 짐작조차 안 됩니다.

뭐, 이 정도면 대충 난독화 도구에 대한 기능을 아시겠죠? ^^




참고로, (단순히 이름 바꾸기가 아닌) 여러 protection 기능을 가능하게 만들 수 있었던 것은 <Module> 클래스의 기여가 한몫했습니다.

닷넷 - <Module> 클래스의 용도
; https://www.sysnet.pe.kr/2/0/11335

C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)
; https://www.sysnet.pe.kr/2/0/12404




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







[최초 등록일: ]
[최종 수정일: 3/9/2024]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13609정성태4/27/202441닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024423닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024420닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024450닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024698닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024729오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024884닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024942닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024971닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024981닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024938닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024980닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024975닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241080닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241070닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241085닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241091닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241227C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241203닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241084Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241159닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241278닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241362오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241537Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241498Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...