
Trap Flag
There is a Trap Flag in the Flags register. Bit number 8 of the EFLAGS register is the trap flag. When the Trap Flag is set, a SINGLE_STEP exception is generated.
Code Snippets
BOOL IsDebuggerPresent_TrapFlag()
{
__try
{
__asm
{
pushfd
or word ptr[esp], 0x100
popfd
nop
}
}
__except(1)
{
return FALSE;
}
return TRUE;
}
Description
Original source code available here: https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiDebug/TrapFlag.cpp
#include "pch.h"
#include "TrapFlag.h"
/*
This technique is similar to exceptions based debugger detections.
You enable the trap flag in the current process and check whether
an exception is raised or not. If an exception is not raised, you
can assume that a debugger has “swallowed” the exception for us,
and that the program is being traced. The beauty of this approach
is that it detects every debugger, user mode or kernel mode,
because they all use the trap flag for tracing a program.
Vectored Exception Handling is used here because SEH is an
anti-debug trick in itself.
*/
static BOOL SwallowedException = TRUE;
static LONG CALLBACK VectoredHandler(
_In_ PEXCEPTION_POINTERS ExceptionInfo
)
{
SwallowedException = FALSE;
if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP)
return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
BOOL TrapFlag()
{
PVOID Handle = AddVectoredExceptionHandler(1, VectoredHandler);
SwallowedException = TRUE;
#ifdef _WIN64
UINT64 eflags = __readeflags();
#else
UINT eflags = __readeflags();
#endif
// Set the trap flag
eflags |= 0x100;
__writeeflags(eflags);
RemoveVectoredExceptionHandler(Handle);
return SwallowedException;
}
Detection Rules
rule:
meta:
name: check for trap flag exception
namespace: anti-analysis/anti-debugging/debugger-detection
authors:
- michael.hunhoff@mandiant.com
scope: basic block
mbc:
- Anti-Behavioral Analysis::Debugger Detection [B0001]
references:
- https://github.com/LordNoteworthy/al-khaser/blob/master/al-khaser/AntiDebug/TrapFlag.cpp
examples:
- al-khaser_x86.exe_:0x431680
- al-khaser_x64.exe_:0x140030CB0
features:
- and:
- or:
- description: read/write EFLAGS register
- and:
- mnemonic: pushf
- mnemonic: popf
- and:
- mnemonic: pushfd
- mnemonic: popfd
- and:
- mnemonic: pushfq
- mnemonic: popfq
- or:
- description: set trap flag
- and:
- mnemonic: or
- number: 0x100
- and:
- mnemonic: bts
- number: 0x8