您的位置:首页 > 其它

RDTSC指令 用于anti debug

2014-02-23 22:43 344 查看
1.使用RDTSC来anti-debug
以下内如引用intel指令手册。

//引用开始

RDTSC—Read Time-Stamp Counter

Opcode Instruction Description
0F 31 RDTSC Read time-stamp counter into EDX:EAX

Description
Loads the current value of the processor’s time-stamp counter into the EDX:EAX registers. The
time-stamp counter is contained in a 64-bit MSR. The high-order 32 bits of the MSR are loaded
into the EDX register, and the low-order 32 bits are loaded into the EAX register. The processor
increments the time-stamp counter MSR every clock cycle and resets it to 0 whenever the
processor is reset.
The time stamp disable (TSD) flag in register CR4 restricts the use of the RDTSC instruction.
When the TSD flag is clear, the RDTSC instruction can be executed at any privilege level; when
the flag is set, the instruction can only be executed at privilege level 0. The time-stamp counter
can also be read with the RDMSR instruction, when executing at privilege level 0.
The RDTSC instruction is not a serializing instruction. Thus, it does not necessarily wait until
all previous instructions have been executed before reading the counter. Similarly, subsequent
instructions may begin execution before the read operation is performed.
This instruction was introduced into the IA-32 Architecture in the Pentium processor.

Operation
IF (CR4.TSD ← 0) OR ((CR4.TSD ← 1) AND (CPL=0))
THEN
EDX:EAX ← TimeStampCounter;
ELSE (* CR4 is 1 and CPL is 1, 2, or 3 *)
#GP(0)
FI;

Flags Affected
None.

Protected Mode Exceptions
#GP(0) If the TSD flag in register CR4 is set and the CPL is greater than 0.

Real-Address Mode Exceptions
#GP If the TSD flag in register CR4 is set.

Virtual-8086 Mode Exceptions
#GP(0) If the TSD flag in register CR4 is set.

英文太多,我也看不懂多少,大概的意思是这样,将计算机启动以来的CPU运行周期数放到EDX:EAX里面,EDX是高位,EAX是低位。
CPU运行周期数指的是CPU的一个时钟触发吧,就是应该是一个上升沿或者一个下降沿表示一个周期。
有一点你应该明白
周期数/CPU主频=CPU通电以来的执行秒数,也就是GetTickcount干的事情。
或者这样说使用两次RDTSC,把两次的结果相减,得到“间隔周期数”,间隔周期数/CPU主频=CPU执行这两条指令间的秒数
这样我们就能使用来做一些anti了
基本的思想是:
RDTSC
mov temp_1,eax ;edx估计不会改变
RDTSC
sub eax,temp_1
cmp eax,isDebug_number ;isDebug_number是一个自定义的小数目作为判断临界值
jg @F
;如果比isDebug_number小,说明没有Debug
@@:
;如果比 isDebug_number大,说明有Debug

因为在使用Debug的单步跟踪的时候,我们就算怎么迅速的press F7(F8)需要的时间也大概要0.0几秒吧,如果让CPU来执行这些指令那么就可能只用0.0000000几秒....

所以说这个isDebug_number临界值还是很好选取的!

好了基本上可以来总结一下了:

RDTSC的anti就是象GetTickcount一样,使用判断两个指令间执行的周期数(时间)来判断是否有debug,因为我们确信cpu执行的周期数(时间)会远远低于某个值,解除他的办法也很简单,比如说你可以找到cmp eax,isDebug_number这一句,然后就不用我说什么了。
附:
GetTickcount返回的是本次Windows启动以来的ms数,得到的时间数值直接在eax中返回,由于这是一个32位的整数,可以表示的范围是1~ffffffffh ms,所以当Windows连续运行49.7天以后,计数器会清零并重新开始。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RDTSC指令