Microsoft MVP성태의 닷넷 이야기
닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx) [링크 복사], [링크+제목 복사]
조회: 1915
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13005정성태3/17/20226199오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226204디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226353.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227127.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227490.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20227074.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226590.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226168.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210591오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202215712VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/20228019.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
12994정성태3/8/20227295오류 유형: 798. WinDbg - Failed to load data access module, 0x80004002
12993정성태3/4/20227129.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
12992정성태3/3/20228555.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제파일 다운로드1
12991정성태3/2/20227717.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
12990정성태3/2/20227317오류 유형: 797. msbuild - The BaseOutputPath/OutputPath property is not set for project '[...].vcxproj'
12989정성태3/2/20226848오류 유형: 796. mstest.exe - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.Tips.WebLoadTest.Tip
12988정성태3/2/20225806오류 유형: 795. CI 환경에서 Docker build 시 csproj의 Link 파일에 대한 빌드 오류
12987정성태3/1/20227301.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
12986정성태2/28/20228145.NET Framework: 1168. C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습 [1]
12985정성태2/28/20228070.NET Framework: 1167. C# -Version 1 Source Generator 실습
12984정성태2/24/20227145.NET Framework: 1166. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 filtering_video.c 예제 포팅
12983정성태2/24/20227236.NET Framework: 1165. .NET Core/5+ 빌드 시 runtimeconfig.json에 설정을 반영하는 방법
12982정성태2/24/20227157.NET Framework: 1164. HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
12981정성태2/23/20226753VC++: 154. C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문 [1]
12980정성태2/23/20227524.NET Framework: 1163. C# - 윈도우 환경에서 usleep을 호출하는 방법 [2]
... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...