Is there a way to identify, from within a VM, that your code is running inside a VM?
I guess there are more or less easy ways to identify specific VM systems, especi
A lot of the research on this is dedicated to detecting so-called "blue pill" attacks, that is, a malicious hypervisor that is actively attempting to evade detection.
The classic trick to detect a VM is to populate the ITLB, run an instruction that must be virtualized (which necessarily clears out such processor state when it gives control to the hypervisor), then run some more code to detect if the ITLB is still populated. The first paper on it is located here, and a rather colorful explanation from a researcher's blog and alternative Wayback Machine link to the blog article (images broken).
Bottom line from discussions on this is that there is always a way to detect a malicious hypervisor, and it's much simpler to detect one that isn't trying to hide.
You might be able to identify whether you're in a virtual machine by looking at the MAC address of your network connection. Xen for example typically recommends using a specific range of addresses 00:16:3e:xx:xx:xx.
This isn't guaranteed as it's up to the administrator of the system to specify what MAC address they like.
Red Hat has a program which detects which (if any) virtualization product it's being run under: virt-what.
Using a third-party-maintained tool such is this is a better strategy long-term than trying to roll your own detection logic: more eyes (testing against more virtualization products), etc.
I once ran across an assembly code snippet that told you if you were in a VM....I googled but couldn't find the original article.
I did find this though: Detect if your program is running inside a Virtual Machine.
Hope it helps.
In most cases, you shouldn't try to. You shouldn't care if someone is running your code in a VM, except in a few specific cases.
If you need to, in Linux the most common way is to look at /sys/devices/virtual/dmi/id/product_name
, which will list the name of the laptop/mainboard on most real systems, and the hypervisor on most virtual systems. dmidecode | grep Product
is another common method, but I think that requires root access.
One good example is that apparently doing a WMI query for the motherboard manufacturer, and if it returns "Microsoft" you're in a VM. Thought I believe this is only for VMWare. There are likely different ways to tell for each VM host software.
This article here http://blogs.technet.com/jhoward/archive/2005/07/26/407958.aspx has some good suggestions and links to a couple of ways to detect if you are in a VM (VMWare and VirtualPC at least).