Microsoft MVP성태의 닷넷 이야기
닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx) [링크 복사], [링크+제목 복사]
조회: 1917
글쓴 사람
정성태 (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)
13357정성태5/16/20233575.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233901DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233836.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234095.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233704.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234209VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233480오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233792.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233689.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234082.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233912오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235313.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236491.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234365디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234273.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234007닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234080오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234746닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234265닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234769Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234577.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234677.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234312Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233754Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233855Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233885오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...