Microsoft MVP성태의 닷넷 이야기
닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx) [링크 복사], [링크+제목 복사]
조회: 1921
글쓴 사람
정성태 (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)
13081정성태6/17/20226371.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226992개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224654오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226705.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20227030스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20226006Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226308.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226529Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226805Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227387스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227192오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229424.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20227924.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227244Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226576Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227256.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226784.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227202.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20228013.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
13061정성태5/16/20226821.NET Framework: 2013. C# - FILE_FLAG_OVERLAPPED가 적용된 파일의 읽기/쓰기 시 Position 관리파일 다운로드1
13060정성태5/15/20229303.NET Framework: 2012. C# - async/await 그리고 스레드 (3) Task.Delay 재현파일 다운로드1
13059정성태5/14/20227752.NET Framework: 2011. C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법 [1]파일 다운로드1
13058정성태5/13/20227657.NET Framework: 2010. C# - ThreadPool.SetMaxThreads 사용법
13057정성태5/12/20229334오류 유형: 812. 파이썬 - ImportError: cannot import name ...
13056정성태5/12/20226461.NET Framework: 2009. C# - async/await 그리고 스레드 (2) MyTask의 호출 흐름 [2]파일 다운로드1
13055정성태5/11/20229405.NET Framework: 2008. C# - async/await 그리고 스레드 (1) MyTask로 재현 [11]파일 다운로드1
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...