Microsoft MVP성태의 닷넷 이야기
Windows: 165. AcLayers의 API 후킹과 FaultTolerantHeap [링크 복사], [링크+제목 복사]
조회: 11277
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

AcLayers의 API 후킹과 FaultTolerantHeap

FaultTolerantHeap을 살펴보기 위해 일부러 CRT로부터 할당받은 메모리의 헤더를 망가뜨리는 코드를,

Need Sample code for heap corruption in C++
; https://stackoverflow.com/questions/35123189/need-sample-code-for-heap-corruption-in-c

// Visual C++
// ...[생략]...

void ReleaseBuf(char* pBuffer)
{
    delete[] pBuffer;
}

char* AllocBuf()
{
    char* cp = new char[10];
    (*(cp - 5))++;

    return cp;
}

char* _p;

__declspec(dllexport) int __fastcall UseCRTHeap(int value)
{
    if (value == 0)
    {
        _p = AllocBuf();
    }
    else if (value == 1)
    {
        ReleaseBuf(_p);
    }

    return 0;
}

// C#
class Program
{

    [DllImport("Win32Project1.dll")]
    internal static extern int UseCRTHeap(int value);

    static unsafe void Main(string[] args)
    {
        Console.WriteLine("Allocating...");
        UseCRTHeap(0);
        Console.WriteLine("Allocated");

        Console.WriteLine("Releasing...");
        UseCRTHeap(1);
        Console.WriteLine("Released...");
    }
}

사용한 프로그램을 실행하면 최초에는 다음과 같이 3개의 이벤트 로그가 생성됩니다.

Log Name:      Application
Source:        Application Error
Date:          2019-11-14 오전 10:21:10
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      TESTPC
Description:
Faulting application name: ConsoleApplication1.exe, version: 1.0.0.0, time stamp: 0x5dcca494
Faulting module name: ntdll.dll, version: 10.0.18362.418, time stamp: 0x99ca0526
Exception code: 0xc0000374
Fault offset: 0x00000000000f9269
Faulting process id: 0x7200
Faulting application start time: 0x01d59a89cc5d5fd2
Faulting application path: c:\temp\ConsoleApplication1.exe
Faulting module path: C:\WINDOWS\SYSTEM32\ntdll.dll
Report Id: 50e4663e-286d-48dc-aba8-696a11188ac6
Faulting package full name: 
Faulting package-relative application ID: 

Log Name:      Application
Source:        Windows Error Reporting
Date:          2019-11-14 오전 10:21:12
Event ID:      1001
Task Category: None
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      TESTPC
Description:
Fault bucket 2118073145157684012, type 4
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: ConsoleApplication1.exe
P2: 1.0.0.0
P3: 5dcca494
P4: StackHash_b2bc
P5: 10.0.18362.418
P6: 99ca0526
P7: c0000374
P8: PCH_03_FROM_ntdll+0x000000000009CC14
P9: 
P10: 

Attached files:
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER84F4.tmp.mdmp
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER8582.tmp.WERInternalMetadata.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER85A2.tmp.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER85A6.tmp.csv
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER85D6.tmp.txt

These files may be available here:
\\?\C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_ConsoleApplicati_75e6a768f43e63769fa883e35983a378d047bd80_6103db0b_e38e88b9-59cf-414d-aaa9-282f7a013f53

Analysis symbol: 
Rechecking for solution: 0
Report Id: 50e4663e-286d-48dc-aba8-696a11188ac6
Report Status: 268435456
Hashed bucket: c8396419a04467d1ed64e84db16b0b2c
Cab Guid: 0

Log Name:      Application
Source:        Windows Error Reporting
Date:          2019-11-14 오전 10:21:14
Event ID:      1001
Task Category: None
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      TESTPC
Description:
Fault bucket 1186916719236790934, type 5
Event Name: FaultTolerantHeap
Response: Not available
Cab Id: 1329775288456208175

Problem signature:
P1: ConsoleApplication1.exe
P2: 1.0.0.0
P3: 5DCCA494
P4: ffffbaad
P5: 
P6: 
P7: 
P8: 
P9: 
P10: 

Attached files:
\\?\C:\WINDOWS\SERVIC~1\LOCALS~1\AppData\Local\Temp\FTH84D5.tmp\fthempty.txt
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER84D6.tmp.WERInternalMetadata.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER84D7.tmp.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER84D9.tmp.csv
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WER84F9.tmp.txt
\\?\C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\WER88CF.tmp.WERDataCollectionStatus.txt

These files may be available here:

Analysis symbol: 
Rechecking for solution: 0
Report Id: e1740ff6-55b8-4d78-80c0-b80185bc9d28
Report Status: 268435464
Hashed bucket: 4c18d2a648f924301078c677b414ba96
Cab Guid: 94e535c5-8c62-4522-9274-4f9453865f2f

주의 깊게 보면, 3번째 로그의 "Event Name"이 "FaultTolerantHeap"인 것을 알 수 있습니다. 그런데, 이후 실행하게 되면 FaultTolerantHeap에 대한 이벤트 로그가 더 이상 생성이 안 됩니다. 재미있는 것은, 이렇게 몇 번 "FaultTolerantHeap"에 해당하는 비정상 종료 프로그램을 실행하다 보면 윈도우는 해당 프로그램을 다음의 레지스트리 경로에 등록하게 됩니다.

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
    Value name: c:\temp\ConsoleApplication1.exe
    Value type: REG_SZ
    Value data: FaultTolerantHeap

(또는, HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers)

만약, 운(?)이 따른다면 이후에는 비정상 종료를 하지 않을 가능성도 있습니다. 왜냐하면, 윈도우는 이런 유의 비정상 종료를 완화하기 위해 후킹을 제공하기 때문입니다. 실제로, AppCompatFlags에 등록되기 전에는 비정상 종료 시 메모리 덤프를 뜨게 되면 다음과 같은 식의 call stack을 보여줍니다.

ntdll!NtWaitForMultipleObjects+14 
KERNELBASE!WaitForMultipleObjectsEx+107 
KERNELBASE!WaitForMultipleObjects+e 
kernel32!WerpReportFaultInternal+51b 
kernel32!WerpReportFault+ac 
KERNELBASE!UnhandledExceptionFilter+3b8 
ntdll!RtlUserThreadStart$filt$0+a2 
ntdll!_C_specific_handler+96 
ntdll!RtlpExecuteHandlerForException+f 
ntdll!RtlDispatchException+219 
ntdll!KiUserExceptionDispatch+2e 
ntdll!RtlpFreeHeapInternal+65ed4 
ntdll!RtlFreeHeap+51 
ucrtbase!_free_base+1b 
Win32Project1!ExternC_FAST_Func_By_DEF+34 
DomainBoundILStubClass.IL_STUB_PInvoke(Int32)+76 
Program.Main(System.String[])+8b 
clr!CallDescrWorkerInternal+83 
clr!CallDescrWorkerWithHandler+4e 
clr!MethodDescCallSite::CallTargetWorker+102 
clr!RunMain+25f 
clr!Assembly::ExecuteMainMethod+b7 
clr!SystemDomain::ExecuteMainMethod+643 
clr!ExecuteEXE+3f 
clr!_CorExeMainInternal+b2 
clr!CorExeMain+14 
mscoreei!CorExeMain+112 
mscoree!CorExeMain_Exported+6c 
kernel32!BaseThreadInitThunk+14 
ntdll!RtlUserThreadStart+21 

반면, 일단 윈도우가 FaultTolerantHeap 유형임을 알고 개입하기 시작하면 다음과 같이 AcLayers.dll의 함수가 중간에 들어가는 것을 볼 수 있습니다.

ntdll!NtWaitForMultipleObjects+14 
KERNELBASE!WaitForMultipleObjectsEx+107 
KERNELBASE!WaitForMultipleObjects+e 
kernel32!WerpReportFaultInternal+51b 
kernel32!WerpReportFault+ac 
KERNELBASE!UnhandledExceptionFilter+3b8 
ntdll!RtlUserThreadStart$filt$0+a2 
ntdll!_C_specific_handler+96 
ntdll!RtlpExecuteHandlerForException+f 
ntdll!RtlDispatchException+219 
ntdll!KiUserExceptionDispatch+2e 
ntdll!RtlSizeHeap+1af 
AcLayers!NS_FaultTolerantHeap::APIHook_RtlFreeHeap+146 
ucrtbase!_free_base+1b 
Win32Project1!ExternC_FAST_Func_By_DEF+34 
DomainBoundILStubClass.IL_STUB_PInvoke(Int32)+76 
Program.Main(System.String[])+8b 
clr!CallDescrWorkerInternal+83 
clr!CallDescrWorkerWithHandler+4e 
clr!MethodDescCallSite::CallTargetWorker+102 
clr!RunMain+25f 
clr!Assembly::ExecuteMainMethod+b7 
clr!SystemDomain::ExecuteMainMethod+643 
clr!ExecuteEXE+3f 
clr!_CorExeMainInternal+b2 
clr!CorExeMain+14 
mscoreei!CorExeMain+112 
mscoree!CorExeMain_Exported+6c 
kernel32!BaseThreadInitThunk+14 
ntdll!RtlUserThreadStart+21 

APIHook_RtlFreeHeap에서 할당된 Heap 크기를 알기 위해 RtlSizeHeap을 호출하는데, 아쉽게도 이번 오류는 Header 영역이 깨졌기 때문에 그런 시도조차 실패하게 된 것입니다.




그렇다면 다시 AcLayers의 개입을 없앨 수 있을까요? 제가 해본 바로는 "AppCompatFlags\Layers" 레지스트리에 등록된 것을 지운다고 해결되지는 않았습니다. 대신 해당 EXE를 다른 경로에 복사해 실행하면 다시 "FaultTolerantHeap" 이벤트 로그가 생성되었고 이후 마찬가지로 몇 번 실행하면 "AppCompatFlags\Layers" 레지스트리에 등록이 되었습니다. (물론, 다시 그 EXE의 실행에는 AcLayers가 개입합니다.)

검색해 보면, 아예 FTH 기능을 끄는 방법이 나옵니다.

Disabling a Shim
; https://learn.microsoft.com/en-us/archive/blogs/maartenb/disabling-a-shim

You can disable the whole shim engine through this setting from GPEdit.msc:

Administrative Templates \ Windows Components \ Application Compatibility \ Turn off Application Compatibility Engine

Setting it to enabled means that the Shim engine is off. Reboot and there you have it. No output in DebugView.

또한 다음의 글을 보면,

Fault Tolerant Heap
; https://learn.microsoft.com/en-us/windows/win32/win7appqual/fault-tolerant-heap

HKLM\Software\Microsoft\FTH 경로의 Enabled 값을 0으로 설정해도 FTH 기능을 시스템 전역적으로 끌 수 있다고 나옵니다.

참고로, 소개된 이벤트 로그 경로(Event Viewer > Applications and Services Logs > Microsoft > Windows > Fault-Tolerant-Heap)를 보면 FTH에 대해 "service started" / "service stopped" 이벤트들을 볼 수 있는데 NT Service처럼 내부적으로 다뤄지고 있는 듯한데 실제로 이를 제어할 수 있는 방법은 gpedit.msc와 레지스트리 설정 이외에는 없는 것 같습니다.

그리고 "Application Compatibility"에 등록된 항목들을 전부 초기화(reset) 할 수 있는 명령어를 소개하는데,

Rundll32.exe fthsvc.dll,FthSysprepSpecialize

(권장하지는 않지만) 실제로 저 명령을 내리면 "AppCompatFlags\Layers" 레지스트리 설정까지 전부 초기화되는 것을 볼 수 있습니다. 따라서 call stack에 보이던 AcLayers의 개입도 없어집니다.

이번엔 여기까지만! ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/7/2023]

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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232822닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232307Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232317Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232500Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232546닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232262개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232195개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232161개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232297닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232820닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232267개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232604개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232299개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232482닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232206닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232278닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...