Microsoft MVP성태의 닷넷 이야기
닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx) [링크 복사], [링크+제목 복사]
조회: 1910
글쓴 사람
정성태 (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)
13255정성태2/10/20234518오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234404Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235180Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20234004오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234458스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236277오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20235121오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234170오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235071VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234199개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234771.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234127VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234976디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234420디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233920디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234076디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233738디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235821.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235480.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235090개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234647개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235729개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237057오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234808스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233736오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234106개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...