Exemple #1
0
def get_root_hub_name(handle):
    buf = win32file.DeviceIoControl(handle, IOCTL_USB_GET_ROOT_HUB_NAME, None,
                                    6, None)
    act_len, _ = struct.unpack('LH', buf)
    buf = win32file.DeviceIoControl(handle, IOCTL_USB_GET_ROOT_HUB_NAME, None,
                                    act_len, None)
    return buf[4:].decode('utf-16le')
Exemple #2
0
        def openTunTap(self):
            guid = self.get_device_guid()

            tun_handle = win32file.CreateFile(
                r'\\.\Global\%s.tap' % 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_OVERLAPPED, None)

            win32file.DeviceIoControl(tun_handle,
                self.TAP_IOCTL_SET_MEDIA_STATUS,
                '\x01\x00\x00\x00',
                None)

            configTunParam  = []
            configTunParam += self.tun_ipv4_address
            configTunParam += self.tun_ipv4_network
            configTunParam += self.tun_ipv4_netmask
            configTunParam  = ''.join([chr(b) for b in configTunParam])

            win32file.DeviceIoControl(
                tun_handle,
                self.TAP_IOCTL_CONFIG_TUN,
                configTunParam,
                None)

            return tun_handle
Exemple #3
0
    def get_device_size(self, name, partition=0):
        assert partition == 0

        import win32file
        import win32con
        import winioctlcon
        import win32api
        import struct

        hFile = win32file.CreateFile(name, win32con.GENERIC_READ, 0, None,
                                     win32con.OPEN_EXISTING, 0, None)
        buffer = " " * 1024
        data = win32file.DeviceIoControl(
            hFile, winioctlcon.IOCTL_DISK_GET_DRIVE_GEOMETRY, buffer, 1024)
        tup = struct.unpack("qiiii", data)
        if tup[1] in (winioctlcon.FixedMedia, winioctlcon.RemovableMedia):
            size = reduce(int.__mul__, tup[:1] + tup[2:])
            logging.debug("Found FixedMedia or RemovableMedia of size " +
                          str(size))
        data = win32file.DeviceIoControl(
            hFile, winioctlcon.IOCTL_DISK_GET_LENGTH_INFO, buffer, 1024)
        win32api.CloseHandle(hFile)
        if data:
            tup = struct.unpack("q", data)
            size = tup[0]
            logging.debug("Found regular device of size " + str(size))
        return size >> 9
def freeDrive(drive):
    try:
        hVol = msvcrt.get_osfhandle(drive.fileno())
        win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_DISMOUNT_VOLUME,None, None)
        win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_UNLOCK_VOLUME,None, None)
    except:
        #no operations performed
        exit
Exemple #5
0
def get_ext_hub_name(handle, index):
    hub_name = chr(index) + '\0' * 9
    buf = win32file.DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_NAME,
                                    hub_name, 10, None)
    _, act_len, _ = struct.unpack('LLH', buf)
    buf = win32file.DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_NAME,
                                    hub_name, act_len, None)
    return buf[8:].decode('utf-16le')
def demo():
    """
    Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION:
    typedef struct _TXFS_CREATE_MINIVERSION_INFO{
        USHORT StructureVersion;
        USHORT StructureLength;
        ULONG BaseVersion;
        USHORT MiniVersion;}
    """
    buf_fmt='HHLH0L'   ## buffer size must include struct padding
    buf_size=struct.calcsize(buf_fmt)

    tempdir=win32api.GetTempPath()
    tempfile=win32api.GetTempFileName(tempdir,'cft')[0]
    print("Demonstrating transactions on tempfile", tempfile)
    f=open(tempfile,'w')
    f.write('This is original file.\n')
    f.close()

    trans=win32transaction.CreateTransaction(Description='Test creating miniversions of a file')
    hfile=win32file.CreateFileW(tempfile, win32con.GENERIC_READ|win32con.GENERIC_WRITE,
        win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
        None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans)

    win32file.WriteFile(hfile, str2bytes('This is first miniversion.\n'))
    buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None)
    struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf)

    win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN)
    win32file.WriteFile(hfile, str2bytes('This is second miniversion!\n'))
    buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,None,buf_size,None)
    struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf)
    hfile.Close()

    ## miniversions can't be opened with write access
    hfile_0=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
        win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
        None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=base_ver)
    print('version:',base_ver,win32file.ReadFile(hfile_0, 100))
    hfile_0.Close()

    hfile_1=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
        win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
        None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=ver_1)
    print('version:',ver_1,win32file.ReadFile(hfile_1, 100))
    hfile_1.Close()

    hfile_2=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
        win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
        None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=ver_2)
    print('version:',ver_2,win32file.ReadFile(hfile_2, 100))
    hfile_2.Close()

    ## MiniVersions are destroyed when transaction is committed or rolled back
    win32transaction.CommitTransaction(trans)

    os.unlink(tempfile)
Exemple #7
0
def lock_volume(vol):
    hVol = msvcrt.get_osfhandle(vol.fileno())
    win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_LOCK_VOLUME, None, None)

    try:
        yield vol
    finally:
        try:
            vol.flush()
        finally:
            win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_UNLOCK_VOLUME,
                                      None, None)
Exemple #8
0
 def _createTunIf(self):
     '''
     Open a TUN/TAP interface and switch it to TUN mode.
     
     :returns: The handler of the interface, which can be used for later
         read/write operations.
     '''
     
     # retrieve the ComponentId from the TUN/TAP interface
     componentId = self._get_tuntap_ComponentId()
     
     # create a win32file for manipulating the TUN/TAP interface
     tunIf = 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
     )
     
     # have Windows consider the interface now connected
     win32file.DeviceIoControl(
         tunIf,
         TAP_IOCTL_SET_MEDIA_STATUS,
         '\x01\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(
         tunIf,
         TAP_IOCTL_CONFIG_TUN,
         configTunParam,
         None
     )
     
     # return the handler of the TUN interface
     return tunIf
Exemple #9
0
def get_driverkey_name(handle, index):
    key_name = chr(index) + '\0' * 9
    try:
        buf = win32file.DeviceIoControl(
            handle, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, key_name, 10,
            None)
    except pywintypes.error as e:
        print(e.strerror, index)
        sys.exit(1)
    _, act_len, _ = struct.unpack('LLH', buf)
    buf = win32file.DeviceIoControl(
        handle, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, key_name,
        act_len, None)
    return buf[8:].decode('utf-16le')
Exemple #10
0
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.")
Exemple #11
0
 def updateMAC(self):
     #The following command can not have an overlapped structure passed to it (throws invalid command exception)
     self.myMACaddr = win32file.DeviceIoControl(self.myInterface,
                                                self.TAP_IOCTL_GET_MAC,
                                                None, 16)
     alert("MAC address updated: " + str(self.myMACaddr))
     return self.myMACaddr
Exemple #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help="Increase output verbosity.")
    args = parser.parse_args()

    for i in range(10):
        name = r"\\.\HCD{}".format(i)
        handle = open_dev(name)
        if not handle:
            continue

        root = get_root_hub_name(handle)
        print('{}RootHub: {}'.format('\n' if i != 0 else '', root))

        dev_name = r'\\.\{}'.format(root)
        dev_handle = open_dev(dev_name)
        if not dev_handle:
            print('Failed to open device {}'.format(dev_name))
            continue
        buf = win32file.DeviceIoControl(dev_handle,
                                        IOCTL_USB_GET_NODE_INFORMATION, None,
                                        76, None)
        print_hub_ports(dev_handle, ord(buf[6]), args.verbose, 0)
        dev_handle.close()
        handle.close()
Exemple #13
0
    def ParseMemoryRuns(self):
        result = win32file.DeviceIoControl(self.fhandle, INFO_IOCTRL, "",
                                           102400, None)

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

        if not self.get_config().dtb:
            self.dtb = self.memory_parameters["CR3"]
            self.get_config().dtb = self.dtb
        else:
            self.dtb = self.get_config().dtb

        if not self.get_config().process_id:
            self.process_id = 0
            self.get_config().process_id = 0
        else:
            self.process_id = self.get_config().process_id

        logging.debug("PmemAddressSpace dtb:{0} process_id:{1}".format(
            self.dtb, self.process_id))
        #rajesh
        #self.session.SetParameter("dtb", int(self.dtb))

        offset = struct.calcsize(fmt_string)

        for x in xrange(self.memory_parameters["NumberOfRuns"]):
            start, length = struct.unpack_from("QQ", result, x * 16 + offset)
            #print "FileAddressSpace inserting run start:{0} start:{1} length:{2}".format(start, start, length)
            self.runs.append((start, start, length))
Exemple #14
0
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()
        interval = 10000000
        i = begin
        end = begin + length
        while i < end:
            d = struct.pack("<QQ", i, interval)
            try:
                r = win32file.DeviceIoControl(handle,
                                              FSCTL_QUERY_ALLOCATED_RANGES, d,
                                              interval, None)
            except pywintypes.error, e:
                # I've seen:
                # error: (1784, 'DeviceIoControl', 'The supplied user buffer is not valid for the requested operation.')
                return
            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 += interval

        return a
Exemple #15
0
    def property(self, property, value=None):
        '''
		Get or set property
		
		@type	property: string
		@param	property: Name of method to invoke
		@type	value: object
		@param	value: Value to set.  If None, return property instead
		'''

        win32file.DeviceIoControl(self.hDevice,
                                  self.IOCTL_PEACH_METHOD_PROPERTY, property,
                                  1)

        win32file.DeviceIoControl(self.hDevice, self.IOCTL_PEACH_METHOD_DATA,
                                  value, 1)
Exemple #16
0
 def _ioctl(self, ioctlCode, buffer="", outSize=0):
     self.log("Sending ioctl %s: '%s'" % (
         hex(ioctlCode),
         buffer.encode("hex"),
     ))
     return win32file.DeviceIoControl(self._driverHandle, ioctlCode, buffer,
                                      outSize)
Exemple #17
0
    def Run(self, args):
        """Run."""
        # This action might crash the box so we need to flush the transaction log.
        self.SyncTransactionLog()

        # Do any initialization we need to do.
        logging.debug("Querying device %s", args.path)

        fd = win32file.CreateFile(
            args.path, win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

        data = win32file.DeviceIoControl(fd, INFO_IOCTRL, "", 1024, None)
        fmt_string = "QQl"
        cr3, _, number_of_runs = struct.unpack_from(fmt_string, data)

        result = rdfvalue.MemoryInformation(
            cr3=cr3,
            device=rdfvalue.PathSpec(
                path=args.path, pathtype=rdfvalue.PathSpec.PathType.MEMORY))

        offset = struct.calcsize(fmt_string)
        for x in range(number_of_runs):
            start, length = struct.unpack_from("QQ", data, x * 16 + offset)
            result.runs.Append(offset=start, length=length)

        self.SendReply(result)
Exemple #18
0
def make_reparse_point(dest, link):
    if dest[-1] == '/' or dest[-1] == '\\':
        dest = dest[:len(dest) - 1]

    link = os.path.abspath(link)

    if link[-1] == '/' or link[-1] == '\\':
        link = link[:len(link) - 1]
    os.mkdir(dest)
    dirh = win32file.CreateFile(
        dest, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
        win32file.OPEN_EXISTING, win32file.FILE_FLAG_OPEN_REPARSE_POINT
        | win32file.FILE_FLAG_BACKUP_SEMANTICS, None)
    tag = 0xA0000003L
    link = '\\??\\' + link
    link = link.encode('utf-16')[2:]
    datalen = len(link)
    inp = struct.pack('LHHHHHH', tag, datalen + 8 + 4, 0, 0, datalen,
                      datalen + 2, 0) + link + '\0\0\0\0'
    try:
        win32file.DeviceIoControl(dirh, winioctlcon.FSCTL_SET_REPARSE_POINT,
                                  inp, None)
    except:
        os.rmdir(dest)
        raise
    finally:
        win32file.CloseHandle(dirh)
Exemple #19
0
def readlink(fpath):
  """ Windows readlink implementation. """
  # This wouldn't return true if the file didn't exist, as far as I know.
  if not islink(fpath):
    return None

  try:
    # Open the file correctly depending on the string type.
    if type(fpath) == unicode:
      handle = win32file.CreateFileW(fpath, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OPEN_REPARSE_POINT | win32file.FILE_FLAG_BACKUP_SEMANTICS, 0)
    else:
      handle = win32file.CreateFile(fpath, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OPEN_REPARSE_POINT | win32file.FILE_FLAG_BACKUP_SEMANTICS, 0)

    # MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 = (16*1024)
    buffer = win32file.DeviceIoControl(handle, winioctlcon.FSCTL_GET_REPARSE_POINT, None, 16*1024)
    # Above will return an ugly string (byte array), so we'll need to parse it.

    # But first, we'll close the handle to our file so we're not locking it anymore.
    win32file.CloseHandle(handle)

    # Minimum possible length (assuming that the length of the target is bigger than 0)
    if len(buffer) < 9:
      return None
    # Parse and return our result.
    result = _parse_reparse_buffer(buffer)
    offset = result[SYMBOLIC_LINK]['substitute_name_offset']
    ending = offset + result[SYMBOLIC_LINK]['substitute_name_length']
    rpath = result[SYMBOLIC_LINK]['buffer'][offset:ending].replace('\x00','')
    if len(rpath) > 4 and rpath[0:4] == '\\??\\':
      rpath = rpath[4:]
    return rpath
  except pywintypes.error, e:
    raise OSError(e.winerror, e.strerror, fpath)
Exemple #20
0
    def map_phys_to_lin(self, PhysStruct):
        if (not win32file.DeviceIoControl(
                self.hDriver, IOCTL_WINIO_MAPPHYSTOLIN, memoryview(PhysStruct),
                memoryview(PhysStruct))):
            raise DeviceIoControlError("Failed on IOCTL_WINIO_MAPPHYSTOLIN")

        return PhysStruct.pvPhysMemLin
Exemple #21
0
    def __get_port_value(self, wPortAddr, bSize):
        if bSize not in [1, 2, 4]:
            raise InvalidArgumentError(
                'Argument "bSize" only accept 1, 2, 4. Current value : %s!' %
                (str(bSize)))

        # If this is a 64 bit OS, we must use the driver to access I/O ports
        # even if the application is 32 bit
        if self.__is_64bit_os():
            PortStruct = tagPortStruct()
            PortStruct.bSize = bSize
            PortStruct.wPortAddr = wPortAddr

            return struct.unpack(
                '@L',
                win32file.DeviceIoControl(self.hDriver, IOCTL_WINIO_READPORT,
                                          memoryview(PortStruct), 4))[0]
        else:
            if bSize == 1:
                return ctypes.c_ubyte(
                    ctypes.cdll.msvcrt._inp(ctypes.c_ushort(wPortAddr))).value
            elif bSize == 2:
                return ctypes.c_ushort(
                    ctypes.cdll.msvcrt._inpw(ctypes.c_ushort(wPortAddr))).value
            elif bSize == 4:
                return ctypes.c_ulong(
                    ctypes.cdll.msvcrt._inpd(ctypes.c_ushort(wPortAddr))).value
Exemple #22
0
    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)
Exemple #23
0
 def setMediaConnectionStatus(self, toConnected):
     #In most TunTap examples, the following line omits an overlapped structure. However, the windows documentation says it should be used
     #if the handle is created with the overlapped flag set. The offsets should be initialized to zero, then left unused.
     win32file.DeviceIoControl(self.myInterface,
                               self.TAP_IOCTL_SET_MEDIA_STATUS,
                               toConnected.to_bytes(4, "little"), None,
                               self.overlapped)
def GetSystemEncryptionState():
    status = BootEncryptionStatus()

    hDevice = win32file.CreateFile(VERACRYPT_DRIVER_STR, 0, 0, None,
                                   win32file.OPEN_EXISTING, 0, None)
    try:
        win32file.DeviceIoControl(hDevice, VC_IOCTL_GET_BOOT_ENCRYPTION_STATUS,
                                  None, status)
    except pywintypes.error as e:
        print "Call to VeraCrypt driver (GET_BOOT_ENCRYPTION_STATUS) failed with error '%s'" % str(
            e[2])
    finally:
        hDevice.close()

    if status.DriveMounted or status.DriveEncrypted:
        if (not status.SetupInProgress
                and status.ConfiguredEncryptedAreaEnd != 0
                and status.ConfiguredEncryptedAreaEnd != -1
                and status.ConfiguredEncryptedAreaStart
                == status.EncryptedAreaStart and
                status.ConfiguredEncryptedAreaEnd == status.EncryptedAreaEnd):
            return SYSENC_FULL

        if (status.EncryptedAreaEnd < 0 or status.EncryptedAreaStart < 0
                or status.EncryptedAreaEnd <= status.EncryptedAreaStart):
            return SYSENC_NONE

        return SYSENC_PARTIAL
    else:
        return SYSENC_NONE
Exemple #25
0
    def __initialize(self):
        # Try to open the winio device.
        hDriver = None
        try:
            hDriver = win32file.CreateFile(
                r"\\.\WINIO", win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                0, None, win32con.OPEN_EXISTING,
                win32con.FILE_ATTRIBUTE_NORMAL, None)

            # Driver already installed in system as service by user, we must
            # not uninstall it.
            self.__is_need_uninstall_driver = False
        except pywintypes.error as e:
            if e.winerror != EC_FILE_NOT_FOUND:
                raise e

        # If the driver is not running, install it
        if hDriver is None:
            self.install_driver(self.__get_driver_file_path(), True)
            self.__start_driver()

            hDriver = win32file.CreateFile(
                r"\\.\WINIO", win32con.GENERIC_READ | win32con.GENERIC_WRITE,
                win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None,
                win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)

        # Enable I/O port access for this process if running on a 32 bit OS
        if not self.__is_64bit_os():
            win32file.DeviceIoControl(hDriver, IOCTL_WINIO_ENABLEDIRECTIO,
                                      None, 4)

        self.hDriver = hDriver
        self.dll_is_initialized = True
Exemple #26
0
def getblkdevsize(dev):
    """report the size for a block device"""
    size = 0
    if sys.platform == "darwin":
        # mac os x ioctl from sys/disk.h
        import fcntl

        DKIOCGETBLOCKSIZE = 0x40046418  # _IOR('d', 24, uint32_t)
        DKIOCGETBLOCKCOUNT = 0x40086419  # _IOR('d', 25, uint64_t)

        fh = open(dev, "r")
        buf = array.array("B", list(range(0, 4)))  # uint32
        r = fcntl.ioctl(fh.fileno(), DKIOCGETBLOCKSIZE, buf, 1)
        blocksize = struct.unpack("I", buf)[0]
        buf = array.array("B", list(range(0, 8)))  # uint64
        r = fcntl.ioctl(fh.fileno(), DKIOCGETBLOCKCOUNT, buf, 1)
        blockcount = struct.unpack("Q", buf)[0]
        fh.close()
        size = blocksize * blockcount

    elif sys.platform.startswith("freebsd"):
        # freebsd ioctl from sys/disk.h
        import fcntl

        DIOCGMEDIASIZE = 0x40086481  # _IOR('d', 129, uint64_t)

        fh = open(dev, "r")
        buf = array.array("B", list(range(0, 8)))  # off_t / int64
        r = fcntl.ioctl(fh.fileno(), DIOCGMEDIASIZE, buf, 1)
        size = struct.unpack("q", buf)[0]
        fh.close()

    elif sys.platform == "win32":
        # win32 ioctl from winioctl.h, requires pywin32
        try:
            import win32file
        except ImportError:
            raise SystemExit(
                "Package pywin32 not found, see http://sf.net/projects/pywin32/"
            )
        IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000
        dh = win32file.CreateFile(dev, 0, win32file.FILE_SHARE_READ, None,
                                  win32file.OPEN_EXISTING, 0, None)
        info = win32file.DeviceIoControl(dh, IOCTL_DISK_GET_DRIVE_GEOMETRY, "",
                                         24)
        win32file.CloseHandle(dh)
        (cyl_lo, cyl_hi, media_type, tps, spt, bps) = struct.unpack("6L", info)
        size = ((cyl_hi << 32) + cyl_lo) * tps * spt * bps

    else:  # linux or compat
        # linux 2.6 lseek from fcntl.h
        fh = open(dev, "r")
        fh.seek(0, os.SEEK_END)
        size = fh.tell()
        fh.close()

    if not size:
        raise Exception("getblkdevsize: Unsupported platform")

    return size
Exemple #27
0
    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
Exemple #28
0
 def __init__(self, device, mode='r'):
     if 'w' in mode or '+' in mode:
         modes = win32file.GENERIC_READ|win32file.GENERIC_WRITE
     else:
         modes = win32file.GENERIC_READ
     
     try:
         self.iohandle = win32file.CreateFile(
             device,
             modes,
             win32file.FILE_SHARE_READ|win32file.FILE_SHARE_WRITE,
             None,
             win32file.OPEN_EXISTING,
             win32file.FILE_ATTRIBUTE_READONLY|win32file.FILE_FLAG_RANDOM_ACCESS,
             None
         )
         
         diskGeometry = win32file.DeviceIoControl(
             self.iohandle,
             IOCTL_DISK_GET_DRIVE_GEOMETRY,
             '',
             24,
             None
         )
         #~ win32file.GetDiskFreeSpaceEx(device)
     except pywintypes.error, e:     #convert exceptions
         raise IOError(str(e))
def recover(drive):
    hVol = msvcrt.get_osfhandle(drive.fileno())
    win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_LOCK_VOLUME,None, None) 
    index = 0

    for sector in delSecs:
        #Seek to sector, copy 512 bytes of sector
        drive.seek((sector*SECTOR_SIZE))
        data = drive.read(512)
        arr = []
        count = 0

        #Copy all bytes, flip bit at offset 22 (flag)
        for i in data:
            if(count == 22):
                arr.append(1)
            else:
                arr.append(i)
            count+=1

        print("["+str(delNames[index])+"] set for recovery.")
        index+=1

        #Re-seek to beginning, lock+dismount drive for writing
        drive.seek((sector*SECTOR_SIZE))
        drive.write(bytes(arr))
Exemple #30
0
    def _ioctl(self, ioctl_code, in_buf, out_length):

        if not self.driver_loaded:
            _handle_error(
                "chipsec kernel driver is not loaded (in native API mode?)")

        out_buf = (c_char * out_length)()
        self.get_driver_handle()
        if logger().DEBUG: print_buffer(bytestostring(in_buf))
        try:
            out_buf = win32file.DeviceIoControl(self.driver_handle, ioctl_code,
                                                in_buf, out_length, None)
        except pywintypes.error as _err:
            err_status = _err.args[0] + 0x100000000
            if STATUS_PRIVILEGED_INSTRUCTION == err_status:
                err_msg = "HW Access Violation: DeviceIoControl returned STATUS_PRIVILEGED_INSTRUCTION (0x{:X})".format(
                    err_status)
                if logger().DEBUG: logger().error(err_msg)
                raise HWAccessViolationError(err_msg, err_status)
            else:
                _handle_error(
                    "HW Access Error: DeviceIoControl returned status 0x{:X} ({})"
                    .format(err_status, _err.args[2]), err_status)

        return out_buf