Python ctypes.wintypes.ULONG Examples

The following are 17 code examples for showing how to use ctypes.wintypes.ULONG(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module ctypes.wintypes , or try the search function .

Example 1
Project: cWMI   Author: fireeye   File: wmi.py    License: Apache License 2.0 6 votes vote down vote up
def NextAsync(self, count, sink):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.ULONG,
                                       ctypes.POINTER(IWbemObjectSink))

        paramflags = ((_In_, 'uCount'),
                      (_In_, 'pSink'),
                      )

        _NextAsync = prototype(IEnumWbemClassObject_NextAsync_Idx,
                               'NextAsync',
                               paramflags)
        _NextAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
        _NextAsync(self.this,
                   count,
                   sink.this if sink else None
                   ) 
Example 2
Project: cWMI   Author: fireeye   File: wmi.py    License: Apache License 2.0 6 votes vote down vote up
def Skip(self, timeout, count):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       ctypes.c_long,
                                       wintypes.ULONG)

        paramflags = ((_In_, 'lTimeout'),
                      (_In_, 'nCount'),
                      )

        _Skip = prototype(IEnumWbemClassObject_Skip_Idx,
                          'Skip',
                          paramflags)
        _Skip.errcheck = winapi.RAISE_NON_ZERO_ERR
        _Skip(self.this,
              timeout,
              count
              ) 
Example 3
Project: pypykatz   Author: skelsec   File: privileges.py    License: MIT License 6 votes vote down vote up
def RtlAdjustPrivilege(privilige_id, enable = True, thread_or_process = False):
	"""
	privilige_id: int
	"""
	_RtlAdjustPrivilege = windll.ntdll.RtlAdjustPrivilege
	_RtlAdjustPrivilege.argtypes = [ULONG, BOOL, BOOL, POINTER(BOOL)]
	_RtlAdjustPrivilege.restype  = NTSTATUS
	
	CurrentThread = thread_or_process #enable for whole process
	Enabled = BOOL()
	
	status = _RtlAdjustPrivilege(privilige_id, enable, CurrentThread, ctypes.byref(Enabled))
	if status != STATUS_SUCCESS:
		raise Exception(NtError(status))
	
	return True 
Example 4
Project: pypykatz   Author: skelsec   File: ntdll.py    License: MIT License 6 votes vote down vote up
def RtlAdjustPrivilege(privilige_id, enable = True, thread_or_process = False):
	"""
	privilige_id: int
	"""
	_RtlAdjustPrivilege = windll.ntdll.RtlAdjustPrivilege
	_RtlAdjustPrivilege.argtypes = [ULONG, BOOL, BOOL, POINTER(BOOL)]
	_RtlAdjustPrivilege.restype  = NTSTATUS

	
	CurrentThread = thread_or_process #False = enable for whole process, True = current thread only
	Enabled = BOOL()
	
	status = _RtlAdjustPrivilege(privilige_id, enable, CurrentThread, ctypes.byref(Enabled))
	if status != 0:
		raise Exception('Failed call to RtlAdjustPrivilege! Status: %s' % status)
	
	return Enabled.value 
Example 5
Project: pypykatz   Author: skelsec   File: privileges.py    License: MIT License 6 votes vote down vote up
def RtlAdjustPrivilege(privilige_id, enable = True, thread_or_process = False):
	"""
	privilige_id: int
	"""
	_RtlAdjustPrivilege = windll.ntdll.RtlAdjustPrivilege
	_RtlAdjustPrivilege.argtypes = [ULONG, BOOL, BOOL, POINTER(BOOL)]
	_RtlAdjustPrivilege.restype  = NTSTATUS
	
	CurrentThread = thread_or_process #enable for whole process
	Enabled = BOOL()
	
	status = _RtlAdjustPrivilege(privilige_id, enable, CurrentThread, ctypes.byref(Enabled))
	if status != STATUS_SUCCESS:
		raise Exception(NtError(status))
	
	return True 
Example 6
Project: cWMI   Author: fireeye   File: wmi.py    License: Apache License 2.0 5 votes vote down vote up
def Next(self, timeout):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       ctypes.c_long,
                                       wintypes.ULONG,
                                       ctypes.POINTER(wintypes.LPVOID),
                                       ctypes.POINTER(wintypes.ULONG))

        paramflags = ((_In_, 'lTimeout'),
                      (_In_, 'uCount'),
                      (_Out_, 'apObjects'),
                      (_Out_, 'puReturned'),
                      )

        _Next = prototype(IEnumWbemClassObject_Next_Idx,
                          'Next',
                          paramflags)
        _Next.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj, return_obj2 = _Next(self.this,
                                        timeout,
                                        1
                                        )
        try:
            return_obj = IWbemClassObject(return_obj)
        except WindowsError:
            return_obj = None
        return return_obj 
Example 7
Project: cloudbase-init   Author: cloudbase   File: windows.py    License: Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        """Get the user account name from the underlying instance."""
        buf_len = wintypes.ULONG(512)
        buf = ctypes.create_unicode_buffer(512)

        ret_val = secur32.GetUserNameExW(
            self.EXTENDED_NAME_FORMAT_SAM_COMPATIBLE,
            buf, ctypes.byref(buf_len))
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "GetUserNameExW failed: %r")

        return buf.value.split("\\") 
Example 8
Project: cloudbase-init   Author: cloudbase   File: windows.py    License: Apache License 2.0 5 votes vote down vote up
def _get_forward_table(self):
        heap = kernel32.GetProcessHeap()
        forward_table_size = ctypes.sizeof(Win32_MIB_IPFORWARDTABLE)
        size = wintypes.ULONG(forward_table_size)
        table_mem = self._heap_alloc(heap, size)

        p_forward_table = ctypes.cast(
            table_mem, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))

        try:
            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err == self.ERROR_INSUFFICIENT_BUFFER:
                kernel32.HeapFree(heap, 0, p_forward_table)
                table_mem = self._heap_alloc(heap, size)
                p_forward_table = ctypes.cast(
                    table_mem,
                    ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))
                err = iphlpapi.GetIpForwardTable(p_forward_table,
                                                 ctypes.byref(size), 0)

            if err and err != kernel32.ERROR_NO_DATA:
                raise exception.CloudbaseInitException(
                    'Unable to get IP forward table. Error: %s' % err)

            yield p_forward_table
        finally:
            kernel32.HeapFree(heap, 0, p_forward_table) 
Example 9
Project: pypykatz   Author: skelsec   File: privileges.py    License: MIT License 5 votes vote down vote up
def NtError(status):
	"""
	Converts NTSTATUS codes into WinError codes
	"""
	err = windll.ntdll.RtlNtStatusToDosError(status)
	return ctypes.WinError(err)

# https://source.winehq.org/WineAPI/RtlAdjustPrivilege.html
# BOOL WINAPI RtlAdjustPrivilege(
#   __in   ULONG     Privilege,
#   __in   BOOLEAN   Enable,
#   __in   BOOLEAN   CurrentThread,
#   __in   PBOOLEAN  Enabled,
# ); 
Example 10
Project: pypykatz   Author: skelsec   File: privileges.py    License: MIT License 5 votes vote down vote up
def NtError(status):
	"""
	Converts NTSTATUS codes into WinError codes
	"""
	err = windll.ntdll.RtlNtStatusToDosError(status)
	return ctypes.WinError(err)

# https://source.winehq.org/WineAPI/RtlAdjustPrivilege.html
# BOOL WINAPI RtlAdjustPrivilege(
#   __in   ULONG     Privilege,
#   __in   BOOLEAN   Enable,
#   __in   BOOLEAN   CurrentThread,
#   __in   PBOOLEAN  Enabled,
# ); 
Example 11
Project: BitTorrent   Author: kenorb-contrib   File: iphelp.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_interface_by_index(index):
    table = MIB_IPADDRTABLE()
    size = ULONG(ctypes.sizeof(table))
    table.dwNumEntries = 0
    Iphlpapi.GetIpAddrTable(ctypes.byref(table), ctypes.byref(size), 0)

    for n in xrange(table.dwNumEntries):
        row = table.table[n]
        if row.dwIndex == index:
            return str(row.dwAddr)
    raise IndexError("interface index out of range") 
Example 12
Project: BitTorrent   Author: kenorb-contrib   File: iphelp.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_interface_by_index(index):
    table = MIB_IPADDRTABLE()
    size = ULONG(ctypes.sizeof(table))
    table.dwNumEntries = 0
    Iphlpapi.GetIpAddrTable(ctypes.byref(table), ctypes.byref(size), 0)

    for n in xrange(table.dwNumEntries):
        row = table.table[n]
        if row.dwIndex == index:
            return str(row.dwAddr)
    raise IndexError("interface index out of range") 
Example 13
Project: EventGhost   Author: EventGhost   File: HID.py    License: GNU General Public License v2.0 5 votes vote down vote up
def SetFeature(self, buffer):
        if self.handle:
            bufferLength = ULONG(len(buffer))
            result = ctypes.windll.hid.HidD_SetFeature(int(self.handle), ctypes.create_string_buffer(buffer), bufferLength)
            if not result:
                raise Exception("could not set feature") 
Example 14
Project: pywintrace   Author: fireeye   File: etw.py    License: Apache License 2.0 4 votes vote down vote up
def get_keywords_bitmask(guid, keywords):
    """
    Queries available keywords of the provider and returns a bitmask of the associated values

    :param guid: The GUID of the ETW provider.
    :param keywords: List of keywords to resolve.
    :return Bitmask of the keyword flags ORed together
    """

    bitmask = 0
    if keywords is None or len(keywords) == 0:
        return bitmask

    # enumerate the keywords for the provider as well as the bitmask values
    provider_info = None
    providers_size = wt.ULONG(0)
    status = tdh.TdhEnumerateProviderFieldInformation(
        ct.byref(guid),
        tdh.EventKeywordInformation,
        provider_info,
        ct.byref(providers_size))

    if status == tdh.ERROR_INSUFFICIENT_BUFFER:

        provider_info = ct.cast((ct.c_char * providers_size.value)(), ct.POINTER(tdh.PROVIDER_FIELD_INFOARRAY))
        status = tdh.TdhEnumerateProviderFieldInformation(
            ct.byref(guid),
            tdh.EventKeywordInformation,
            provider_info,
            ct.byref(providers_size))

    if tdh.ERROR_SUCCESS != status and tdh.ERROR_NOT_FOUND != status:
        raise ct.WinError(status)

    if provider_info:
        field_info_array = ct.cast(provider_info.contents.FieldInfoArray, ct.POINTER(tdh.PROVIDER_FIELD_INFO))
        provider_keywords = {}
        for i in range(provider_info.contents.NumberOfElements):
            provider_keyword = rel_ptr_to_str(provider_info, field_info_array[i].NameOffset)
            provider_keywords[provider_keyword] = field_info_array[i].Value

        for keyword in keywords:
            if keyword in provider_keywords:
                bitmask |= provider_keywords[keyword]

    return bitmask 
Example 15
Project: ifaddr   Author: pydron   File: _win32.py    License: MIT License 4 votes vote down vote up
def get_adapters(include_unconfigured=False):

    # Call GetAdaptersAddresses() with error and buffer size handling

    addressbuffersize = wintypes.ULONG(15*1024)
    retval = ERROR_BUFFER_OVERFLOW
    while retval == ERROR_BUFFER_OVERFLOW:
        addressbuffer = ctypes.create_string_buffer(addressbuffersize.value)
        retval = iphlpapi.GetAdaptersAddresses(wintypes.ULONG(AF_UNSPEC),
                                      wintypes.ULONG(0),
                                      None,
                                      ctypes.byref(addressbuffer),
                                      ctypes.byref(addressbuffersize))
    if retval != NO_ERROR:
        raise ctypes.WinError()

    # Iterate through adapters fill array
    address_infos = []
    address_info = IP_ADAPTER_ADDRESSES.from_buffer(addressbuffer)
    while True:
        address_infos.append(address_info)
        if not address_info.Next:
            break
        address_info = address_info.Next[0]


    # Iterate through unicast addresses
    result = []
    for adapter_info in address_infos:

        name = adapter_info.AdapterName
        if sys.version_info[0] > 2:
            # We don't expect non-ascii characters here, so encoding shouldn't matter
            name = name.decode()
        nice_name = adapter_info.Description
        index = adapter_info.IfIndex

        if adapter_info.FirstUnicastAddress:
            ips = enumerate_interfaces_of_adapter(adapter_info.FriendlyName, adapter_info.FirstUnicastAddress[0])
            ips = list(ips)
            result.append(shared.Adapter(name, nice_name, ips,
                                         index=index))
        elif include_unconfigured:
            result.append(shared.Adapter(name, nice_name, [],
                                         index=index))

    return result 
Example 16
Project: AstroBox   Author: AstroPrint   File: list_ports_windows.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
def comports():
    """This generator scans the device registry for com ports and yields port, desc, hwid"""
    g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
    #~ for i in range(256):
    for dwIndex in range(256):
        did = SP_DEVICE_INTERFACE_DATA()
        did.cbSize = ctypes.sizeof(did)

        if not SetupDiEnumDeviceInterfaces(g_hdi, None, ctypes.byref(GUID_CLASS_COMPORT), dwIndex, ctypes.byref(did)):
            if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
                raise ctypes.WinError()
            break

        dwNeeded = DWORD()
        # get the size
        if not SetupDiGetDeviceInterfaceDetail(g_hdi, ctypes.byref(did), None, 0, ctypes.byref(dwNeeded), None):
            # Ignore ERROR_INSUFFICIENT_BUFFER
            if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
                raise ctypes.WinError()
        # allocate buffer
        class SP_DEVICE_INTERFACE_DETAIL_DATA_A(ctypes.Structure):
            _fields_ = [
                ('cbSize', DWORD),
                ('DevicePath', CHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
            ]
            def __str__(self):
                return "DevicePath:%s" % (self.DevicePath,)
        idd = SP_DEVICE_INTERFACE_DETAIL_DATA_A()
        if is_64bit():
            idd.cbSize = 8
        else:
            idd.cbSize = 5
        devinfo = SP_DEVINFO_DATA()
        devinfo.cbSize = ctypes.sizeof(devinfo)
        if not SetupDiGetDeviceInterfaceDetail(g_hdi, ctypes.byref(did), ctypes.byref(idd), dwNeeded, None, ctypes.byref(devinfo)):
            raise ctypes.WinError()

        # hardware ID
        szHardwareID = byte_buffer(250)
        if not SetupDiGetDeviceRegistryProperty(g_hdi, ctypes.byref(devinfo), SPDRP_HARDWAREID, None, ctypes.byref(szHardwareID), ctypes.sizeof(szHardwareID) - 1, None):
            # Ignore ERROR_INSUFFICIENT_BUFFER
            if GetLastError() != ERROR_INSUFFICIENT_BUFFER:
                raise ctypes.WinError()

        # friendly name
        szFriendlyName = byte_buffer(250)
        if not SetupDiGetDeviceRegistryProperty(g_hdi, ctypes.byref(devinfo), SPDRP_FRIENDLYNAME, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None):
            # Ignore ERROR_INSUFFICIENT_BUFFER
            if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
                #~ raise IOError("failed to get details for %s (%s)" % (devinfo, szHardwareID.value))
                port_name = None
        else:
            # the real com port name has to read differently...
            hkey = SetupDiOpenDevRegKey(g_hdi, ctypes.byref(devinfo), DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ)
            port_name_buffer = byte_buffer(250)
            port_name_length = ULONG(ctypes.sizeof(port_name_buffer))
            RegQueryValueEx(hkey, PortName, None, None, ctypes.byref(port_name_buffer), ctypes.byref(port_name_length))
            RegCloseKey(hkey)
            yield string(port_name_buffer), string(szFriendlyName), string(szHardwareID)

    SetupDiDestroyDeviceInfoList(g_hdi) 
Example 17
Project: pyp2p   Author: StorjOld   File: ip_routes.py    License: MIT License 4 votes vote down vote up
def get_ipv4_routing_table():
        routing_table = []

        heap = kernel32.GetProcessHeap()

        size = wintypes.ULONG(ctypes.sizeof(Win32MIBIPFORWARDTABLE))
        p = kernel32.HeapAlloc(heap, 0, size)
        if not p:
            raise Exception('Unable to allocate memory for the IP forward '
                            'table')
        p_forward_table = ctypes.cast(
            p, ctypes.POINTER(Win32MIBIPFORWARDTABLE))

        try:
            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err == ERROR_INSUFFICIENT_BUFFER:
                kernel32.HeapFree(heap, 0, p_forward_table)
                p = kernel32.HeapAlloc(heap, 0, size)
                if not p:
                    raise Exception('Unable to allocate memory for the IP '
                                    'forward table')
                p_forward_table = ctypes.cast(
                    p, ctypes.POINTER(Win32MIBIPFORWARDTABLE))

            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err != ERROR_NO_DATA:
                if err:
                    raise Exception('Unable to get IP forward table. '
                                    'Error: %s' % err)

                forward_table = p_forward_table.contents
                table = ctypes.cast(
                    ctypes.addressof(forward_table.table),
                    ctypes.POINTER(Win32MIBIPFORWARDROW *
                                   forward_table.dwNumEntries)).contents

                i = 0
                while i < forward_table.dwNumEntries:
                    row = table[i]
                    routing_table.append((
                        Ws2_32.inet_ntoa(row.dwForwardDest),
                        Ws2_32.inet_ntoa(row.dwForwardMask),
                        Ws2_32.inet_ntoa(row.dwForwardNextHop),
                        row.dwForwardIfIndex,
                        row.dwForwardMetric1))
                    i += 1

            return routing_table
        finally:
            kernel32.HeapFree(heap, 0, p_forward_table)