def main(vm_name, guest_ip, host_ip, guest_primary_dns, path_logs):
    # Welcome
    print "\n--- AntiVMdetect by Mikael, @nsmfoo (modified by Jose Carlos R.) ---"
    print bcolors.OKGREEN + " [*]" + bcolors.ENDC + " Creating VirtualBox modifications .."

    dmi_info = {}

    for v in dmidecode.bios().values():
        if type(v) == dict and v["dmi_type"] == 0:
            dmi_info["DmiBIOSVendor"] = v["data"]["Vendor"]
            dmi_info["DmiBIOSReleaseDate"] = v["data"]["Relase Date"]
            dmi_info["DmiBIOSVersion"] = v["data"]["Version"]
            biosversion = v["data"]["BIOS Revision"]

    try:
        dmi_info["DmiBIOSReleaseMajor"], dmi_info["DmiBIOSReleaseMinor"] = biosversion.split(".", 1)
    except:
        dmi_info["DmiBIOSReleaseMajor"] = "** No value to retrieve **"
        dmi_info["DmiBIOSReleaseMinor"] = "** No value to retrieve **"

        # python-dmidecode does not currently reveal all values .. this is plan B
    dmi_firmware = commands.getoutput("dmidecode -t0")
    try:
        dmi_info["DmiBIOSFirmwareMajor"], dmi_info["DmiBIOSFirmwareMinor"] = (
            re.search("Firmware Revision: ([0-9A-Za-z. ]*)", dmi_firmware).group(1).split(".", 1)
        )
    except:
        dmi_info["DmiBIOSFirmwareMajor"] = "** No value to retrieve **"
        dmi_info["DmiBIOSFirmwareMinor"] = "** No value to retrieve **"

    for v in dmidecode.baseboard().values():
        if type(v) == dict and v["dmi_type"] == 2:
            serial_number = v["data"]["Serial Number"]
            dmi_info["DmiBoardVersion"] = v["data"]["Version"]
            if isinstance(v["data"]["Product Name"], int):
                dmi_info["DmiBoardProduct"] = str(v["data"]["Product Name"]) + " "
            else:
                dmi_info["DmiBoardProduct"] = v["data"]["Product Name"]
            dmi_info["DmiBoardVendor"] = v["data"]["Manufacturer"]

            # This is hopefully not the best solution ..
    try:
        s_number = []
        if serial_number:
            # Get position
            if "/" in serial_number:
                for slash in re.finditer("/", serial_number):
                    s_number.append(slash.start(0))
                    # Remove / from string
                    new_serial = re.sub("/", "", serial_number)
                    new_serial = serial_randomize(0, len(new_serial))
                    # Add / again
                for char in s_number:
                    new_serial = new_serial[:char] + "/" + new_serial[char:]
            else:
                new_serial = serial_randomize(0, len(serial_number))
        else:
            new_serial = "** No value to retrieve **"
    except:
        new_serial = "** No value to retrieve **"

    dmi_info["DmiBoardSerial"] = "string:" + new_serial

    # python-dmidecode does not reveal all values .. this is plan B
    dmi_board = commands.getoutput("dmidecode -t2")
    try:
        asset_tag = re.search("Asset Tag: ([0-9A-Za-z ]*)", dmi_board).group(1)
    except:
        asset_tag = "** No value to retrieve **"

    dmi_info["DmiBoardAssetTag"] = asset_tag

    try:
        loc_chassis = re.search("Location In Chassis: ([0-9A-Za-z ]*)", dmi_board).group(1)
    except:
        loc_chassis = "** No value to retrieve **"

    dmi_info["DmiBoardLocInChass"] = loc_chassis

    # Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
    board_dict = {
        "Unknown": 1,
        "Other": 2,
        "Server Blade": 3,
        "Connectivity Switch": 4,
        "System Management Module": 5,
        "Processor Module": 6,
        "I/O Module": 7,
        "Memory Module": 8,
        "Daughter board": 9,
        "Motherboard": 10,
        "Processor/Memory Module": 11,
        "Processor/IO Module": 12,
        "Interconnect board": 13,
    }
    try:
        board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
        board_type = str(board_dict.get(board_type))
    except:
        board_type = "** No value to retrieve **"

    dmi_info["DmiBoardBoardType"] = board_type

    for v in dmidecode.system().values():
        if type(v) == dict and v["dmi_type"] == 1:
            dmi_info["DmiSystemSKU"] = v["data"]["SKU Number"]
            system_family = v["data"]["Family"]
            system_serial = v["data"]["Serial Number"]
            dmi_info["DmiSystemVersion"] = "string:" + v["data"]["Version"]
            dmi_info["DmiSystemProduct"] = v["data"]["Product Name"]
            dmi_info["DmiSystemVendor"] = v["data"]["Manufacturer"]

    if not system_family:
        dmi_info["DmiSystemFamily"] = "Not Specified"
    else:
        dmi_info["DmiSystemFamily"] = system_family

        # Create a new UUID
    newuuid = str(uuid.uuid4())
    dmi_info["DmiSystemUuid"] = newuuid.upper()
    # Create a new system serial number
    dmi_info["DmiSystemSerial"] = "string:" + (serial_randomize(0, len(system_serial)))

    for v in dmidecode.chassis().values():
        dmi_info["DmiChassisVendor"] = v["data"]["Manufacturer"]
        chassi_serial = v["data"]["Serial Number"]
        dmi_info["DmiChassisVersion"] = v["data"]["Version"]
        dmi_info["DmiChassisType"] = v["data"]["Type"]

        # Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
    chassi_dict = {
        "Other": 1,
        "Unknown": 2,
        "Desktop": 3,
        "Low Profile Desktop": 4,
        "Pizza Box": 5,
        "Mini Tower": 6,
        "Tower": 7,
        "Portable": 8,
        "Laptop": 9,
        "Notebook": 10,
        "Hand Held": 11,
        "Docking Station": 12,
        "All in One": 13,
        "Sub Notebook": 14,
        "Space-saving": 15,
        "Lunch Box": 16,
        "Main Server Chassis": 17,
        "Expansion Chassis": 18,
        "SubChassis": 19,
        "Bus Expansion Chassis": 20,
        "Peripheral Chassis": 21,
    }
    dmi_info["DmiChassisType"] = str(chassi_dict.get(dmi_info["DmiChassisType"]))
    # python-dmidecode does not reveal all values .. this is plan B
    chassi = commands.getoutput("dmidecode -t3")
    try:
        dmi_info["DmiChassisAssetTag"] = re.search("Asset Tag: ([0-9A-Za-z ]*)", chassi).group(1)
    except:
        dmi_info["DmiChassisAssetTag"] = "** No value to retrieve **"

        # Create a new chassi serial number, added string to make it be taken as a string even if it's a number
    dmi_info["DmiChassisSerial"] = "string:" + str(serial_randomize(0, len(chassi_serial)))

    for v in dmidecode.processor().values():
        dmi_info["DmiProcVersion"] = v["data"]["Version"]
        dmi_info["DmiProcManufacturer"] = v["data"]["Manufacturer"]["Vendor"]
        # OEM strings
    try:
        for v in dmidecode.type(11).values():
            oem_ver = v["data"]["Strings"]["3"]
            oem_rev = v["data"]["Strings"]["2"]
    except:
        pass
    try:
        dmi_info["DmiOEMVBoxVer"] = oem_ver
        dmi_info["DmiOEMVBoxRev"] = oem_rev
    except:
        dmi_info["DmiOEMVBoxVer"] = "** No value to retrieve **"
        dmi_info["DmiOEMVBoxRev"] = "** No value to retrieve **"

        # Write all data collected so far to file
    file_name = "vboxmods-" + vm_name.replace(" ", "_") + ".sh"

    logfile = file(path_logs + "/" + file_name, "w+")
    logfile.write("# Generated on: " + time.strftime("%H:%M:%S") + "\n")

    for k, v in sorted(dmi_info.iteritems()):
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/pcbios/0/Config/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/pcbios/0/Config/'
                + k
                + "\t'"
                + v
                + "'\n"
            )
            # Disk information
    disk_dmi = {}
    try:
        if os.path.exists("/dev/sda"):
            # Disk serial
            disk_serial = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            # To avoid exceding 20 bytes serials
            if len(disk_serial) > 20:
                disk_dmi["SerialNumber"] = serial_randomize(0, 20)
            else:
                disk_dmi["SerialNumber"] = serial_randomize(0, len(disk_serial))
                # Check for HP Legacy RAID
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_serial = re.search("Serial number:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
                # To avoid exceding 20 bytes serials
                if len(disk_serial) > 20:
                    disk_dmi["SerialNumber"] = serial_randomize(0, 20)
                else:
                    disk_dmi["SerialNumber"] = serial_randomize(0, len(disk_serial))
            else:
                print bcolors.WARNING + "Install smartmontools: apt-get install smartmontools" + bcolors.ENDC
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Disk firmeware rev
    try:
        if os.path.exists("/dev/sda"):
            disk_fwrev = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'FwRev=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            disk_dmi["FirmwareRevision"] = disk_fwrev
            if len(disk_dmi["FirmwareRevision"]) < 8:
                disk_dmi["FirmwareRevision"] = disk_dmi["FirmwareRevision"][:8]
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_dmi["FirmwareRevision"] = (
                    re.search("Revision:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
                )
                if len(disk_dmi["FirmwareRevision"]) < 8:
                    disk_dmi["FirmwareRevision"] = disk_dmi["FirmwareRevision"][:8]
            else:
                print "Install smartmontools: apt-get install smartmontools"
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Disk Model number
    try:
        if os.path.exists("/dev/sda"):
            disk_modelno = commands.getoutput(
                "hdparm -i /dev/sda | grep -o 'Model=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
            )
            disk_dmi["ModelNumber"] = disk_modelno
        elif os.path.exists("/dev/cciss/c0d0"):
            # Needs smartctl to be able to get the correct information
            if os.path.exists("/usr/sbin/smartctl"):
                hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
                disk_dmi["ModelNumber"] = re.search("Product:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
            else:
                print "Install smartmontools: apt-get install smartmontools"
    except OSError:
        print "Haz RAID?"
        print commands.getoutput("lspci | grep -i raid")

        # Write more things to file
    for k, v in disk_dmi.iteritems():
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/'
                + k
                + "\t'"
                + v
                + "'\n"
            )

            # CD-ROM information
    cdrom_dmi = {}
    if os.path.islink("/dev/cdrom"):
        # CD-ROM serial
        cdrom_serial = commands.getoutput(
            "hdparm -i /dev/cdrom | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'"
        )
        if cdrom_serial:
            cdrom_dmi["ATAPISerialNumber"] = serial_randomize(0, len(cdrom_serial))
        else:
            cdrom_dmi["ATAPISerialNumber"] = "** No value to retrieve **"

            # CD-ROM firmeware rev
        cdrom_fwrev = commands.getoutput("cd-drive | grep Revision | grep  ':' | awk {' print $3 \" \" $4'}")
        cdrom_dmi["ATAPIRevision"] = cdrom_fwrev.replace(" ", "")

        # CD-ROM Model numberA-Za-z0-9_\+\/ .\"-
        cdrom_modelno = commands.getoutput("cd-drive | grep Model | grep  ':' | awk {' print $3 \" \" $4'}")
        cdrom_dmi["ATAPIProductId"] = cdrom_modelno

        # CD-ROM Vendor
        cdrom_vendor = commands.getoutput("cd-drive | grep Vendor | grep  ':' | awk {' print $3 '}")
        cdrom_dmi["ATAPIVendorId"] = cdrom_vendor
    else:
        logfile.write("# No CD-ROM detected: ** No values to retrieve **\n")

        # And some more
    for k, v in cdrom_dmi.iteritems():
        if "** No value to retrieve **" in v:
            logfile.write(
                '# VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/'
                + k
                + "\t"
                + v
                + "\n"
            )
        else:
            logfile.write(
                'VBoxManage setextradata "'
                + vm_name
                + '" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/'
                + k
                + "\t'"
                + v
                + "'\n"
            )

            # Get the DSDT image
            # os.system("dd if=/sys/firmware/acpi/tables/DSDT of=DSDT.bin >/dev/null 2>&1")
            # Write to file
            # Da un error de que la tabla ACPI es mayor de 64KB, aunque lo comente, si luego ejecuto el batch dentro del Guest, pasa las pruebas
            # logfile.write('VBoxManage setextradata '+vm_name+' VBoxInternal/Devices/acpi/0/Config/CustomTable\t\'' + os.getcwd() + '/DSDT.bin\'\n')

    acpi_misc = commands.getoutput('acpidump -s | grep DSDT | grep -o "\(([A-Za-z0-9].*)\)" | tr -d "()"')
    acpi_list = acpi_misc.split(" ")
    acpi_list = filter(None, acpi_list)

    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiOemId\t'"
        + acpi_list[1]
        + "'\n"
    )
    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorId\t'"
        + acpi_list[4]
        + "'\n"
    )
    logfile.write(
        'VBoxManage setextradata "'
        + vm_name
        + "\" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorRev\t'"
        + acpi_list[5]
        + "'\n"
    )

    # Randomize MAC address, based on onboard interface MAC
    mac_seed = ":".join(re.findall("..", "%012x" % uuid.getnode()))[0:9]
    big_mac = mac_seed + "%02x:%02x:%02x" % (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    le_big_mac = re.sub(":", "", big_mac)

    # The last thing!
    logfile.write('VBoxManage modifyvm "' + vm_name + '" --macaddress1\t' + le_big_mac + "\n")
    # Done!
    logfile.close()

    print "	Finished: A template shell script has been created named:", file_name
    print bcolors.OKGREEN + "\n [*]" + bcolors.ENDC + " Creating guest based modification file (to be run inside the guest)"

    # Write all data to file
    file_name2 = "vboxmods-" + vm_name.replace(" ", "_") + ".bat"
    logfile = file("/srv/ftp/CopyThisOne!/" + file_name2, "w+")

    manu = acpi_list[1]

    # DSDT
    logfile.write("@reg copy HKLM\HARDWARE\ACPI\DSDT\VBOX__ HKLM\HARDWARE\ACPI\DSDT\\" + manu + " /s /f\n\n")
    logfile.write("@reg delete HKLM\HARDWARE\ACPI\DSDT\VBOX__ /f\n\n")

    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\VBOXBIOS HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___"
        + " /s /f\n\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\" + manu + "\VBOXBIOS /f\n\n")

    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000002 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\n\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\" + manu + "\\" + acpi_list[2] + "___\\00000002 /f\n"
    )

    # FADT
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\VBOXFACP HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___  /s /f\n\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\" + manu + "\VBOXFACP /f\n")
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\n\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\" + manu + "\\" + acpi_list[2] + "___\\00000001 /f\n\n"
    )

    # RSDT
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\VBOXRSDT HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___  /s /f\r\n"
    )
    logfile.write("@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\" + manu + "\VBOXRSDT /f\r\n")
    logfile.write(
        "@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\"
        + manu
        + "\\"
        + acpi_list[2]
        + "___\\"
        + acpi_list[3]
        + " /s /f\r\n"
    )
    logfile.write(
        "@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\" + manu + "\\" + acpi_list[2] + "___\\00000001 /f\r\n"
    )

    # SystemBiosVersion - TODO: get real values
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosVersion /t REG_MULTI_SZ /d "'
        + acpi_list[1]
        + " - "
        + acpi_list[0]
        + '" /f\n\n'
    )
    # VideoBiosVersion - TODO: get real values
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v VideoBiosVersion /t REG_MULTI_SZ /d "'
        + acpi_list[0]
        + '" /f\n'
    )
    # SystemBiosDate
    d_month, d_day, d_year = dmi_info["DmiBIOSReleaseDate"].split("/")

    if len(d_year) > 2:
        d_year = d_year[:2]

    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosDate /t REG_MULTI_SZ /d "'
        + d_month
        + "/"
        + d_day
        + "/"
        + d_year
        + '" /f\n'
    )

    # Prevent WMI identification
    logfile.write(
        '@reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PlugPlay /v Start /t REG_MULTI_SZ /d "4" /f\r\n'
    )
    # The system have to be rebooted for this to work, don't know why

    #  Disables FW
    logfile.write("netsh firewall set opmode disable\n")
    # Disables windows updates
    logfile.write(
        '@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f\n'
    )
    # Change the IP and DNS
    shortScript = (
        """
		@echo off

		set _enabled=Habilitado
		set _dedicated=Dedicado

		for /f "tokens=1,2,3*" %%i in ('netsh int show interface') do (
			if %%i equ %_enabled% (
				if %%j equ %_dedicated% (
					netsh int ip set address "%%k %%l" static """
        + guest_ip
        + """ 255.255.255.0 """
        + host_ip
        + """ 1
					netsh int ip set dns "%%k %%l" static """
        + guest_primary_dns
        + """
				 )
			)
		)
		ipconfig /flushdns

		:EOF"""
    )
    logfile.write(shortScript + "\n")

    logfile.close()
    print "	Finished: A Windows batch file has been created named:", file_name2

    return
Beispiel #2
0
    def mobo_info(self):
        mobo = []

        for v in dmidecode.baseboard().values():
            if v['dmi_type'] == 2: #Motherboard
                mobo.append("Manufacturer: %s" %(v['data']['Manufacturer']))
                mobo.append("Product Name: %s" %(v['data']['Product Name']))
                mobo.append("Version: %s" %(v['data']['Version']))
                mobo.append("Serial Number: %s" %(v['data']['Serial Number']))
                break

        return mobo
Beispiel #3
0
    def net_info(self):
        #~ data1 = dmidecode.connector().values()
        #~ data2 = dmidecode.baseboard().values()
        #~ data2 = dmidecode.QueryTypeId(41) ; print data2

        net = []
        netport = 0
        netdev  = 0

        for v in dmidecode.connector().values():
            if v['dmi_type'] == 8 and v['data']['Port Type'] == "Network Port": #Network Port
                if netport > 0:
                    net.append(" ")
                net.append("Network Port %s" %netport)
                net.append("Internal Reference Designator: %s" %(v['data']['Internal Reference Designator']))
                net.append("Internal Connector Type: %s" %(v['data']['Internal Connector Type']))
                net.append("External Reference Designator: %s" %(v['data']['External Reference Designator']))
                net.append("External Connector Type: %s" %(v['data']['External Connector Type']))

                netport += 1

        for v in dmidecode.baseboard().values():
            if v['dmi_type'] == 41:
                chk = v['data']['Reference Designation']
                if "802.11" in chk or "WiFi" in chk or "Ethernet" in chk:
                    if netport > 0:
                        net.append(" ")
                    net.append("Network Device %s" %netdev)
                    net.append("Name: %s" %(v['data']['Reference Designation']))
                    net.append("Status: %s" %(v['data']['Status']))
                    net.append("Type: %s" %(v['data']['Type']))
                    net.append("Type Instance: %s" %(v['data']['Type Instance']))
                    net.append("Bus Address: %s" %(v['data']['Bus Address']))

                    netdev += 1

        return net
Beispiel #4
0
    def _getdmi(self):
        from pprint import pprint
        DMI = { }


        # get BIOS Data
        #tmp = dmidecode.bios()
        #pprint(tmp)
        for v  in dmidecode.bios().values():
            if type(v) == dict and v['dmi_type'] == 0:
                DMI['bios',0,'BIOS Revision'] = str((v['data']['BIOS Revision']))
                DMI['bios',0,'ROM Size'] = str((v['data']['ROM Size']))
                try:
                    DMI['bios',0,'Release Date'] = str((v['data']['Relase Date']))
                except (KeyError):
                    DMI['bios',0,'Release Date'] = str((v['data']['Release Date']))

                DMI['bios',0,'Runtime Size'] = str((v['data']['Runtime Size']))
                DMI['bios',0,'Vendor'] = str((v['data']['Vendor']))
                DMI['bios',0,'Version'] = str((v['data']['Version']))

        # get System Data
        #tmp = dmidecode.system()
        #pprint(tmp)
        for v  in dmidecode.system().values():
            if type(v) == dict and v['dmi_type'] == 1:
                DMI['system',0,'Family'] = str((v['data']['Family']))
                DMI['system',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['system',0,'Product Name'] = str((v['data']['Product Name']))
                DMI['system',0,'SKU Number'] = str((v['data']['SKU Number']))
                DMI['system',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['system',0,'UUID'] = str((v['data']['UUID']))
                DMI['system',0,'Version'] = str((v['data']['Version']))
                DMI['system',0,'Wake-Up Type'] = str((v['data']['Wake-Up Type']))

        # get BaseBoard Data
        #tmp = dmidecode.baseboard()
        #pprint(tmp)
        for v  in dmidecode.baseboard().values():
            if type(v) == dict and v['dmi_type'] == 2:
                DMI['baseboard',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['baseboard',0,'Product Name'] = str((v['data']['Product Name']))
                DMI['baseboard',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['baseboard',0,'Version'] = str((v['data']['Version']))


        # get chassis Data
        #tmp = dmidecode.chassis()
        #pprint(tmp)
        for v  in dmidecode.chassis().values():
            if type(v) == dict and v['dmi_type'] == 3:
                DMI['chassis',0,'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['chassis',0,'Boot-Up State'] = str((v['data']['Boot-Up State']))
                DMI['chassis',0,'Lock'] = str((v['data']['Lock']))
                DMI['chassis',0,'Manufacturer'] = str((v['data']['Manufacturer']))
                DMI['chassis',0,'Power Supply State'] = str((v['data']['Power Supply State']))
                DMI['chassis',0,'Security Status'] = str((v['data']['Security Status']))
                DMI['chassis',0,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['chassis',0,'Thermal State'] = str((v['data']['Thermal State']))
                DMI['chassis',0,'Type'] = str((v['data']['Type']))
                DMI['chassis',0,'Version'] = str((v['data']['Version']))

        # get Processor Data
        #tmp = dmidecode.processor()
        #pprint(tmp)
        i = 0
        for v  in dmidecode.processor().values():
            if type(v) == dict and v['dmi_type'] == 4:
                DMI['processor',i,'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['processor',i,'Characteristics'] = str((v['data']['Characteristics']))
                DMI['processor',i,'Core Count'] = str((v['data']['Core Count']))
                DMI['processor',i,'Core Enabled'] = str((v['data']['Core Enabled']))
                DMI['processor',i,'Current Speed'] =str((v['data']['Current Speed']))
                DMI['processor',i,'External Clock'] = str((v['data']['External Clock']))
                DMI['processor',i,'Family'] = str((v['data']['Family']))
                DMI['processor',i,'L1 Cache Handle'] = str((v['data']['L1 Cache Handle']))
                DMI['processor',i,'L2 Cache Handle'] = str((v['data']['L2 Cache Handle']))
                DMI['processor',i,'L3 Cache Handle'] = str((v['data']['L3 Cache Handle']))
                DMI['processor',i,'Manufacturer'] = str((v['data']['Manufacturer']['Vendor']))
                DMI['processor',i,'Max Speed'] = str((v['data']['Max Speed']))
                DMI['processor',i,'Part Number'] = str((v['data']['Part Number']))
                DMI['processor',i,'Serial Number'] = str((v['data']['Serial Number']))
                DMI['processor',i,'Socket Designation'] = str((v['data']['Socket Designation']))
                DMI['processor',i,'Status'] = str((v['data']['Status']))
                DMI['processor',i,'Thread Count'] = str((v['data']['Thread Count']))
                DMI['processor',i,'Type'] = str((v['data']['Type']))
                DMI['processor',i,'Upgrade'] = str((v['data']['Upgrade']))
                DMI['processor',i,'Version'] = str((v['data']['Version']))
                DMI['processor',i,'Voltage'] = str((v['data']['Voltage']))
                i += 1


        # get Memory Data
        #tmp = dmidecode.memory()
        #pprint(tmp)
        i = 0
        for v  in dmidecode.memory().values():
            if type(v) == dict and v['dmi_type'] == 17 :
                if str((v['data']['Size'])) != 'None':
                    DMI['memory',i,'Data Width'] = str((v['data']['Data Width']))
                    DMI['memory',i,'Error Information Handle'] = str((v['data']['Error Information Handle']))
                    DMI['memory',i,'Form Factor'] = str((v['data']['Form Factor']))
                    DMI['memory',i,'Bank Locator'] = str((v['data']['Bank Locator']))
                    DMI['memory',i,'Locator'] = str((v['data']['Locator']))
                    DMI['memory',i,'Manufacturer'] = str((v['data']['Manufacturer']))
                    DMI['memory',i,'Part Number'] = str((v['data']['Part Number']))
                    DMI['memory',i,'Serial Number'] = str((v['data']['Serial Number']))
                    DMI['memory',i,'Size'] = str((v['data']['Size']))
                    DMI['memory',i,'Speed'] = str((v['data']['Speed']))
                    DMI['memory',i,'Type'] = str((v['data']['Type']))
                    i += 1

        # get cache Data
        #tmp = dmidecode.cache()
        #pprint(tmp)

        # get connector Data
        #tmp = dmidecode.connector()
        #pprint(tmp)

        # get slot Data
        #tmp = dmidecode.slot()
        #pprint(tmp)

        return DMI
try:
    dmi_info['DmiBIOSReleaseMajor'], dmi_info['DmiBIOSReleaseMinor'] = biosversion.split('.', 1)
except:
    dmi_info['DmiBIOSReleaseMajor'] = '** No value to retrieve **'
    dmi_info['DmiBIOSReleaseMinor'] = '** No value to retrieve **'

# python-dmidecode does not currently reveal all values .. this is plan B
dmi_firmware = commands.getoutput("dmidecode -t0")
try:
    dmi_info['DmiBIOSFirmwareMajor'], dmi_info['DmiBIOSFirmwareMinor'] = re.search(
        "Firmware Revision: ([0-9A-Za-z. ]*)", dmi_firmware).group(1).split('.', 1)
except:
    dmi_info['DmiBIOSFirmwareMajor'] = '** No value to retrieve **'
    dmi_info['DmiBIOSFirmwareMinor'] = '** No value to retrieve **'

for v in dmidecode.baseboard().values():
    if type(v) == dict and v['dmi_type'] == 2:
        serial_number = v['data']['Serial Number']
        dmi_info['DmiBoardVersion'] = v['data']['Version']
        dmi_info['DmiBoardProduct'] = "string:" + v['data']['Product Name']
        dmi_info['DmiBoardVendor'] = v['data']['Manufacturer']

# This is hopefully not the best solution ..
try:
    s_number = []
    if serial_number:
        # Get position
        if '/' in serial_number:
            for slash in re.finditer('/', serial_number):
                s_number.append(slash.start(0))
                # Remove / from string
Beispiel #6
0
except:
    dmi_info['DmiBIOSReleaseMajor'] = '** No value to retrieve **'
    dmi_info['DmiBIOSReleaseMinor'] = '** No value to retrieve **'

# python-dmidecode does not currently reveal all values .. this is plan B
dmi_firmware = commands.getoutput("dmidecode -t0")
try:
    dmi_info['DmiBIOSFirmwareMajor'], dmi_info[
        'DmiBIOSFirmwareMinor'] = re.search(
            "Firmware Revision: ([0-9A-Za-z. ]*)",
            dmi_firmware).group(1).split('.', 1)
except:
    dmi_info['DmiBIOSFirmwareMajor'] = '** No value to retrieve **'
    dmi_info['DmiBIOSFirmwareMinor'] = '** No value to retrieve **'

for v in dmidecode.baseboard().values():
    if type(v) == dict and v['dmi_type'] == 2:
        serial_number = v['data']['Serial Number']
        dmi_info['DmiBoardVersion'] = v['data']['Version']
        dmi_info['DmiBoardProduct'] = v['data']['Product Name']
        dmi_info['DmiBoardVendor'] = v['data']['Manufacturer']

# This is hopefully not the best solution ..
try:
    s_number = []
    if serial_number:
        # Get position
        if '/' in serial_number:
            for slash in re.finditer('/', serial_number):
                s_number.append(slash.start(0))
                # Remove / from string
Beispiel #7
0
        print("####")
        print()
        print()


#. Test for presence of important functions using /dev/mem...  Using the legacy API
#. This does not print any decoded info.  If the call fails, either a warning will
#. be issued or an exception will be raised.  This test is now only used to check
#. for presence of the legacy API, which "under the hood" uses
#. dmidecode.QuerySection(name), where name can be 'bios', 'system', etc.
if root_user:
        print("*** bios ***\n");      dmidecode.bios()
        print_warnings()
        print("*** system ***\n");    dmidecode.system()
        print_warnings()
        print("*** baseboard ***\n"); dmidecode.baseboard()
        print_warnings()
        print("*** chassis ***\n");   dmidecode.chassis()
        print_warnings()
        print("*** processor ***\n"); dmidecode.processor()
        print_warnings()
        print("*** memory ***\n");    dmidecode.memory()
        print_warnings()
        print("*** cache ***\n");     dmidecode.cache()
        print_warnings()
        print("*** connector ***\n"); dmidecode.connector()
        print_warnings()
        print("*** slot ***\n");      dmidecode.slot()
        print_warnings()

Beispiel #8
0
def main(vm_name, guest_ip, host_ip, guest_primary_dns, path_logs):
	# Welcome
	print '\n--- AntiVMdetect by Mikael, @nsmfoo (modified by Jose Carlos R.) ---'
	print bcolors.OKGREEN+' [*]'+bcolors.ENDC+' Creating VirtualBox modifications ..'

	dmi_info = {}

	for v in dmidecode.bios().values():
		if type(v) == dict and v['dmi_type'] == 0:
			dmi_info['DmiBIOSVendor'] = v['data']['Vendor']
			dmi_info['DmiBIOSReleaseDate'] = v['data']['Relase Date']
			dmi_info['DmiBIOSVersion'] = v['data']['Version']
			biosversion = v['data']['BIOS Revision']

	try:
		dmi_info['DmiBIOSReleaseMajor'], dmi_info['DmiBIOSReleaseMinor'] = biosversion.split('.', 1)
	except:
		dmi_info['DmiBIOSReleaseMajor'] = '** No value to retrieve **'
		dmi_info['DmiBIOSReleaseMinor'] = '** No value to retrieve **'

	# python-dmidecode does not currently reveal all values .. this is plan B
	dmi_firmware = commands.getoutput("dmidecode -t0")
	try:
		dmi_info['DmiBIOSFirmwareMajor'], dmi_info['DmiBIOSFirmwareMinor'] = re.search(
			"Firmware Revision: ([0-9A-Za-z. ]*)", dmi_firmware).group(1).split('.', 1)
	except:
		dmi_info['DmiBIOSFirmwareMajor'] = '** No value to retrieve **'
		dmi_info['DmiBIOSFirmwareMinor'] = '** No value to retrieve **'

	for v in dmidecode.baseboard().values():
		if type(v) == dict and v['dmi_type'] == 2:
			serial_number = v['data']['Serial Number']
			dmi_info['DmiBoardVersion'] = v['data']['Version']
			if isinstance(v['data']['Product Name'], int ):
				dmi_info['DmiBoardProduct'] = str(v['data']['Product Name'])+ ' '
			else:
				dmi_info['DmiBoardProduct'] = v['data']['Product Name']
			dmi_info['DmiBoardVendor'] = v['data']['Manufacturer']

	# This is hopefully not the best solution ..
	try:
		s_number = []
		if serial_number:
			# Get position
			if '/' in serial_number:
				for slash in re.finditer('/', serial_number):
					s_number.append(slash.start(0))
					# Remove / from string
					new_serial = re.sub('/', '', serial_number)
					new_serial = serial_randomize(0, len(new_serial))
				# Add / again
				for char in s_number:
					new_serial = new_serial[:char] + '/' + new_serial[char:]
			else:
				new_serial = serial_randomize(0, len(serial_number))
		else:
			new_serial = "** No value to retrieve **"
	except:
		new_serial = "** No value to retrieve **"

	dmi_info['DmiBoardSerial'] = "string:"+new_serial

	# python-dmidecode does not reveal all values .. this is plan B
	dmi_board = commands.getoutput("dmidecode -t2")
	try:
		asset_tag = re.search("Asset Tag: ([0-9A-Za-z ]*)", dmi_board).group(1)
	except:
		asset_tag = '** No value to retrieve **'

	dmi_info['DmiBoardAssetTag'] = asset_tag

	try:
		loc_chassis = re.search("Location In Chassis: ([0-9A-Za-z ]*)", dmi_board).group(1)
	except:
		loc_chassis = '** No value to retrieve **'

	dmi_info['DmiBoardLocInChass'] = loc_chassis

	# Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
	board_dict = {'Unknown': 1, 'Other': 2, 'Server Blade': 3, 'Connectivity Switch': 4, 'System Management Module': 5,
				  'Processor Module': 6, 'I/O Module': 7, 'Memory Module': 8, 'Daughter board': 9, 'Motherboard': 10,
				  'Processor/Memory Module': 11, 'Processor/IO Module': 12, 'Interconnect board': 13}
	try:
		board_type = re.search("Type: ([0-9A-Za-z ]+)", dmi_board).group(1)
		board_type = str(board_dict.get(board_type))
	except:
		board_type = '** No value to retrieve **'

	dmi_info['DmiBoardBoardType'] = board_type

	for v in dmidecode.system().values():
		if type(v) == dict and v['dmi_type'] == 1:
			dmi_info['DmiSystemSKU'] = v['data']['SKU Number']
			system_family = v['data']['Family']
			system_serial = v['data']['Serial Number']
			dmi_info['DmiSystemVersion'] = "string:" + v['data']['Version']
			dmi_info['DmiSystemProduct'] = v['data']['Product Name']
			dmi_info['DmiSystemVendor'] = v['data']['Manufacturer']

	if not system_family:
		dmi_info['DmiSystemFamily'] = "Not Specified"
	else:
		dmi_info['DmiSystemFamily'] = system_family

	# Create a new UUID
	newuuid = str(uuid.uuid4())
	dmi_info['DmiSystemUuid'] = newuuid.upper()
	# Create a new system serial number
	dmi_info['DmiSystemSerial'] = "string:"+(serial_randomize(0, len(system_serial)))

	for v in dmidecode.chassis().values():
		dmi_info['DmiChassisVendor'] = v['data']['Manufacturer']
		chassi_serial = v['data']['Serial Number']
		dmi_info['DmiChassisVersion'] = v['data']['Version']
		dmi_info['DmiChassisType'] = v['data']['Type']

	# Based on the list from http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.0.0.pdf
	chassi_dict = {'Other': 1, 'Unknown': 2, 'Desktop': 3, 'Low Profile Desktop': 4, 'Pizza Box': 5, 'Mini Tower': 6,
				   'Tower': 7, 'Portable': 8, 'Laptop': 9, 'Notebook': 10, 'Hand Held': 11, 'Docking Station': 12,
				   'All in One': 13, 'Sub Notebook': 14, 'Space-saving': 15, 'Lunch Box': 16, 'Main Server Chassis': 17,
				   'Expansion Chassis': 18, 'SubChassis': 19, 'Bus Expansion Chassis': 20, 'Peripheral Chassis': 21}
	dmi_info['DmiChassisType'] = str(chassi_dict.get(dmi_info['DmiChassisType']))
	# python-dmidecode does not reveal all values .. this is plan B
	chassi = commands.getoutput("dmidecode -t3")
	try:
		dmi_info['DmiChassisAssetTag'] = re.search("Asset Tag: ([0-9A-Za-z ]*)", chassi).group(1)
	except:
		dmi_info['DmiChassisAssetTag'] = '** No value to retrieve **'

	# Create a new chassi serial number, added string to make it be taken as a string even if it's a number
	dmi_info['DmiChassisSerial'] = "string:"+str(serial_randomize(0, len(chassi_serial)))

	for v in dmidecode.processor().values():
		dmi_info['DmiProcVersion'] = v['data']['Version']
		dmi_info['DmiProcManufacturer'] = v['data']['Manufacturer']['Vendor']
	# OEM strings
	try:
		for v in dmidecode.type(11).values():
			oem_ver = v['data']['Strings']['3']
			oem_rev = v['data']['Strings']['2']
	except:
		pass
	try:
		dmi_info['DmiOEMVBoxVer'] = oem_ver
		dmi_info['DmiOEMVBoxRev'] = oem_rev
	except:
		dmi_info['DmiOEMVBoxVer'] = '** No value to retrieve **'
		dmi_info['DmiOEMVBoxRev'] = '** No value to retrieve **'

	# Write all data collected so far to file
	file_name="vboxmods-"+vm_name.replace(' ','_')+".sh"

	logfile = file(path_logs+'/'+file_name, 'w+')
	logfile.write('# Generated on: ' + time.strftime("%H:%M:%S") + '\n')

	for k, v in sorted(dmi_info.iteritems()):
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/pcbios/0/Config/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/pcbios/0/Config/' + k + '\t\'' + v + '\'\n')
	# Disk information
	disk_dmi = {}
	try:
		if os.path.exists("/dev/sda"):
			# Disk serial
			disk_serial = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			# To avoid exceding 20 bytes serials
			if len(disk_serial)>20:
				disk_dmi['SerialNumber'] = (serial_randomize(0, 20))
			else:
				disk_dmi['SerialNumber'] = (serial_randomize(0, len(disk_serial)))
			# Check for HP Legacy RAID
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_serial = re.search("Serial number:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
				# To avoid exceding 20 bytes serials
				if len(disk_serial)>20:
					disk_dmi['SerialNumber'] = (serial_randomize(0, 20))
				else:
					disk_dmi['SerialNumber'] = (serial_randomize(0, len(disk_serial)))
			else:
				print bcolors.WARNING+"Install smartmontools: apt-get install smartmontools"+bcolors.ENDC
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Disk firmeware rev
	try:
		if os.path.exists("/dev/sda"):
			disk_fwrev = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'FwRev=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			disk_dmi['FirmwareRevision'] = disk_fwrev
			if len(disk_dmi['FirmwareRevision'])<8:
				disk_dmi['FirmwareRevision']=disk_dmi['FirmwareRevision'][:8]
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_dmi['FirmwareRevision'] = re.search("Revision:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
				if len(disk_dmi['FirmwareRevision'])<8:
					disk_dmi['FirmwareRevision']=disk_dmi['FirmwareRevision'][:8]
			else:
				print "Install smartmontools: apt-get install smartmontools"
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Disk Model number
	try:
		if os.path.exists("/dev/sda"):
			disk_modelno = commands.getoutput(
				"hdparm -i /dev/sda | grep -o 'Model=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
			disk_dmi['ModelNumber'] = disk_modelno
		elif os.path.exists("/dev/cciss/c0d0"):
			# Needs smartctl to be able to get the correct information
			if os.path.exists("/usr/sbin/smartctl"):
				hp_old_raid = commands.getoutput("smartctl -d cciss,1 -i /dev/cciss/c0d0")
				disk_dmi['ModelNumber'] = re.search("Product:([0-9A-Za-z ]*)", hp_old_raid).group(1).replace(" ", "")
			else:
				print "Install smartmontools: apt-get install smartmontools"
	except OSError:
		print "Haz RAID?"
		print commands.getoutput("lspci | grep -i raid")

	# Write more things to file
	for k, v in disk_dmi.iteritems():
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/PrimaryMaster/' + k + '\t\'' + v + '\'\n')

	# CD-ROM information
	cdrom_dmi = {}
	if os.path.islink('/dev/cdrom'):
		# CD-ROM serial
		cdrom_serial = commands.getoutput(
			"hdparm -i /dev/cdrom | grep -o 'SerialNo=[A-Za-z0-9_\+\/ .\"-]*' | awk -F= '{print $2}'")
		if cdrom_serial:
			cdrom_dmi['ATAPISerialNumber'] = (serial_randomize(0, len(cdrom_serial)))
		else:
			cdrom_dmi['ATAPISerialNumber'] = "** No value to retrieve **"

		# CD-ROM firmeware rev
		cdrom_fwrev = commands.getoutput("cd-drive | grep Revision | grep  ':' | awk {' print $3 \" \" $4'}")
		cdrom_dmi['ATAPIRevision'] = cdrom_fwrev.replace(" ", "")

		# CD-ROM Model numberA-Za-z0-9_\+\/ .\"-
		cdrom_modelno = commands.getoutput("cd-drive | grep Model | grep  ':' | awk {' print $3 \" \" $4'}")
		cdrom_dmi['ATAPIProductId'] = cdrom_modelno

		# CD-ROM Vendor
		cdrom_vendor = commands.getoutput("cd-drive | grep Vendor | grep  ':' | awk {' print $3 '}")
		cdrom_dmi['ATAPIVendorId'] = cdrom_vendor
	else:
		logfile.write('# No CD-ROM detected: ** No values to retrieve **\n')

	# And some more
	for k, v in cdrom_dmi.iteritems():
		if '** No value to retrieve **' in v:
			logfile.write('# VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/' + k + '\t' + v + '\n')
		else:
			logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/piix3ide/0/Config/SecondaryMaster/' + k + '\t\'' + v + '\'\n')

	# Get the DSDT image
	#os.system("dd if=/sys/firmware/acpi/tables/DSDT of=DSDT.bin >/dev/null 2>&1")
	# Write to file
	# Da un error de que la tabla ACPI es mayor de 64KB, aunque lo comente, si luego ejecuto el batch dentro del Guest, pasa las pruebas
	#logfile.write('VBoxManage setextradata '+vm_name+' VBoxInternal/Devices/acpi/0/Config/CustomTable\t\'' + os.getcwd() + '/DSDT.bin\'\n')

	acpi_misc = commands.getoutput('acpidump -s | grep DSDT | grep -o "\(([A-Za-z0-9].*)\)" | tr -d "()"')
	acpi_list = acpi_misc.split(' ')
	acpi_list = filter(None, acpi_list)

	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiOemId\t\'' + acpi_list[1] + '\'\n')
	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorId\t\'' + acpi_list[4] + '\'\n')
	logfile.write('VBoxManage setextradata "'+vm_name+'" VBoxInternal/Devices/acpi/0/Config/AcpiCreatorRev\t\'' + acpi_list[5] + '\'\n')

	# Randomize MAC address, based on onboard interface MAC
	mac_seed = ':'.join(re.findall('..', '%012x' % uuid.getnode()))[0:9]
	big_mac = mac_seed + "%02x:%02x:%02x" % (
		random.randint(0, 255),
		random.randint(0, 255),
		random.randint(0, 255),
	)
	le_big_mac = re.sub(':', '', big_mac)

	# The last thing!
	logfile.write('VBoxManage modifyvm "'+vm_name+'" --macaddress1\t' + le_big_mac +'\n')
	# Done!
	logfile.close()

	print '	Finished: A template shell script has been created named:', file_name
	print bcolors.OKGREEN+'\n [*]'+bcolors.ENDC+' Creating guest based modification file (to be run inside the guest)'

	# Write all data to file
	file_name2="vboxmods-"+vm_name.replace(' ','_')+".bat"
	logfile = file('/srv/ftp/CopyThisOne!/' +file_name2, 'w+')

	manu = acpi_list[1]

	# DSDT
	logfile.write('@reg copy HKLM\HARDWARE\ACPI\DSDT\VBOX__ HKLM\HARDWARE\ACPI\DSDT\\' + manu + ' /s /f\n\n')
	logfile.write('@reg delete HKLM\HARDWARE\ACPI\DSDT\VBOX__ /f\n\n')

	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\VBOXBIOS HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___' + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\VBOXBIOS /f\n\n')

	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000002 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\DSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000002 /f\n')

	# FADT
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\VBOXFACP HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___  /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\VBOXFACP /f\n')
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\n\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\FADT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 /f\n\n')

	# RSDT
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\VBOXRSDT HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___  /s /f\r\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\VBOXRSDT /f\r\n')
	logfile.write('@reg copy HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\' + acpi_list[3] + ' /s /f\r\n')
	logfile.write('@reg delete HKEY_LOCAL_MACHINE\HARDWARE\ACPI\RSDT\\' + manu + '\\' + acpi_list[2] + '___\\00000001 /f\r\n')


	# SystemBiosVersion - TODO: get real values
	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosVersion /t REG_MULTI_SZ /d "' + acpi_list[1] + ' - ' + acpi_list[0] + '" /f\n\n')
	# VideoBiosVersion - TODO: get real values
	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v VideoBiosVersion /t REG_MULTI_SZ /d "' + acpi_list[0] + '" /f\n')
	# SystemBiosDate
	d_month, d_day, d_year = dmi_info['DmiBIOSReleaseDate'].split('/')

	if len(d_year) > 2:
		d_year = d_year[:2]

	logfile.write('@reg add HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System /v SystemBiosDate /t REG_MULTI_SZ /d "' + d_month + '/' + d_day + '/' + d_year + '" /f\n')


	# Prevent WMI identification
	logfile.write('@reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PlugPlay /v Start /t REG_MULTI_SZ /d "4" /f\r\n')
	#The system have to be rebooted for this to work, don't know why

	#  Disables FW
	logfile.write('netsh firewall set opmode disable\n')
	# Disables windows updates
	logfile.write('@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f\n')
	# Change the IP and DNS
	shortScript='''
		@echo off

		set _enabled=Habilitado
		set _dedicated=Dedicado

		for /f "tokens=1,2,3*" %%i in ('netsh int show interface') do (
			if %%i equ %_enabled% (
				if %%j equ %_dedicated% (
					netsh int ip set address "%%k %%l" static '''+guest_ip+''' 255.255.255.0 '''+host_ip+''' 1
					netsh int ip set dns "%%k %%l" static '''+guest_primary_dns+'''
				 )
			)
		)
		ipconfig /flushdns

		:EOF'''
	logfile.write(shortScript+'\n')

	logfile.close()
	print '	Finished: A Windows batch file has been created named:', file_name2
	
	return
Beispiel #9
0
    def _getdmi(self):
        from pprint import pprint
        DMI = {}

        # get BIOS Data
        #tmp = dmidecode.bios()
        #pprint(tmp)
        for v in dmidecode.bios().values():
            if type(v) == dict and v['dmi_type'] == 0:
                DMI['bios', 0, 'BIOS Revision'] = str(
                    (v['data']['BIOS Revision']))
                DMI['bios', 0, 'ROM Size'] = str((v['data']['ROM Size']))
                try:
                    DMI['bios', 0, 'Release Date'] = str(
                        (v['data']['Relase Date']))
                except (KeyError):
                    DMI['bios', 0, 'Release Date'] = str(
                        (v['data']['Release Date']))

                DMI['bios', 0, 'Runtime Size'] = str(
                    (v['data']['Runtime Size']))
                DMI['bios', 0, 'Vendor'] = str((v['data']['Vendor']))
                DMI['bios', 0, 'Version'] = str((v['data']['Version']))

        # get System Data
        #tmp = dmidecode.system()
        #pprint(tmp)
        for v in dmidecode.system().values():
            if type(v) == dict and v['dmi_type'] == 1:
                DMI['system', 0, 'Family'] = str((v['data']['Family']))
                DMI['system', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['system', 0, 'Product Name'] = str(
                    (v['data']['Product Name']))
                DMI['system', 0, 'SKU Number'] = str((v['data']['SKU Number']))
                DMI['system', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['system', 0, 'UUID'] = str((v['data']['UUID']))
                DMI['system', 0, 'Version'] = str((v['data']['Version']))
                DMI['system', 0, 'Wake-Up Type'] = str(
                    (v['data']['Wake-Up Type']))

        # get BaseBoard Data
        #tmp = dmidecode.baseboard()
        #pprint(tmp)
        for v in dmidecode.baseboard().values():
            if type(v) == dict and v['dmi_type'] == 2:
                DMI['baseboard', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['baseboard', 0, 'Product Name'] = str(
                    (v['data']['Product Name']))
                DMI['baseboard', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['baseboard', 0, 'Version'] = str((v['data']['Version']))

        # get chassis Data
        #tmp = dmidecode.chassis()
        #pprint(tmp)
        for v in dmidecode.chassis().values():
            if type(v) == dict and v['dmi_type'] == 3:
                DMI['chassis', 0, 'Asset Tag'] = str((v['data']['Asset Tag']))
                DMI['chassis', 0, 'Boot-Up State'] = str(
                    (v['data']['Boot-Up State']))
                DMI['chassis', 0, 'Lock'] = str((v['data']['Lock']))
                DMI['chassis', 0, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']))
                DMI['chassis', 0, 'Power Supply State'] = str(
                    (v['data']['Power Supply State']))
                DMI['chassis', 0, 'Security Status'] = str(
                    (v['data']['Security Status']))
                DMI['chassis', 0, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['chassis', 0, 'Thermal State'] = str(
                    (v['data']['Thermal State']))
                DMI['chassis', 0, 'Type'] = str((v['data']['Type']))
                DMI['chassis', 0, 'Version'] = str((v['data']['Version']))

        # get Processor Data
        #tmp = dmidecode.processor()
        #pprint(tmp)
        i = 0
        for v in dmidecode.processor().values():
            if type(v) == dict and v['dmi_type'] == 4:
                DMI['processor', i, 'Asset Tag'] = str(
                    (v['data']['Asset Tag']))
                DMI['processor', i, 'Characteristics'] = str(
                    (v['data']['Characteristics']))
                DMI['processor', i, 'Core Count'] = str(
                    (v['data']['Core Count']))
                DMI['processor', i, 'Core Enabled'] = str(
                    (v['data']['Core Enabled']))
                DMI['processor', i, 'Current Speed'] = str(
                    (v['data']['Current Speed']))
                DMI['processor', i, 'External Clock'] = str(
                    (v['data']['External Clock']))
                DMI['processor', i, 'Family'] = str((v['data']['Family']))
                DMI['processor', i, 'L1 Cache Handle'] = str(
                    (v['data']['L1 Cache Handle']))
                DMI['processor', i, 'L2 Cache Handle'] = str(
                    (v['data']['L2 Cache Handle']))
                DMI['processor', i, 'L3 Cache Handle'] = str(
                    (v['data']['L3 Cache Handle']))
                DMI['processor', i, 'Manufacturer'] = str(
                    (v['data']['Manufacturer']['Vendor']))
                DMI['processor', i, 'Max Speed'] = str(
                    (v['data']['Max Speed']))
                DMI['processor', i, 'Part Number'] = str(
                    (v['data']['Part Number']))
                DMI['processor', i, 'Serial Number'] = str(
                    (v['data']['Serial Number']))
                DMI['processor', i, 'Socket Designation'] = str(
                    (v['data']['Socket Designation']))
                DMI['processor', i, 'Status'] = str((v['data']['Status']))
                DMI['processor', i, 'Thread Count'] = str(
                    (v['data']['Thread Count']))
                DMI['processor', i, 'Type'] = str((v['data']['Type']))
                DMI['processor', i, 'Upgrade'] = str((v['data']['Upgrade']))
                DMI['processor', i, 'Version'] = str((v['data']['Version']))
                DMI['processor', i, 'Voltage'] = str((v['data']['Voltage']))
                i += 1

        # get Memory Data
        #tmp = dmidecode.memory()
        #pprint(tmp)
        i = 0
        for v in dmidecode.memory().values():
            if type(v) == dict and v['dmi_type'] == 17:
                if str((v['data']['Size'])) != 'None':
                    DMI['memory', i, 'Data Width'] = str(
                        (v['data']['Data Width']))
                    DMI['memory', i, 'Error Information Handle'] = str(
                        (v['data']['Error Information Handle']))
                    DMI['memory', i, 'Form Factor'] = str(
                        (v['data']['Form Factor']))
                    DMI['memory', i, 'Bank Locator'] = str(
                        (v['data']['Bank Locator']))
                    DMI['memory', i, 'Locator'] = str((v['data']['Locator']))
                    DMI['memory', i, 'Manufacturer'] = str(
                        (v['data']['Manufacturer']))
                    DMI['memory', i, 'Part Number'] = str(
                        (v['data']['Part Number']))
                    DMI['memory', i, 'Serial Number'] = str(
                        (v['data']['Serial Number']))
                    DMI['memory', i, 'Size'] = str((v['data']['Size']))
                    DMI['memory', i, 'Speed'] = str((v['data']['Speed']))
                    DMI['memory', i, 'Type'] = str((v['data']['Type']))
                    i += 1

        # get cache Data
        #tmp = dmidecode.cache()
        #pprint(tmp)

        # get connector Data
        #tmp = dmidecode.connector()
        #pprint(tmp)

        # get slot Data
        #tmp = dmidecode.slot()
        #pprint(tmp)

        return DMI
Beispiel #10
0
	def __init__(self):
		#Get all required system info
		for v in dmidecode.system().values():
                	if type(v) == dict and v['dmi_type'] == 1:
                        	self.Mfg = str((v['data']['Manufacturer']))
                        	self.Model = str((v['data']['Product Name']))
                        	self.Serial = str((v['data']['Serial Number']))
		for x in dmidecode.chassis().values():
                        if type(x) == dict and x['dmi_type'] == 3:
				self.FFactor = str((x['data']['Type']))
        	for x in dmidecode.processor().values():
                	if type(x) == dict and x['dmi_type'] == 4:
                        	self.CPUMfg = str((x['data']['Manufacturer']))
                        	self.CPUFam = str((x['data']['Family']))
                        	self.CPUVer = str((x['data']['Version']))
                        	self.CPUFrq = str((x['data']['Current Speed']))
        	for x in dmidecode.memory().values():
                	if type(x) == dict and x['dmi_type'] == 17:
                        	self.MEMSize = str((x['data']['Size']))
                        	self.MEMType = str((x['data']['Type']))
                        	self.MEMDeta = str((x['data']['Type Detail']))
                        	self.MEMSpeed = str((x['data']['Speed']))
		for x in dmidecode.baseboard().values():
                        if type(x) == dict and x['dmi_type'] == 10:
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Video":
					self.Video = str((x['data']['dmi_on_board_devices'][0]['Description']))
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Sound":
                                        self.Audio = str((x['data']['dmi_on_board_devices'][0]['Description']))
				if str((x['data']['dmi_on_board_devices'][0]['Type'])) == "Ethernet":
                                        self.Network = str((x['data']['dmi_on_board_devices'][0]['Description'])) 
		### Workarounds for things python-dmidecode doesn't do
        	command = "grep \"model name\" /proc/cpuinfo | uniq | awk -F\" \" {' print $4 $5 \" \" $6 \" \" $8 '} | sed 's/(.\{1,2\})/ /g'"
	        self.CPUName = subprocess.check_output(command, shell=True).strip()
	        command = "MSiz=0; for Size in $(dmidecode -t 17 | grep \"Size:\" | awk {' print $2 '}); do MSiz=$(($MSiz+$Size)); done; echo $MSiz"
	        self.MEMSize = subprocess.check_output(command, shell=True).strip()
	        command = "dmidecode -t 17 | grep \"Type:\" | awk {' print $2 '} | uniq"
	        self.MEMType = subprocess.check_output(command, shell=True).strip()
		if self.Video is None:
	        	command = "lspci | grep VGA | awk -F: {' print $3 '}"
	        	self.Video = subprocess.check_output(command, shell=True).strip()
		if self.Audio is None:
	        	command = "lspci | grep Audio | awk -F: {' print $3 '}"
	        	self.Audio = subprocess.check_output(command, shell=True).strip()
		if self.Network is None:
	        	command = "lspci | grep Ethernet | awk -F: {' print $3 '}"
	        	self.Network = subprocess.check_output(command, shell=True).strip()
		command = "lspci | grep 802.11 | awk -F: {' print $3 '}"
                self.WiFi = subprocess.check_output(command, shell=True).strip()
		command = "echo \"Not Yet Implemented\""
                self.Battery = subprocess.check_output(command, shell=True).strip()
		### Get hard drive info
		self.Drive = []
		command = "lshw -C disk"
		CMDOutput = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
		Type = None
		Model = None
		Vendor = None
		Device = None
		Serial = None
		Size = 0
		SectSize = 0
		for line in CMDOutput.stdout:
			if "*-" in line:
				#print("Found: "+line)
				Line = line.split('-', 1)
				Type = Line[1].strip()
			if "product:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Model = Line[1].strip()
			if "vendor:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Vendor = Line[1].strip()
			if "logical name:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Device = Line[1].strip()
			if "serial:" in line:
				#print("Found: "+line)
				Line = line.split(':', 1)
				Serial = Line[1].strip()
			if "size:" in line:
				command = "fdisk -l /dev/sda | grep \""+Device+":\" | awk {' print $5 '}"
				Size = subprocess.check_output(command, shell=True).strip()
				#print("Size: "+Size)
				command = "fdisk -l /dev/sda | grep \"Sector\" | awk {' print $4 '}"
				SectSize = subprocess.check_output(command, shell=True).strip()
				#print("SectSize: "+SectSize)
			if "configuration:" in line:
				Dev = Device.split('/', 2)
				if (Type == "cdrom"):
					self.Optical = Vendor+" "+Model
				else:
					if Vendor is None:
						Line = Model.split(' ', 1)
						Vendor = Line[0].strip()
						Model = Line[1].strip()
					self.Drive.append(self.Disk(Type, Model, Vendor, Device, Serial, Size, SectSize))
				Type = None
				Model = None
				Vendor = None
				Device = None
				Serial = None
				Size = 0
				SectSize = 0
Beispiel #11
0
def run(options, steps):
    if not steps:
        steps = ["fw-updates", "oob-config", "intake", "reboot"]

    try:
        system = dmidecode.system()
        system_manufacturer = [
            v for k, v in system.items() if 'Manufacturer' in v['data']
        ][0]['data']['Manufacturer']
        if system_manufacturer.startswith("HP"):
            system_manufacturer = "HP"
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in system.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        elif system_manufacturer.startswith("Dell"):
            system_manufacturer = "Dell"
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in system.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        elif system_manufacturer.startswith("Supermicro"):
            system_manufacturer = "Supermicro"
            baseboard = dmidecode.baseboard()
            model = [
                v for k, v in system.items() if 'Product Name' in v['data']
            ][0]['data']['Product Name'].strip()
            if model in ('Super Server', 'To be filled by O.E.M.'):
                model = [
                    v for k, v in baseboard.items()
                    if 'Product Name' in v['data']
                ][0]['data']['Product Name'].strip()
            asset_tag = [
                v for k, v in baseboard.items() if 'Serial Number' in v['data']
            ][0]['data']['Serial Number'].strip()
        else:
            raise Exception("Unknown")
    except:
        system_manufacturer = "Unknown"
        model = "Unknown"
        asset_tag = "Unknown"

    security_qs = {}
    if options.hmac:
        security_qs['hmac'] = options.hmac
    if options.nonce:
        security_qs['nonce'] = options.nonce

    while True:
        try:
            response = requests.get("%sconfig/%s" % (options.url, asset_tag),
                                    params=security_qs,
                                    verify=False,
                                    headers={"Accept": "application/json"})
        except:
            response = None
        if response is not None and response.status_code == 200:
            break
        else:
            time.sleep(5)

    configuration = response.text
    configuration_file = "/tmp/sot.conf"
    with open(configuration_file, 'w') as f:
        f.write(configuration)

    for step in steps:
        # Special steps implemented here
        data = None
        if step == 'reboot':
            subprocess.call(["/sbin/shutdown", "-r", "+1"])
            data = {'msg': 'rebooting'}
            ret = 1
        elif step == 'poweroff':
            subprocess.call(["/sbin/shutdown", "-h", "+1"])
            data = {'msg': 'powering off'}
            ret = 1
        else:
            p = subprocess.Popen([
                os.path.join(options.path, step), system_manufacturer, model,
                asset_tag, configuration_file
            ],
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            stdout, stderr = p.communicate()
            ret = p.returncode
            try:
                data = json.loads(stdout)
            except:
                pass
        report = {
            'step': step,
            'data': data,
            'returncode': p.returncode,
            'stderr': stderr
        }
        response = requests.post("%sintake/%s" % (options.url, asset_tag),
                                 data=json.dumps(report),
                                 params=security_qs,
                                 verify=False,
                                 headers={
                                     "Content-Type": "application/json",
                                     "Accept": "application/json"
                                 })
        if ret != 0 or data is None or (
                'failed' in data
                and data['failed']) or response.status_code not in [200, 201]:
            sys.stderr.write(
                "Failed to run step %s, report %r, response code is %s\n" %
                (step, report, response.status_code))
            break