How to detect if my application is running in a virtual machine?

Viewed 58616

How can I detect (.NET or Win32) if my application is running in a virtual machine?

11 Answers

Remember you should not just check popular VM model,manufacturer name from wmi, You should also check difference between reality and virtualization.
VM don't have much features.
1) check-if-cpu-temperature-information-is-available

wmic /namespace:\\root\WMI path MSAcpi_ThermalZoneTemperature get CurrentTemperature
//On Real PC
//CurrentTemperature
//3147

//On VM
//Node - Admin
//Error:
//Description not supported

Tested on vmware,virtualbox,windows server,app.any.run sandbox.

2) Win32_PortConnector

Get-WmiObject Win32_PortConnector
//On Vm it is null

//On real pc it looks something like that
Tag                         : Port Connector 0
ConnectorType               : {23, 3}
SerialNumber                :
ExternalReferenceDesignator :
PortType                    : 2

I have tested for 3 types - VirtualBox,Wmware and Huper-V

foreach (var mo in "Select * from Win32_ComputerSystem")
{
    var model = (string)mo["Model"];

    if (model == "VirtualBox" ||
        model == "Virtual Machine" ||
        model.StartsWith("VMware"))
    {
        return true;
    }
}
return false;

I wanted to make this configurable so I converted @RobSiklos answer to a WMI query. Now I can put the query in a config location and change it when needed.

private static bool IsVirtual()
{
    using (var searcher = new System
        .Management
        .ManagementObjectSearcher(@"SELECT * from Win32_ComputerSystem 
                                    WHERE (Manufacturer LIKE '%microsoft corporation%' AND Model LIKE '%virtual%')
                                    OR Manufacturer LIKE '%vmware%'
                                    OR Model LIKE '%VirtualBox%'"))
    {
        using (System.Management.ManagementObjectCollection items = searcher.Get())
        {
            if (items.Count > 0)
            {
                return true;
            }
        }
    }

    return false;
}

WQL Reference:

https://docs.microsoft.com/en-us/windows/win32/wmisdk/wql-sql-for-wmi

Related