如何检测我的应用程序是否在虚拟机中运行?

时间:2009-01-31 06:01:43

标签: .net winapi virtualization

如果我的应用程序在虚拟机中运行,我如何检测(.NET或Win32)?

10 个答案:

答案 0 :(得分:39)

这就是我使用的:

using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
{
  using (var items = searcher.Get())
  {
    foreach (var item in items)
    {
      string manufacturer = item["Manufacturer"].ToString().ToLower();
      if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
          || manufacturer.Contains("vmware")
          || item["Model"].ToString() == "VirtualBox")
      {
        return true;
      }
    }
  }
}
return false;

编辑2014-12-02 :更新了代码,使其不再将Microsoft Surface Pro检测为VM。感谢Erik Funkenbusch指出这一点。

编辑2017-06-29 :更新了代码,以便它还会检查HypervisorPresent属性的值。

编辑2018-02-05 :已删除对HypervisorPresent属性的检查,因为它不正确。如果在超V服务器上的主机O / S上运行,则此属性可以返回true。

答案 1 :(得分:19)

根据Virtual PC Guy的博文“Detecting Microsoft virtual machines”,您可以使用WMI检查主板的制造商。在PowerShell中:

 (gwmi Win32_BaseBoard).Manufacturer -eq "Microsoft Corporation"

答案 2 :(得分:12)

以下是一种方法的示例。它只适用于微软的Virtual PC和VMWare,但它是一个开始: http://www.codeproject.com/KB/system/VmDetect.aspx

答案 3 :(得分:3)

Jay Abuzi在powershell中展示了解决方案。这与c#函数相同:

   /// <summary>
    /// Detect if this OS runs in a virtual machine
    /// 
    /// http://blogs.msdn.com/b/virtual_pc_guy/archive/2005/10/27/484479.aspx
    /// 
    /// Microsoft themselves say you can see that by looking at the motherboard via wmi
    /// </summary>
    /// <returns>false</returns> if it runs on a fysical machine
    public bool DetectVirtualMachine()
    {
        bool result = false;
      const  string  MICROSOFTCORPORATION ="microsoft corporation";
        try
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_BaseBoard");

            foreach (ManagementObject queryObj in searcher.Get())
            {
               result =  queryObj["Manufacturer"].ToString().ToLower() == MICROSOFTCORPORATION.ToLower();
            }
            return result;
        }
        catch (ManagementException ex)
        {
            return result;
        }
    }

答案 4 :(得分:3)

此C函数将检测VM Guest OS: (在Windows上测试,使用Visual Studio编译)

#include <intrin.h>

    bool isGuestOSVM()
    {
        unsigned int cpuInfo[4];
        __cpuid((int*)cpuInfo,1);
        return ((cpuInfo[2] >> 31) & 1) == 1;
    }

答案 5 :(得分:1)

我发现找出我的C#应用​​程序是否在vmware VM上运行的最简单方法是检查NIC卡的MAC地址。如果它是VMware VM,它将永远是:00:50:56:XX:YY:ZZ

您可以通过网卡枚举as resolved here.

答案 6 :(得分:1)

public static bool isVirtualMachine()
{
    const string MICROSOFTCORPORATION = "microsoft corporation";
    const string VMWARE = "vmware"; 

    foreach (var item in new ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
    {
        string manufacturer = item["Manufacturer"].ToString().ToLower();
        // Check the Manufacturer (eg: vmware, inc)
        if (manufacturer.Contains(MICROSOFTCORPORATION) || manufacturer.Contains(VMWARE))  
        {
            return true;
        }

        // Also, check the model (eg: VMware Virtual Platform)
        if (item["Model"] != null)
        {
            string model = item["Model"].ToString().ToLower();
            if (model.Contains(MICROSOFTCORPORATION) || model.Contains(VMWARE)) 
            {
                return true;
            }
        }
    }
    return false;
}

答案 7 :(得分:1)

对于较低级别的测试,我建议查看ScoopyNG [1]。它是一系列已知的低水平,良好工作的vm检测方法,尽管有点过时了。

如果你真的想要依赖其他东西,比如已安装的工具(VM * Additions),那么这些更容易被假冒&#34;假的&#34;。

这篇[2]博客文章也有一个非常好的概述,从低级asm的东西,检查特定的DLL,文件路径和注册表项来检查。

[1] http://trapkit.de/research/vmm/scoopyng/index.html

[2] http://securitykitten.github.io/vm-checking-and-detecting/

答案 8 :(得分:1)

此C ++代码将检测vmware产品,如express,esx,fusion或workstation

// VMWareDetector.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include <conio.h>
void CheckVM(void); 
int main()
{
    CheckVM(); 
    _getch(); 
    return 0;
}

void CheckVM(void)
{
    unsigned int    a, b;

    __try {
        __asm {

            // save register values on the stack
            push eax
            push ebx
            push ecx
            push edx

            // perform fingerprint
            mov eax, 'VMXh' // VMware magic value (0x564D5868)
            mov ecx, 0Ah // special version cmd (0x0a)
            mov dx, 'VX' // special VMware I/O port (0x5658)

            in eax, dx // special I/O cmd

            mov a, ebx // data 
            mov b, ecx // data (eax gets also modified
                       // but will not be evaluated)

                       // restore register values from the stack
                       pop edx
                       pop ecx
                       pop ebx
                       pop eax
        }
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {}
    printf("\n[+] Debug : [ a=%x ; b=%d ]\n\n", a, b);
    if (a == 'VMXh') { // is the value equal to the VMware magic value?
        printf("Result  : VMware detected\nVersion : ");
        if (b == 1)
            printf("Express\n\n");
        else if (b == 2)
            printf("ESX\n\n");
        else if (b == 3)
            printf("GSX\n\n");
        else if (b == 4)
            printf("Workstation\n\n");
        else
            printf("unknown version\n\n");
    }
    else
        printf("Result  : Not Detected\n\n");
}

答案 9 :(得分:0)

请记住,您不仅应该检查流行的VM模型,wmi的制造商名称,还应该检查现实与虚拟化之间的区别。
VM没有太多功能。
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

在vmware,virtualbox,Windows服务器,app.any.run沙箱上进行了测试。

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

相关问题