Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [링크 복사], [링크+제목 복사],
조회: 6696
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# / Visual C++ - Control Flow Guard (CFG) 활성화

CFG라는 기술이 있군요. ^^

Control Flow Guard for platform security
; https://learn.microsoft.com/en-us/windows/win32/secbp/control-flow-guard

기존의 /GS (Buffer Security Check), Data Execution Prevention (DEP), Address Space Layout Randomization (ASLR)로도, 시중에서 흔하게 구할 수 있는 해킹 서적의 예제들이 실습이 안 될 정도로 보안이 강화됐는데요, 그런데 이제는 Indirect Call, (쉬운 예로) 코드상 함수 포인터를 이용한 호출까지도 대상 주소가 적법한지를 체크하는 기능이 추가됐습니다.

이를 구현하기 위해, 컴파일러와 운영체제 양측의 지원이 필요한데요, Visual C++ 컴파일러의 경우 "C/C++ > Code Generation > Control Flow Guard" 옵션을 활성화하면 됩니다. 유의해야 할 점은, Release 모드에서만 켜는 것이 좋은데, Debug 모드에서 키게 되면 다른 옵션(Program Database for Edit And Continue)과의 충돌로 빌드가 안 됩니다.

cl : command line  error D8016: '/ZI' and '/guard:cf' command-line options are incompatible

(EnC 옵션이 필요하지 않다면 Debug에서도 /Zi + /guard:cf 옵션을 사용하면 됩니다.)

구체적으로 어떻게 동작하는지에 대해서는, 문서에 있는 한 장의 그림으로 잘 설명하고 있습니다.

cfg_1.jpg

이로 인해 발생하는 뚜렷한 차이점이라면, cfg가 켜져 있는 경우 대상 함수를 호출하기 전에 미리 (fail-fast) 실패해버린다는 점입니다.




실제로 Visual C++ 컴파일러가 어떻게 대응하는지를 간단하게 살펴보겠습니다. ^^

#include <Windows.h>

typedef BOOL(WINAPI* BEEPPROC)(DWORD, DWORD);

int main()
{
    BEEPPROC pfn = (BEEPPROC)GetProcAddress(LoadLibrary(L"kernel32.dll"), "Beep");
    pfn(1000, 1000);
}

위의 예제를 cfg 옵션 없이 컴파일하면 기계어로 다음과 같은 코드가 생성됩니다.

    11:     pfn(1000, 1000);
00007FF6A3D114E4 BA E8 03 00 00       mov         edx,3E8h  
00007FF6A3D114E9 B9 E8 03 00 00       mov         ecx,3E8h  
00007FF6A3D114EE FF 54 24 20          call        qword ptr [pfn]  
00007FF6A3D114F2 90                   nop  

call [pfn], 즉 indirect call을 그대로 호출하고 있는데요, 이를 cfg 옵션을 켜고 컴파일하면 다음과 같이 변경됩니다.

    11:     pfn(1000, 1000);
00007FF62CC11EC4 48 8B 44 24 20       mov         rax,qword ptr [pfn]  
00007FF62CC11EC9 48 89 44 24 28       mov         qword ptr [rsp+28h],rax  
00007FF62CC11ECE BA E8 03 00 00       mov         edx,3E8h  
00007FF62CC11ED3 B9 E8 03 00 00       mov         ecx,3E8h  
00007FF62CC11ED8 48 8B 44 24 28       mov         rax,qword ptr [rsp+28h]  
00007FF62CC11EDD FF 15 2D 01 01 00    call        qword ptr [__guard_dispatch_icall_fptr (07FF62CC22010h)]  
00007FF62CC11EE3 90                   nop  

(아하... 어쩌다 windbg로 역어셈블 코드를 보면 나오던 __guard_dispatch_icall_fptr이 바로 cfg 옵션으로 추가된 코드였었던 것입니다.)

문제를 재현하기 위해 코드를 다음과 같이 바꾸고 실행하면,

BEEPPROC pfn = (BEEPPROC)GetProcAddress(LoadLibrary(L"kernel32.dll"), "Beep");
pfn = (BEEPPROC)0x00007FF091AD03A0;
pfn(1000, 1000);

cfg가 활성화된 경우 LdrpDispatchUserCallTarget에서 예외가 발생합니다.

    ntdll.dll!LdrpDispatchUserCallTarget()  Unknown
>    ConsoleApplication1.exe!main() Line 12  C++
    ConsoleApplication1.exe!invoke_main() Line 79   C++
...[생략]...

이때의 이벤트 로그를 보면, "Exception code: 0xc0000409 (STATUS_FAIL_FAST_EXCEPTION)"으로 나옵니다. 반면 cfg가 꺼진 상태라면 call stack이 이렇게 나오는데요,

    00007ff091ad03a0()  Unknown
>    ConsoleApplication1.exe!main() Line 12  C++
    ConsoleApplication1.exe!invoke_main() Line 79   C++

그러니까, 명시된 주소로 call을 했고 그 내부의 기계어 코드가 정상적이지 않을 것이므로 AV(Access Violation) 예외가 발생하게 됩니다. 따라서 이벤트 로그에도 "Exception code: 0xc0000005"로 나옵니다.

위의 경우에는 임의의 주소를 지정했지만, 실제로는 (dumpbin으로 확인할 수 있는) Guard CF Function Table에 등록돼 있지 않은 주소는 모두 invalid 주소로 판정하고 실패하는 것으로 보입니다. 보다 구체적인 정보는 blackhat 문서를 참고하세요.)




참고로 .NET App은 어떻게 하고 있을까요? ^^

우선, dotnet.exe 및 관련 바이너리(clrjt.dll)을 보면 CFG 컴파일러 스위치가 적용된 것을 확인할 수 있습니다.

C:temp> dumpbin /headers /loadconfig "C:\Program Files\dotnet\dotnet.exe"
Microsoft (R) COFF/PE Dumper Version 14.40.33811.0
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file C:\Program Files\dotnet\dotnet.exe

PE signature found

File Type: EXECUTABLE IMAGE

...[생략]...

OPTIONAL HEADER VALUES
             20B magic # (PE32+)
           14.40 linker version
            DA00 size of code
           14200 size of initialized data
               0 size of uninitialized data
            9790 entry point (0000000140009790)
            1000 base of code
       140000000 image base (0000000140000000 to 0000000140024FFF)
            1000 section alignment
             200 file alignment
            6.00 operating system version
            0.00 image version
            6.00 subsystem version
               0 Win32 version
           25000 size of image
             400 size of headers
           2671E checksum
               3 subsystem (Windows CUI)
            C160 DLL characteristics
                   High Entropy Virtual Addresses
                   Dynamic base
                   NX compatible
                   Control Flow Guard
                   Terminal Server Aware
          180000 size of stack reserve
            1000 size of stack commit
          100000 size of heap reserve
            ...[생략]...

  Section contains the following load config:

            00000140 size
                   0 time date stamp
                0.00 Version
            ...[생략]...
    000000014000F328 Guard CF address of check-function pointer
    000000014000F338 Guard CF address of dispatch-function pointer
    000000014000F420 Guard CF function table
                  1E Guard CF function count
            10417500 Guard Flags
                       CF instrumented
                       FID table present
                       Protect delayload IAT
                       Delayload IAT in its own section
                       Export suppression info present
                       Long jump target table present
                       EH Continuation table present
                0000 Code Integrity Flags
                0000 Code Integrity Catalog
            00000000 Code Integrity Catalog Offset
            00000000 Code Integrity Reserved
    0000000000000000 Guard CF address taken IAT entry table
                   0 Guard CF address taken IAT entry count
    0000000000000000 Guard CF long jump target table
                   0 Guard CF long jump target count
    0000000000000000 Dynamic value relocation table
    0000000000000000 Hybrid metadata pointer
    0000000000000000 Guard RF address of failure-function
    0000000000000000 Guard RF address of failure-function pointer
            00000000 Dynamic value relocation table offset
                0000 Dynamic value relocation table section
                0000 Reserved2
    0000000000000000 Guard RF address of stack pointer verification function pointer
            00000000 Hot patching table offset
                0000 Reserved3
    0000000000000000 Enclave configuration pointer
    0000000140013034 Volatile metadata pointer
    000000014000F3F0 Guard EH continuation table
                   9 Guard EH continuation count
    000000014000F330 Guard XFG address of check-function pointer
    000000014000F340 Guard XFG address of dispatch-function pointer
    000000014000F348 Guard XFG address of dispatch-table-function pointer
    000000014000F350 CastGuard OS determined failure mode
    000000014000F358 Guard memcpy function pointer

            ...[생략]...

c:\temp> dumpbin /headers /loadconfig "C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\clrjit.dll"
Microsoft (R) COFF/PE Dumper Version 14.40.33811.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\clrjit.dll

PE signature found

File Type: DLL

            ...[생략]...

OPTIONAL HEADER VALUES
             20B magic # (PE32+)
            ...[생략]...
               2 subsystem (Windows GUI)
            4160 DLL characteristics
                   High Entropy Virtual Addresses
                   Dynamic base
                   NX compatible
                   Control Flow Guard
          100000 size of stack reserve
            ...[생략]...

        00000001 extended DLL characteristics
                   CET compatible

  Section contains the following load config:

            00000140 size
            ...[생략]...
    0000000000000000 Edit List
    000000018019F040 Security Cookie
    0000000180166470 Guard CF address of check-function pointer
    0000000180166480 Guard CF address of dispatch-function pointer
    0000000180166550 Guard CF function table
                  E7 Guard CF function count
            10417500 Guard Flags
                       CF instrumented
                       FID table present
                       Protect delayload IAT
                       Delayload IAT in its own section
                       Export suppression info present
                       Long jump target table present
                       EH Continuation table present
                0000 Code Integrity Flags
                0000 Code Integrity Catalog
            ...[생략]...

하지만, JIT 컴파일이 된 코드에는 CFG가 적용되지 않은 듯합니다.

namespace ConsoleApp1;

internal class Program
{
    static unsafe void Main(string[] args)
    {
        delegate* unmanaged[Stdcall]<int, bool, int> sleepExFunc = (delegate* unmanaged[Stdcall]<int, bool, int>)0x00007FF091AD03A0;
        sleepExFunc(2000, false);
    }
}

위의 코드를 실행해 보면, 0x00007FF091AD03A0 주소에서 AV(0xc0000005) 예외가 발생합니다.

물론, 닷넷 코드에서 저렇게 native 주소를 직접 호출하는 코드를 넣는 경우는 거의 없을 것이므로, CFG 여부에 따른 차이가 크진 않을 것입니다.




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







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

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

비밀번호

댓글 작성자
 



2024-09-17 07시42분
The case of the fail-fast crashes coming from the power management system
; https://devblogs.microsoft.com/oldnewthing/20240913-00/?p=110257

---------------------------

A quick introduction to return address protection technologies (Intel Control-flow Enforcement Technology (CET))
; https://devblogs.microsoft.com/oldnewthing/20241015-00/?p=110374

Effects of classic return address tricks on hardware-assisted return address protection
; https://devblogs.microsoft.com/oldnewthing/20241016-00/?p=110378
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13917정성태4/30/202544VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/2025446디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20251652닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20251965디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251204오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/2025863닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251091오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20251257디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20251725닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20252138닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20251933VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20252189닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20252217Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20251901디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20251522VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20251737개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20252112Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20252346스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251806스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20252124오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20252367닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20252178Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20252220Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20252250Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20252197Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...