Q:

Timing checks for anti-VM not working well? 

Does anyone know if timing check is still working to detect virtual environment?  I tried using rdtsc instruction to get cpu cycles and compare the results between real linux machine and linux running on virtualbox.  But the results seems to be unstable.  Sometimes, the cpu cycle from real machine even larger than in virtualbox.  Does this technique assume the hardware like cpu speed is the same?  If so, I am confused how it really works.  I cannot even find the obvious boundary between real and virtual environment.  Does anyone have an idea what might be wrong?  Here is my implementation:
#define rdtsc(low,high) \
    asm volatile ("rdtsc" : "=a" (low), "=d" (high))

typedef struct {
    int lo;
    int hi;
} longpair;

typedef union {
    longpair ll;
    long long t;    
} timestamp;

void test(){
  printf("test");
}
int main(int argc, char* argv[])
{
  timestamp a,b,c;
  int i;

  rdtsc(a.ll.lo,a.ll.hi);
  test();
  rdtsc(b.ll.lo,b.ll.hi);
  c.t = b.t-a.t;
}

Some results on virtualbox are:
c(hi) = 0   c(lo) = 36162
c(hi) = 0   c(lo) = 41468
c(hi) = 0   c(lo) = 85921
c(hi) = 0   c(lo) = 38840
c(hi) = 0   c(lo) = 24126

Some in real machine are:
c(hi) = 0   c(lo) = 52045
c(hi) = 0   c(lo) = 48382
c(hi) = 0   c(lo) = 47719
c(hi) = 0   c(lo) = 48535
c(hi) = 0   c(lo) = 58879

Actually, I do not know why some resutls in virtualbox is even lower than real machine.  By the way, I test the virtualbox and real environment in two computers with, maybe different hardware configurations.  I do not know if that's the reason for these results.  If so, is  there a way to improve that?  Thanks. 

A:

You can't detect virtualization by measuring the elapsed time of one kind of operation - given the vast number of different CPUs, concurrent workloads, etc.  you have no way to know what the expected time should be.  Furthermore, with modern hardware virtualization (VT-x and the like) there is not necessarily any significant slowdown for ordinary code running in a VM vs. directly on hardware. 
As the paper Virtualization Detection: New Strategies and Their Effectiveness explains, one technique to detect the presence of virtualization is to compare the run-time of two operations that should take a similar amount of time in the absence of virtualization but which take different amounts of time with virtualization.  The paper gives the example of a no-op vs. the cpuid instruction.  On physical hardware, cpuid will take about the same amount of time as a no-op.  In a virtualized environment, cpuid will normally trap to the hypervisor (so that the hypervisor can potentially modify the results) and thus take much longer than a no-op.