# Different implementations of these mac virtualization detection techniques were used in OSX/MacRansom.
# Objective-See's analysis of this malware can be found here: https://objective-see.com/blog/blog_0x1E.html
# I found his work incredibly helpful as I was researching macOS malware.
import sys
sys.path.insert(0, "../..")
from utils.print import *
from utils.utils import run_cmd


def check_hardware_model():
        """
        On a real Mac, when the system is queried for the model, it will return
        something like this: "hw.model: MacBookPro14,2", but on a VM it will
        return something like 'VMware7,1'
        """
        print_blue("Hardware Model Test...")
        hardware_model = run_cmd("sysctl hw.model").stdout.decode()
        if "Mac" not in hardware_model.split()[1]:
                print_red("Running on a VM.")
        else:
                print_green("Running on a real Mac.")


def check_logical_physical_cpu_ratio():
        """
        A ratio of logical CPUs to physical CPUs that equals 1 may indicate
        a virtualized Mac environment.

        Real Mac:
                $ sysctl -n hw.logicalcpu
                4
                $ sysctl -n hw.physicalcpu
                2

        In VM:
                $ sysctl -n hw.logicalcpu
                2
                $ sysctl -n hw.physicalcpu
                2
        """
        print_blue("Physical vs. Logical CPU Count Test...")
        logical_cpu_count = int(run_cmd("sysctl -n hw.logicalcpu").stdout.decode())
        physical_cpu_count = int(run_cmd("sysctl -n hw.physicalcpu").stdout.decode())

        if logical_cpu_count == physical_cpu_count:
                print_red("Running on a VM.")
        else:
                print_green("Running on a real Mac.")


def ioreg_check():
    """
    Uses ioreg command to check for references to any virtualization software
    in the macOS I/O Kit registry.

    You can find a real world example of this in OSX.FairyTale, which can be
    downloaded from the Objective-See archives here: https://objective-see[.]com/downloads/malware/FairyTale.zip

    WARNING: THIS LINK DOWNLOADS LIVE MALWARE.
    """
    print_blue("ioreg Test...")
    result = run_cmd("ioreg | grep -i -e \"vmware\" -e \"virtualbox\" -e \"parallels\" -e \"qemu\"").stdout.decode()
    if len(result) == 0:
        print_green("No virtualization software detected.")
    else:
        print_red("Virtualization software detected.")


def main():
        check_hardware_model()
        check_logical_physical_cpu_ratio()
        ioreg_check()


if __name__ == '__main__':
        main()
