Python win32file.DeviceIoControl() Examples

The following are 19 code examples of win32file.DeviceIoControl(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32file , or try the search function .
Example #1
Source File: win32.py    From multibootusb with GNU General Public License v2.0 7 votes vote down vote up
def lockPhysicalDrive(handle, logfunc=lambda s: None):
    try:
        win32file.DeviceIoControl(
            handle, winioctlcon.FSCTL_ALLOW_EXTENDED_DASD_IO,
            None, 0, None)
    except pywintypes.error as e:
        logfunc('IO boundary checks diabled.')
    for retry in range(20):
        try:
            win32file.DeviceIoControl(handle, winioctlcon.FSCTL_LOCK_VOLUME,
                                      None, 0, None)
            return
        except pywintypes.error as e:
            logfunc( str(e) )
            time.sleep(1)
    raise RuntimeError("Couldn't lock the Volume.") 
Example #2
Source File: win32.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def ZapMBRGPT(self, disk_size, sector_size, add1MB):
        self.assert_physical_drive()
        # Implementation borrowed from rufus: https://github.com/pbatard/rufus
        num_sectors_to_clear \
            = (add1MB and 2048 or 0) + self.MAX_SECTORS_TO_CLEAR
        zeroBuf = b'\0' * sector_size
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        offset = disk_size - self.MAX_SECTORS_TO_CLEAR * sector_size
        win32file.SetFilePointer(self.h, offset, win32con.FILE_BEGIN)
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        # We need to append paddings as CREATE_DISK structure contains a union.
        param = struct.pack('<IIIHH8s',
                            winioctlcon.PARTITION_STYLE_MBR, 0xdeadbeef,
                            0,0,0,b'abcdefgh')
        win32file.DeviceIoControl(
            self.h, winioctlcon.IOCTL_DISK_CREATE_DISK, param, 0, None) 
Example #3
Source File: win32.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def ZapPhysicalDrive(target_drive, get_volume_info_func, log_func):
    with openHandle('\\\\.\\PhysicalDrive%d' % target_drive, True, False,
                    lambda s:sys.stdout.write(s+'\n')) as hDrive:
        hDrive.LockPhysicalDrive()
        geom = hDrive.DiskGeometory()
        for v in get_volume_info_func(target_drive):
            volume_path = '\\\\.\\'+v.DeviceID
            log_func('Dismounting volume ' + volume_path)
            with openHandle(volume_path, False, False) as h:
                x = win32file.DeviceIoControl(
                    h.h, winioctlcon.FSCTL_DISMOUNT_VOLUME, None, None)
                print ('FSCTL_DISMOUNT_VOLUME=>%s' % x)
            x = win32file.DeleteVolumeMountPoint(volume_path+'\\')
            log_func('DeleteVolumeMountPoint=>%s' % x)
        else:
            log_func('No volumes on %s' % target_drive)

        add1MB = False
        hDrive.ZapMBRGPT(geom.disk_size, geom.bytes_per_sector, add1MB) 
Example #4
Source File: winpmem.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def ParseMemoryRuns(self):
        self.runs = []

        result = win32file.DeviceIoControl(
            self.fd, INFO_IOCTRL, "", 102400, None)

        fmt_string = "Q" * len(self.FIELDS)
        self.memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
                    fmt_string, result)))

        self.dtb = self.memory_parameters["CR3"]
        self.kdbg = self.memory_parameters["KDBG"]

        offset = struct.calcsize(fmt_string)

        for x in range(self.memory_parameters["NumberOfRuns"]):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            self.runs.append((start, length)) 
Example #5
Source File: winpmem.py    From Fastir_Collector with GNU General Public License v3.0 6 votes vote down vote up
def ParseMemoryRuns(self):
        self.runs = []

        result = win32file.DeviceIoControl(
            self.fd, INFO_IOCTRL, "", 102400, None)

        fmt_string = "Q" * len(self.FIELDS)
        self.memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
            fmt_string, result)))

        self.dtb = self.memory_parameters["CR3"]
        self.kdbg = self.memory_parameters["KDBG"]

        offset = struct.calcsize(fmt_string)

        for x in range(self.memory_parameters["NumberOfRuns"]):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            self.runs.append((start, length)) 
Example #6
Source File: win32.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def ParseMemoryRuns(self, fhandle):
        # Set acquisition mode. If the driver does not support this mode it will
        # just fall back to the default.
        win32file.DeviceIoControl(
            fhandle, CTRL_IOCTRL,
            struct.pack("I", PMEM_MODE_PTE), 4, None)

        result = win32file.DeviceIoControl(
            fhandle, INFO_IOCTRL, b"", 102400, None)

        fmt_string = "Q" * len(self.FIELDS)
        self.memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
            fmt_string, result)))

        offset = struct.calcsize(fmt_string)
        for x in range(self.memory_parameters["NumberOfRuns"]):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            self.add_run(start, start, length, self.fhandle_as) 
Example #7
Source File: win32pmem.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def ParseMemoryRuns(self):
        result = win32file.DeviceIoControl(
            self.fhandle, INFO_IOCTRL, "", 102400, None)

        fmt_string = "Q" * len(self.FIELDS)
        memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
                    fmt_string, result)))

        self.dtb = memory_parameters["CR3"]

        offset = struct.calcsize(fmt_string)

        for x in xrange(memory_parameters["NumberOfRuns"]):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            self.runs.append((start, start, length)) 
Example #8
Source File: win32.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def DiskGeometory(self):
        self.assert_physical_drive()
        o = win32file.DeviceIoControl(
            self.h, winioctlcon.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
            None, 256, None)
        return self.geometory_tuple(*struct.unpack('<qiiiiq', o[:32])) 
Example #9
Source File: platform.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def get_allocated_regions(path, f=None, begin=0, length=None):
    supported = get_sparse_files_support(path)
    if not supported:
        return
    if os.name == 'nt':
        if not os.path.exists(path):
            return False
        if f is None:
            f = file(path, 'r')
        handle = win32file._get_osfhandle(f.fileno())
        if length is None:
            length = os.path.getsize(path) - begin
        a = SparseSet()
        run = 128
        i = begin
        end = begin + length
        while i < end:
            d = struct.pack("<QQ", i, length)
            try:
                r = win32file.DeviceIoControl(handle, FSCTL_QUERY_ALLOCATED_RANGES,
                                              d, struct.calcsize("<QQ")*run, None)
            except pywintypes.error, e:
                if e.args[0] == winerror.ERROR_MORE_DATA:
                    run *= 2
                    continue
                # I've also seen:
                # error: (1784, 'DeviceIoControl', 'The supplied user buffer is not valid for the requested operation.')
                return
            if not r:
                break
            for c in xrange(0, len(r), 16):
                qq = struct.unpack("<QQ", r[c:c+16])
                b = qq[0]
                e = b + qq[1]
                a.add(b, e)
                i = max(i, e)

        return a 
Example #10
Source File: Storage_base.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _sparse_magic(handle, length=0):
        win32file.DeviceIoControl(handle, FSCTL_SET_SPARSE, '', 0, None)

        win32file.SetFilePointer(handle, length, win32file.FILE_BEGIN)
        win32file.SetEndOfFile(handle)

        win32file.SetFilePointer(handle, 0, win32file.FILE_BEGIN) 
Example #11
Source File: winpmem.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def SetMode(self):
        mode = 1
        win32file.DeviceIoControl(
            self.fd, CTRL_IOCTRL, struct.pack("I", mode), 0, None) 
Example #12
Source File: winpmem.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def GetInfoDeprecated(self):
        result = win32file.DeviceIoControl(self.fd, INFO_IOCTRL_DEPRECATED, "",
                                           1024, None)
        fmt_string = "QQl"
        offset = struct.calcsize(fmt_string)

        cr3, kpcr, number_of_runs = struct.unpack_from(fmt_string, result)
        for x in range(number_of_runs):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            print "0x%X\t\t0x%X" % (start, length) 
Example #13
Source File: utils_rawstring.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def get_physical_drive_size(drive="\\\\.\\PhysicalDrive0"):
    """Uses IOCTL to get physical drives size"""
    handle = win32file.CreateFile(drive, 0, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, 0)
    if handle:
        IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000
        info = win32file.DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, '', 24)
        win32file.CloseHandle(handle)
        if info:
            (cyl_lo, cyl_hi, media_type, tps, spt, bps) = struct.unpack('6L', info)
            mediasize = ((cyl_hi << 32) + cyl_lo) * tps * spt * bps
            """print mediasize, 'bytes'
            print mediasize/10**3, 'kbytes'
            print mediasize/10**6, 'Mbytes'
            print mediasize/10**9, 'Gbytes'"""
            return mediasize 
Example #14
Source File: winpmem.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def SetMode(self):
        if FLAGS.mode == "iospace":
            mode = 0
        elif FLAGS.mode == "physical":
            mode = 1
        elif FLAGS.mode == "pte":
            mode = 2
        elif FLAGS.mode == "pte_pci":
            mode = 3
        else:
            raise RuntimeError("Mode %s not supported" % FLAGS.mode)

        win32file.DeviceIoControl(
            self.fd, CTRL_IOCTRL, struct.pack("I", mode), 0, None) 
Example #15
Source File: winpmem.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def GetInfoDeprecated(self):
        result = win32file.DeviceIoControl(self.fd, INFO_IOCTRL_DEPRECATED, "",
                                           1024, None)
        fmt_string = "QQl"
        offset = struct.calcsize(fmt_string)

        cr3, kpcr, number_of_runs = struct.unpack_from(fmt_string, result)
        for x in range(number_of_runs):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            print("0x%X\t\t0x%X" % (start, length)) 
Example #16
Source File: win32.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def findVolumeGuids():
    DiskExtent = collections.namedtuple(
        'DiskExtent', ['DiskNumber', 'StartingOffset', 'ExtentLength'])
    Volume = collections.namedtuple(
        'Volume', ['Guid', 'MediaType', 'DosDevice', 'Extents'])
    found = []
    h, guid = FindFirstVolume()
    while h and guid:
        #print (guid)
        #print (guid, win32file.GetDriveType(guid),
        #       win32file.QueryDosDevice(guid[4:-1]))
        hVolume = win32file.CreateFile(
            guid[:-1], win32con.GENERIC_READ,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL,  None)
        extents = []
        driveType = win32file.GetDriveType(guid)
        if driveType in [win32con.DRIVE_REMOVABLE, win32con.DRIVE_FIXED]:
            x = win32file.DeviceIoControl(
                hVolume, winioctlcon.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
                None, 512, None)
            instream = io.BytesIO(x)
            numRecords = struct.unpack('<q', instream.read(8))[0]
            fmt = '<qqq'
            sz = struct.calcsize(fmt)
            while 1:
                b = instream.read(sz)
                if len(b) < sz:
                    break
                rec = struct.unpack(fmt, b)
                extents.append( DiskExtent(*rec) )
        vinfo = Volume(guid, driveType, win32file.QueryDosDevice(guid[4:-1]),
                       extents)
        found.append(vinfo)
        guid = FindNextVolume(h)
    return found 
Example #17
Source File: tun-ping-responder.py    From pyvpn with The Unlicense 4 votes vote down vote up
def openTunTap():
    '''
    \brief Open a TUN/TAP interface and switch it to TUN mode.
    
    \return The handler of the interface, which can be used for later
        read/write operations.
    '''
    
    # retrieve the ComponentId from the TUN/TAP interface
    componentId = get_tuntap_ComponentId()
    print('componentId = {0}'.format(componentId))
    
    # create a win32file for manipulating the TUN/TAP interface
    tuntap = win32file.CreateFile(
        r'\\.\Global\%s.tap' % componentId,
        win32file.GENERIC_READ    | win32file.GENERIC_WRITE,
        win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
        None,
        win32file.OPEN_EXISTING,
        win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_FLAG_OVERLAPPED,
        None
    )
    print('tuntap      = {0}'.format(tuntap.handle))
    
    # have Windows consider the interface now connected
    win32file.DeviceIoControl(
        tuntap,
        TAP_IOCTL_SET_MEDIA_STATUS,
        '\x00\x00\x00\x00',
        None
    )
    
    # prepare the parameter passed to the TAP_IOCTL_CONFIG_TUN commmand.
    # This needs to be a 12-character long string representing
    # - the tun interface's IPv4 address (4 characters)
    # - the tun interface's IPv4 network address (4 characters)
    # - the tun interface's IPv4 network mask (4 characters)
    configTunParam  = []
    configTunParam += TUN_IPv4_ADDRESS
    configTunParam += TUN_IPv4_NETWORK
    configTunParam += TUN_IPv4_NETMASK
    configTunParam  = ''.join([chr(b) for b in configTunParam])
    
    # switch to TUN mode (by default the interface runs in TAP mode)
    win32file.DeviceIoControl(
        tuntap,
        TAP_IOCTL_CONFIG_TUN,
        configTunParam,
        None
    )
    
    # return the handler of the TUN interface
    return tuntap

#=== misc 
Example #18
Source File: interface.py    From XFLTReaT with MIT License 4 votes vote down vote up
def win_set_ip_address(self, dev, ip, serverip, netmask):
		TAP_WIN_IOCTL_CONFIG_TUN = self.WIN_TAP_CONTROL_CODE(10, 0)
		TAP_WIN_IOCTL_CONFIG_DHCP_MASQ = self.WIN_TAP_CONTROL_CODE(7, 0)

		integer_ip = struct.unpack(">I", socket.inet_aton(ip))[0]
		integer_network = struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask))
		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		settings = socket.inet_aton(ip) + integer_network + integer_netmask

		win32file.DeviceIoControl(self.wintun, TAP_WIN_IOCTL_CONFIG_TUN,
			settings, 1, None)

		lease = '\x10\x0e\x00\x00'
		settings = socket.inet_aton(ip) + integer_netmask + socket.inet_aton(ip) + lease

		iface_name = self.WIN_get_subinterface_name()
		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		netmask = socket.inet_ntoa(integer_netmask)

		# server mode
		if serverip == ip:
			ps = subprocess.Popen(["netsh", "interface", "ipv4", "set", "address", "name={0}".format(iface_name),
				"source=static", "address={0}".format(ip), "mask={0}".format(netmask)], stdout=subprocess.PIPE,
				stderr=subprocess.PIPE)
			(stdout, stderr) = ps.communicate()

			if stderr != "":
				common.internal_print("Cannot set IP. netsh failed: {0}".format(stdout), -1)
				sys.exit(-1)

		# client mode
		else:
			ps = subprocess.Popen(["netsh", "interface", "ipv4", "set", "address", "name={0}".format(iface_name),
				"source=static", "address={0}".format(ip), "mask={0}".format(netmask),"gateway={0}".format(serverip)],
				stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			(stdout, stderr) = ps.communicate()

			if stderr != "":
				common.internal_print("Cannot set IP. netsh failed: {0}".format(stdout), -1)
				sys.exit(-1)

		return 
Example #19
Source File: interface.py    From XFLTReaT with MIT License 4 votes vote down vote up
def win_tun_alloc(self, dev, flags):
		TAP_IOCTL_SET_MEDIA_STATUS 	= self.WIN_TAP_CONTROL_CODE(6, 0)
		import pywintypes

		guid = self.WIN_get_device_guid()
		if not guid:
			common.internal_print("Please install OpenVPN's Windows TAP driver (NDIS 6) to use XFLTReaT\r\nhttps://openvpn.net/index.php/open-source/downloads.html", -1)
			sys.exit(-1)

		# create a win32file for manipulating the TUN/TAP interface
		try:
			self.wintun = win32file.CreateFile("\\\\.\\Global\\{0}.tap".format(guid),
				win32file.GENERIC_READ | win32file.GENERIC_WRITE,
				win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
				None, win32file.OPEN_EXISTING,
				win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_FLAG_NO_BUFFERING | win32file.FILE_FLAG_OVERLAPPED,
				None)
		except pywintypes.error as e:
			if e.args[0] == 31: # A device attached to the system is not functioning.
				common.internal_print("The TUN device is already in use. Maybe another XFLTReaT is running.", -1)
				sys.exit(-1)	


		# have Windows consider the interface now connected
		win32file.DeviceIoControl(self.wintun, TAP_IOCTL_SET_MEDIA_STATUS, '\x01\x00\x00\x00', 1, None)

		return self.wintun