Last active
February 4, 2020 20:42
-
-
Save toravir/4b6b7da70be03d37c1edfb44de2a49c4 to your computer and use it in GitHub Desktop.
Get Hypervisor Type (assumes you are running IN a vm) - does not check if it is running on bare metal..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import socket | |
import ctypes | |
from ctypes import c_uint32, c_int, c_long, c_ulong, c_size_t, c_void_p, POINTER, CFUNCTYPE | |
class CPUID_struct(ctypes.Structure): | |
_fields_ = [(r, c_uint32) for r in ("eax", "ebx", "ecx", "edx")] | |
def getHypervisorType(): | |
opc = [ | |
0x53, # push %rbx | |
0x89, 0xf0, # mov %esi,%eax | |
0x89, 0xd1, # mov %edx,%ecx | |
0x0f, 0xa2, # cpuid | |
0x89, 0x07, # mov %eax,(%rdi) | |
0x89, 0x5f, 0x04, # mov %ebx,0x4(%rdi) | |
0x89, 0x4f, 0x08, # mov %ecx,0x8(%rdi) | |
0x89, 0x57, 0x0c, # mov %edx,0xc(%rdi) | |
0x5b, # pop %rbx | |
0xc3 # retq | |
] | |
size = len(opc) | |
code = (ctypes.c_ubyte * size)(*opc) | |
libc = ctypes.cdll.LoadLibrary(None) | |
libc.valloc.restype = ctypes.c_void_p | |
libc.valloc.argtypes = [ctypes.c_size_t] | |
addr = libc.valloc(size) | |
if not addr: | |
raise MemoryError("Could not allocate memory") | |
libc.mprotect.restype = c_int | |
libc.mprotect.argtypes = [c_void_p, c_size_t, c_int] | |
ret = libc.mprotect(addr, size, 1 | 2 | 4) | |
if ret != 0: | |
raise OSError("Failed to set RWX") | |
ctypes.memmove(addr, code, size) | |
func_type = CFUNCTYPE(None, POINTER(CPUID_struct), c_uint32, c_uint32) | |
func_ptr = func_type(addr) | |
struct = CPUID_struct() | |
func_ptr(struct, 0x40000000, 0x0) | |
libc.free.restype = None | |
libc.free.argtypes = [c_void_p] | |
libc.free(addr) | |
oc1 = "%x" % socket.htonl(struct.ebx) | |
oc2 = "%x" % socket.htonl(struct.ecx) | |
oc3 = "%x" % socket.htonl(struct.edx) | |
hvSig = oc1.decode("hex")+oc2.decode("hex")+oc3.decode("hex") | |
if (hvSig == "VMWareVMWare") : | |
return "VMWare" | |
elif (hvSig == "KVMKVMKVM\x00\x00\x00"): | |
return "KVM" | |
elif (hvSig == "Microsoft Hv"): | |
return "HyperV" | |
elif (hvSig == "XenVMMXenVMM"): | |
return "Xen" | |
return hvSig | |
if __name__ == "__main__": | |
print(getHypervisorType()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment