diff --git a/ctypes_generation/definitions/winfunc_crypto_wintrust.txt b/ctypes_generation/definitions/winfunc_crypto_wintrust.txt index 10e82e4..efe9672 100644 --- a/ctypes_generation/definitions/winfunc_crypto_wintrust.txt +++ b/ctypes_generation/definitions/winfunc_crypto_wintrust.txt @@ -319,3 +319,8 @@ BOOL WINAPI CertCompareCertificate( _In_ PCERT_INFO pCertId1, _In_ PCERT_INFO pCertId2 ); + +PCCTL_CONTEXT WINAPI CertEnumCTLsInStore( + _In_ HCERTSTORE hCertStore, + _In_ PCCTL_CONTEXT pPrevCtlContext +); diff --git a/ctypes_generation/extended_structs/_CRYPTOAPI_BLOB.py b/ctypes_generation/extended_structs/_CRYPTOAPI_BLOB.py new file mode 100644 index 0000000..000b123 --- /dev/null +++ b/ctypes_generation/extended_structs/_CRYPTOAPI_BLOB.py @@ -0,0 +1,11 @@ +class _CRYPTOAPI_BLOB(_CRYPTOAPI_BLOB): + @classmethod + def from_string(cls, buf): + self = cls() + self.cbData = len(buf) + self.pbData = (BYTE * self.cbData)(*bytearray(buf)) + return self + + @property + def data(self): + return bytearray(self.pbData[:self.cbData]) \ No newline at end of file diff --git a/ctypes_generation/generate.py b/ctypes_generation/generate.py index 5a486ec..9ed4adf 100644 --- a/ctypes_generation/generate.py +++ b/ctypes_generation/generate.py @@ -16,6 +16,7 @@ pexists = os.path.exists dedent = textwrap.dedent + TYPE_EQUIVALENCE = [ # BYTE is defined in ctypes.wintypes as c_byte but who wants # BYTE to be signed ? (from MSDN: ) @@ -258,8 +259,6 @@ class InitialDefGenerator(CtypesGenerator): with open(target_file, "w") as f: f.writelines(all_lines) -EXTENDED_STRUCT = ["_GUID", "_RPC_IF_ID"] # TODO: check auto the dir - class StructGenerator(CtypesGenerator): PARSER = struct_parser.WinStructParser IMPORT_HEADER = dedent (""" @@ -723,6 +722,10 @@ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) print(SCRIPT_DIR) from_here = lambda path: pjoin(SCRIPT_DIR, path) + +EXTENDED_STRUCT_FILE = glob.glob(pjoin(SCRIPT_DIR, "extended_structs", "*.py")) +EXTENDED_STRUCT = [os.path.basename(filename)[:-len(".py")] for filename in EXTENDED_STRUCT_FILE] + DEFAULT_INTERFACE_TO_IID = from_here("definitions\\interface_to_iid.txt") # A partial define without the dependance to ntstatus defintion diff --git a/docs/source/winstructs_generated.rst b/docs/source/winstructs_generated.rst index b0b93e0..0d5ebf0 100644 --- a/docs/source/winstructs_generated.rst +++ b/docs/source/winstructs_generated.rst @@ -5480,6 +5480,181 @@ _CRYPTOAPI_BLOB :class:`BYTE` +CRYPTCATATTRIBUTE_ +'''''''''''''''''' +.. class:: CRYPTCATATTRIBUTE + + Alias for :class:`CRYPTCATATTRIBUTE_` + +.. class:: PCRYPTCATATTRIBUTE + + Pointer to :class:`CRYPTCATATTRIBUTE_` + +.. class:: CRYPTCATATTRIBUTE_ + + .. attribute:: cbStruct + + :class:`DWORD` + + + .. attribute:: pwszReferenceTag + + :class:`LPWSTR` + + + .. attribute:: dwAttrTypeAndAction + + :class:`DWORD` + + + .. attribute:: cbValue + + :class:`DWORD` + + + .. attribute:: pbValue + + :class:`BYTE` + + + .. attribute:: dwReserved + + :class:`DWORD` + +_CRYPT_ATTRIBUTE_TYPE_VALUE +''''''''''''''''''''''''''' +.. class:: CRYPT_ATTRIBUTE_TYPE_VALUE + + Alias for :class:`_CRYPT_ATTRIBUTE_TYPE_VALUE` + +.. class:: PCRYPT_ATTRIBUTE_TYPE_VALUE + + Pointer to :class:`_CRYPT_ATTRIBUTE_TYPE_VALUE` + +.. class:: _CRYPT_ATTRIBUTE_TYPE_VALUE + + .. attribute:: pszObjId + + :class:`LPSTR` + + + .. attribute:: Value + + :class:`CRYPT_OBJID_BLOB` + +_CRYPT_ALGORITHM_IDENTIFIER +''''''''''''''''''''''''''' +.. class:: CRYPT_ALGORITHM_IDENTIFIER + + Alias for :class:`_CRYPT_ALGORITHM_IDENTIFIER` + +.. class:: PCRYPT_ALGORITHM_IDENTIFIER + + Pointer to :class:`_CRYPT_ALGORITHM_IDENTIFIER` + +.. class:: _CRYPT_ALGORITHM_IDENTIFIER + + .. attribute:: pszObjId + + :class:`LPSTR` + + + .. attribute:: Parameters + + :class:`CRYPT_OBJID_BLOB` + +SIP_INDIRECT_DATA_ +'''''''''''''''''' +.. class:: SIP_INDIRECT_DATA + + Alias for :class:`SIP_INDIRECT_DATA_` + +.. class:: PSIP_INDIRECT_DATA + + Pointer to :class:`SIP_INDIRECT_DATA_` + +.. class:: SIP_INDIRECT_DATA_ + + .. attribute:: Data + + :class:`CRYPT_ATTRIBUTE_TYPE_VALUE` + + + .. attribute:: DigestAlgorithm + + :class:`CRYPT_ALGORITHM_IDENTIFIER` + + + .. attribute:: Digest + + :class:`CRYPT_HASH_BLOB` + +CRYPTCATMEMBER_ +''''''''''''''' +.. class:: CRYPTCATMEMBER + + Alias for :class:`CRYPTCATMEMBER_` + +.. class:: PCRYPTCATMEMBER + + Pointer to :class:`CRYPTCATMEMBER_` + +.. class:: CRYPTCATMEMBER_ + + .. attribute:: cbStruct + + :class:`DWORD` + + + .. attribute:: pwszReferenceTag + + :class:`LPWSTR` + + + .. attribute:: pwszFileName + + :class:`LPWSTR` + + + .. attribute:: gSubjectType + + :class:`GUID` + + + .. attribute:: fdwMemberFlags + + :class:`DWORD` + + + .. attribute:: pIndirectData + + :class:`SIP_INDIRECT_DATA` + + + .. attribute:: dwCertVersion + + :class:`DWORD` + + + .. attribute:: dwReserved + + :class:`DWORD` + + + .. attribute:: hReserved + + :class:`HANDLE` + + + .. attribute:: sEncodedIndirectData + + :class:`CRYPT_ATTR_BLOB` + + + .. attribute:: sEncodedMemberInfo + + :class:`CRYPT_ATTR_BLOB` + WINTRUST_FILE_INFO_ ''''''''''''''''''' .. class:: WINTRUST_FILE_INFO @@ -5610,27 +5785,6 @@ _CRYPT_ATTRIBUTES :class:`PCRYPT_ATTRIBUTE` -_CRYPT_ALGORITHM_IDENTIFIER -''''''''''''''''''''''''''' -.. class:: CRYPT_ALGORITHM_IDENTIFIER - - Alias for :class:`_CRYPT_ALGORITHM_IDENTIFIER` - -.. class:: PCRYPT_ALGORITHM_IDENTIFIER - - Pointer to :class:`_CRYPT_ALGORITHM_IDENTIFIER` - -.. class:: _CRYPT_ALGORITHM_IDENTIFIER - - .. attribute:: pszObjId - - :class:`LPSTR` - - - .. attribute:: Parameters - - :class:`CRYPT_OBJID_BLOB` - _CMSG_SIGNER_INFO ''''''''''''''''' .. class:: CMSG_SIGNER_INFO diff --git a/windows/crypto/certificate.py b/windows/crypto/certificate.py index 9975e83..4cf3333 100644 --- a/windows/crypto/certificate.py +++ b/windows/crypto/certificate.py @@ -3,29 +3,30 @@ import ctypes import windows from windows import winproxy -from windows.generated_def import * +# from windows.generated_def import * +import windows.generated_def as gdef from windows.crypto import DEFAULT_ENCODING -from windows.crypto.helper import ECRYPT_DATA_BLOB +# from windows.crypto.helper import ECRYPT_DATA_BLOB CRYPT_OBJECT_FORMAT_TYPE = [ - CERT_QUERY_OBJECT_FILE, - CERT_QUERY_OBJECT_BLOB, - CERT_QUERY_CONTENT_CERT, - CERT_QUERY_CONTENT_CTL, - CERT_QUERY_CONTENT_CRL, - CERT_QUERY_CONTENT_SERIALIZED_STORE, - CERT_QUERY_CONTENT_SERIALIZED_CERT, - CERT_QUERY_CONTENT_SERIALIZED_CTL, - CERT_QUERY_CONTENT_SERIALIZED_CRL, - CERT_QUERY_CONTENT_PKCS7_SIGNED, - CERT_QUERY_CONTENT_PKCS7_UNSIGNED, - CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED, - CERT_QUERY_CONTENT_PKCS10, - CERT_QUERY_CONTENT_PFX, - CERT_QUERY_CONTENT_CERT_PAIR, - CERT_QUERY_CONTENT_PFX_AND_LOAD + gdef.CERT_QUERY_OBJECT_FILE, + gdef.CERT_QUERY_OBJECT_BLOB, + gdef.CERT_QUERY_CONTENT_CERT, + gdef.CERT_QUERY_CONTENT_CTL, + gdef.CERT_QUERY_CONTENT_CRL, + gdef.CERT_QUERY_CONTENT_SERIALIZED_STORE, + gdef.CERT_QUERY_CONTENT_SERIALIZED_CERT, + gdef.CERT_QUERY_CONTENT_SERIALIZED_CTL, + gdef.CERT_QUERY_CONTENT_SERIALIZED_CRL, + gdef.CERT_QUERY_CONTENT_PKCS7_SIGNED, + gdef.CERT_QUERY_CONTENT_PKCS7_UNSIGNED, + gdef.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED, + gdef.CERT_QUERY_CONTENT_PKCS10, + gdef.CERT_QUERY_CONTENT_PFX, + gdef.CERT_QUERY_CONTENT_CERT_PAIR, + gdef.CERT_QUERY_CONTENT_PFX_AND_LOAD ] CRYPT_OBJECT_FORMAT_TYPE_DICT = {x:x for x in CRYPT_OBJECT_FORMAT_TYPE} @@ -36,13 +37,15 @@ class CryptObject(object): Current main use is extracting the signers certificates from a PE file. """ - MSG_PARAM_KNOW_TYPES = {CMSG_SIGNER_INFO_PARAM: CMSG_SIGNER_INFO, - CMSG_SIGNER_COUNT_PARAM: DWORD, - CMSG_CERT_COUNT_PARAM: DWORD} + MSG_PARAM_KNOW_TYPES = {gdef.CMSG_SIGNER_INFO_PARAM: gdef.CMSG_SIGNER_INFO, + gdef.CMSG_SIGNER_COUNT_PARAM: gdef.DWORD, + gdef.CMSG_CERT_COUNT_PARAM: gdef.DWORD} - def __init__(self, filename, content_type=CERT_QUERY_CONTENT_FLAG_ALL): + def __init__(self, filename, content_type=gdef.CERT_QUERY_CONTENT_FLAG_ALL): # No other API than filename for now.. self.filename = filename + if filename is None: + return # TMP ! dwEncoding = DWORD() dwContentType = DWORD() @@ -50,10 +53,10 @@ class CryptObject(object): hStore = PVOID() hMsg = PVOID() - winproxy.CryptQueryObject(CERT_QUERY_OBJECT_FILE, + winproxy.CryptQueryObject(gdef.CERT_QUERY_OBJECT_FILE, LPWSTR(filename), content_type, - CERT_QUERY_FORMAT_FLAG_BINARY, + gdef.CERT_QUERY_FORMAT_FLAG_BINARY, 0, dwEncoding, dwContentType, @@ -128,11 +131,19 @@ class CryptObject(object): """ return self.msg_get_param(CMSG_CERT_COUNT_PARAM).value + @property + def signers(self): + return [self.get_signer_data(i) for i in range(self.nb_signer)] + + @property + def certs(self): + return [self.get_cert(i) for i in range(self.nb_cert)] + def __repr__(self): return '<{0} "{1}" content_type={2}>'.format(type(self).__name__, self.filename, self.content_type) -class EHCERTSTORE(HCERTSTORE): +class EHCERTSTORE(gdef.HCERTSTORE): """A certificate store""" @property def certs(self): @@ -146,7 +157,7 @@ class EHCERTSTORE(HCERTSTORE): try: cert = winproxy.CertEnumCertificatesInStore(self, last) except winproxy.Kernel32Error as e: - if (e.winerror & 0xffffffff) in (CRYPT_E_NOT_FOUND,): + if (e.winerror & 0xffffffff) in (gdef.CRYPT_E_NOT_FOUND,): return tuple(res) raise # Need to duplicate as CertEnumCertificatesInStore will free the context 'last' @@ -157,12 +168,12 @@ class EHCERTSTORE(HCERTSTORE): def add_certificate(self, certificate): """Add a certificate to the store""" - winproxy.CertAddCertificateContextToStore(self, certificate, CERT_STORE_ADD_NEW, None) + winproxy.CertAddCertificateContextToStore(self, certificate, gdef.CERT_STORE_ADD_NEW, None) @classmethod def from_file(cls, filename): """Create a new :class:`EHCERTSTORE` from ``filename``""" - res = winproxy.CertOpenStore(CERT_STORE_PROV_FILENAME_A, DEFAULT_ENCODING, None, CERT_STORE_OPEN_EXISTING_FLAG, filename) + res = winproxy.CertOpenStore(gdef.CERT_STORE_PROV_FILENAME_A, DEFAULT_ENCODING, None, gdef.CERT_STORE_OPEN_EXISTING_FLAG, filename) return ctypes.cast(res, cls) @@ -185,7 +196,7 @@ class EHCERTSTORE(HCERTSTORE): # PKCS12_NO_PERSIST_KEY -> do not save it in a key container on disk # Without it, a key container is created at 'C:\Users\USERNAME\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-3241049326-165485355-1070449050-1001' -def import_pfx(pfx, password=None, flags=CRYPT_USER_KEYSET | PKCS12_NO_PERSIST_KEY): +def import_pfx(pfx, password=None, flags=gdef.CRYPT_USER_KEYSET | gdef.PKCS12_NO_PERSIST_KEY): """Import the file ``pfx`` with the ``password``. ``default flags = PKCS12_NO_PERSIST_KEY | CRYPT_USER_KEYSET``. @@ -195,18 +206,18 @@ def import_pfx(pfx, password=None, flags=CRYPT_USER_KEYSET | PKCS12_NO_PERSIST_K :return: :class:`EHCERTSTORE` """ if isinstance(pfx, basestring): - pfx = ECRYPT_DATA_BLOB.from_string(pfx) + pfx = gdef.CRYPT_DATA_BLOB.from_string(pfx) cert_store = winproxy.PFXImportCertStore(pfx, password, flags) return EHCERTSTORE(cert_store) # Why PCCERT_CONTEXT (pointer type) and not _CERT_CONTEXT ? -class CertificateContext(PCCERT_CONTEXT): +class CertificateContext(gdef.PCCERT_CONTEXT): """Represent a Certificate. note: It is a pointer ctypes structure (``PCCERT_CONTEXT``) """ - _type_ = PCCERT_CONTEXT._type_ # Not herited from PCCERT_CONTEXT + _type_ = gdef.PCCERT_CONTEXT._type_ # Not herited from PCCERT_CONTEXT def __repr__(self): @@ -231,7 +242,7 @@ class CertificateContext(PCCERT_CONTEXT): return " ".join("{:02x}".format(x) for x in serial_bytes) - def get_name(self, nametype=CERT_NAME_SIMPLE_DISPLAY_TYPE, flags=0): + def get_name(self, nametype=gdef.CERT_NAME_SIMPLE_DISPLAY_TYPE, flags=0): """Retrieve the subject or issuer name of the certificate. See ``CertGetNameStringA`` :returns: :class:`str` @@ -251,7 +262,7 @@ class CertificateContext(PCCERT_CONTEXT): """The name of the certificate's issuer. :type: :class:`str`""" - return self.get_name(flags=CERT_NAME_ISSUER_FLAG) + return self.get_name(flags=gdef.CERT_NAME_ISSUER_FLAG) @property def store(self): @@ -309,7 +320,7 @@ class CertificateContext(PCCERT_CONTEXT): # Only the refcount is incremented # This postulate allow us to return 'self' directly # https://msdn.microsoft.com/en-us/library/windows/desktop/aa376045(v=vs.85).aspx - if not ctypes.cast(res, PVOID).value == ctypes.cast(self, PVOID).value: + if not ctypes.cast(res, gdef.PVOID).value == ctypes.cast(self, gdef.PVOID).value: raise ValueError("CertDuplicateCertificateContext did not returned the argument (check doc)") return self @@ -382,14 +393,14 @@ class CertificateContext(PCCERT_CONTEXT): # Those classes are more of a POC than anything else -class EPCCERT_CHAIN_CONTEXT(PCCERT_CHAIN_CONTEXT): - _type_ = PCCERT_CHAIN_CONTEXT._type_ +class EPCCERT_CHAIN_CONTEXT(gdef.PCCERT_CHAIN_CONTEXT): + _type_ = gdef.PCCERT_CHAIN_CONTEXT._type_ @property def chains(self): res = [] for i in range(self[0].cChain): - simple_chain = ctypes.cast(self[0].rgpChain[i], EPCCERT_SIMPLE_CHAIN) + simple_chain = ctypes.cast(self[0].rgpChain[i], gdef.EPCCERT_SIMPLE_CHAIN) res.append(simple_chain) return res @@ -403,8 +414,8 @@ class EPCCERT_CHAIN_CONTEXT(PCCERT_CHAIN_CONTEXT): ch.append(element.cert) return res -class EPCCERT_SIMPLE_CHAIN(PCCERT_SIMPLE_CHAIN): - _type_ = PCCERT_SIMPLE_CHAIN._type_ +class EPCCERT_SIMPLE_CHAIN(gdef.PCCERT_SIMPLE_CHAIN): + _type_ = gdef.PCCERT_SIMPLE_CHAIN._type_ @property def elements(self): @@ -414,8 +425,8 @@ class EPCCERT_SIMPLE_CHAIN(PCCERT_SIMPLE_CHAIN): res.append(element) return res -class EPCERT_CHAIN_ELEMENT(PCERT_CHAIN_ELEMENT): - _type_ = PCERT_CHAIN_ELEMENT._type_ +class EPCERT_CHAIN_ELEMENT(gdef.PCERT_CHAIN_ELEMENT): + _type_ = gdef.PCERT_CHAIN_ELEMENT._type_ @property def cert(self): @@ -423,9 +434,9 @@ class EPCERT_CHAIN_ELEMENT(PCERT_CHAIN_ELEMENT): # Move this in another .py ? -class CryptContext(HCRYPTPROV): +class CryptContext(gdef.HCRYPTPROV): """ A context manager arround ``CryptAcquireContextW`` & ``CryptReleaseContext``""" - _type_ = HCRYPTPROV._type_ + _type_ = gdef.HCRYPTPROV._type_ def __init__(self, pszContainer=None, pszProvider=None, dwProvType=0, dwFlags=0, retrycreate=False): self.pszContainer = pszContainer diff --git a/windows/generated_def/winfuncs.py b/windows/generated_def/winfuncs.py index 329186d..0ef46da 100644 --- a/windows/generated_def/winfuncs.py +++ b/windows/generated_def/winfuncs.py @@ -6,7 +6,7 @@ from ctypes.wintypes import * from winstructs import * -functions = ['ExitProcess', 'TerminateProcess', 'GetLastError', 'GetCurrentProcess', 'CreateFileA', 'CreateFileW', 'NtCreateFile', 'LdrLoadDll', 'NtQuerySystemInformation', 'NtQueryInformationProcess', 'NtQueryVirtualMemory', 'NtCreateThreadEx', 'NtQueryInformationThread', 'GetExitCodeThread', 'GetExitCodeProcess', 'VirtualAlloc', 'VirtualAllocEx', 'NtProtectVirtualMemory', 'VirtualFree', 'VirtualFreeEx', 'VirtualProtect', 'VirtualProtectEx', 'VirtualQuery', 'VirtualQueryEx', 'QueryWorkingSet', 'QueryWorkingSetEx', 'GetModuleFileNameA', 'GetModuleFileNameW', 'CreateThread', 'CreateRemoteThread', 'VirtualProtect', 'CreateProcessA', 'CreateProcessW', 'CreateProcessAsUserA', 'CreateProcessAsUserW', 'GetThreadContext', 'NtGetContextThread', 'SetThreadContext', 'NtSetContextThread', 'OpenThread', 'OpenProcess', 'CloseHandle', 'ReadProcessMemory', 'NtWow64ReadVirtualMemory64', 'NtReadVirtualMemory', 'WriteProcessMemory', 'NtWow64WriteVirtualMemory64', 'CreateToolhelp32Snapshot', 'Thread32First', 'Thread32Next', 'Process32First', 'Process32Next', 'Process32FirstW', 'Process32NextW', 'GetProcAddress', 'LoadLibraryA', 'LoadLibraryW', 'OpenProcessToken', 'OpenThreadToken', 'LookupPrivilegeValueA', 'LookupPrivilegeValueW', 'LookupPrivilegeNameA', 'LookupPrivilegeNameW', 'AdjustTokenPrivileges', 'FindResourceA', 'FindResourceW', 'SizeofResource', 'LoadResource', 'LockResource', 'GetVersionExA', 'GetVersionExW', 'GetVersion', 'GetCurrentThread', 'GetCurrentThreadId', 'GetCurrentProcessorNumber', 'AllocConsole', 'FreeConsole', 'GetStdHandle', 'SetStdHandle', 'SetThreadAffinityMask', 'ReadFile', 'WriteFile', 'GetExtendedTcpTable', 'GetExtendedUdpTable', 'SetTcpEntry', 'AddVectoredContinueHandler', 'AddVectoredExceptionHandler', 'TerminateThread', 'ExitThread', 'RemoveVectoredExceptionHandler', 'ResumeThread', 'SuspendThread', 'WaitForSingleObject', 'GetThreadId', 'LoadLibraryExA', 'LoadLibraryExW', 'SymInitialize', 'SymFromName', 'SymLoadModuleEx', 'SymSetOptions', 'SymGetTypeInfo', 'DeviceIoControl', 'GetTokenInformation', 'RegOpenKeyExA', 'RegOpenKeyExW', 'RegGetValueA', 'RegGetValueW', 'RegCloseKey', 'Wow64DisableWow64FsRedirection', 'Wow64RevertWow64FsRedirection', 'Wow64EnableWow64FsRedirection', 'Wow64GetThreadContext', 'SetConsoleCtrlHandler', 'WinVerifyTrust', 'GlobalAlloc', 'GlobalFree', 'GlobalUnlock', 'GlobalLock', 'OpenClipboard', 'EmptyClipboard', 'CloseClipboard', 'SetClipboardData', 'GetClipboardData', 'EnumClipboardFormats', 'GetClipboardFormatNameA', 'GetClipboardFormatNameW', 'WinVerifyTrust', 'OpenProcessToken', 'OpenThreadToken', 'GetTokenInformation', 'SetTokenInformation', 'GetSidIdentifierAuthority', 'GetSidSubAuthority', 'GetSidSubAuthorityCount', 'GetLengthSid', 'CreateWellKnownSid', 'DebugBreak', 'WaitForDebugEvent', 'ContinueDebugEvent', 'DebugActiveProcess', 'DebugActiveProcessStop', 'DebugSetProcessKillOnExit', 'DebugBreakProcess', 'GetProcessId', 'Wow64SetThreadContext', 'GetMappedFileNameW', 'GetMappedFileNameA', 'RtlInitString', 'RtlInitUnicodeString', 'RtlAnsiStringToUnicodeString', 'RtlDecompressBuffer', 'NtCreateSection', 'NtOpenSection', 'NtMapViewOfSection', 'NtUnmapViewOfSection', 'OpenEventA', 'OpenEventW', 'NtOpenEvent', 'NtAlpcCreatePort', 'NtAlpcQueryInformation', 'NtAlpcConnectPort', 'NtAlpcConnectPortEx', 'NtAlpcAcceptConnectPort', 'AlpcInitializeMessageAttribute', 'AlpcGetMessageAttribute', 'NtAlpcSendWaitReceivePort', 'NtAlpcDisconnectPort', 'NtAlpcCreatePortSection', 'NtAlpcDeletePortSection', 'NtAlpcCreateResourceReserve', 'NtAlpcDeleteResourceReserve', 'NtAlpcCreateSectionView', 'NtAlpcDeleteSectionView', 'NtAlpcCreateSecurityContext', 'NtAlpcDeleteSecurityContext', 'NtAlpcRevokeSecurityContext', 'lstrcmpA', 'lstrcmpW', 'CreateFileMappingA', 'CreateFileMappingW', 'MapViewOfFile', 'OpenSCManagerA', 'OpenSCManagerW', 'CloseServiceHandle', 'EnumServicesStatusExA', 'EnumServicesStatusExW', 'StartServiceA', 'StartServiceW', 'OpenServiceA', 'OpenServiceW', 'EnumWindows', 'GetWindowTextA', 'GetWindowTextW', 'GetWindowModuleFileNameA', 'GetWindowModuleFileNameW', 'GetLogicalDriveStringsA', 'GetLogicalDriveStringsW', 'GetVolumeInformationA', 'GetVolumeInformationW', 'GetVolumeNameForVolumeMountPointA', 'GetVolumeNameForVolumeMountPointW', 'GetDriveTypeA', 'GetDriveTypeW', 'QueryDosDeviceA', 'QueryDosDeviceW', 'NtQueryObject', 'DuplicateHandle', 'ZwDuplicateObject', 'GetModuleBaseNameA', 'GetModuleBaseNameW', 'GetProcessImageFileNameA', 'GetProcessImageFileNameW', 'GetFileVersionInfoA', 'GetFileVersionInfoW', 'GetFileVersionInfoSizeA', 'GetFileVersionInfoSizeW', 'VerQueryValueA', 'VerQueryValueW', 'GetSystemMetrics', 'GetComputerNameA', 'GetComputerNameW', 'LookupAccountSidA', 'LookupAccountSidW', 'CoInitializeEx', 'CoInitializeSecurity', 'CoCreateInstance', 'GetInterfaceInfo', 'GetIfTable', 'GetIpAddrTable', 'NtOpenDirectoryObject', 'NtQueryDirectoryObject', 'NtQuerySymbolicLinkObject', 'NtOpenSymbolicLinkObject', 'GetProcessTimes', 'GetShortPathNameA', 'GetShortPathNameW', 'GetLongPathNameA', 'GetLongPathNameW', 'GetProcessDEPPolicy', 'GetCursorPos', 'WindowFromPoint', 'GetWindowRect', 'GetNamedSecurityInfoA', 'GetNamedSecurityInfoW', 'GetSecurityInfo', 'ConvertStringSidToSidA', 'ConvertStringSidToSidW', 'ConvertSidToStringSidA', 'ConvertSidToStringSidW', 'LocalFree', 'RegQueryValueExA', 'RegQueryValueExW', 'ShellExecuteA', 'ShellExecuteW', 'InitializeProcThreadAttributeList', 'UpdateProcThreadAttribute', 'DeleteProcThreadAttributeList', 'MessageBoxA', 'MessageBoxW', 'GetWindowsDirectoryA', 'GetWindowsDirectoryW', 'RtlGetUnloadEventTraceEx', 'CryptCATAdminCalcHashFromFileHandle', 'CryptCATAdminEnumCatalogFromHash', 'CryptCATAdminAcquireContext', 'CryptCATCatalogInfoFromContext', 'CryptCATAdminReleaseCatalogContext', 'CryptCATAdminReleaseContext', 'CryptCATGetAttrInfo', 'CryptCATGetMemberInfo', 'CryptCATGetAttrInfo', 'CryptCATEnumerateCatAttr', 'CryptCATEnumerateAttr', 'CryptCATEnumerateMember', 'CryptQueryObject', 'CryptMsgGetParam', 'CryptDecodeObject', 'CertFindCertificateInStore', 'CertGetNameStringA', 'CertGetNameStringW', 'CertGetCertificateChain', 'CertCreateSelfSignCertificate', 'CertStrToNameA', 'CertStrToNameW', 'CertOpenStore', 'CertAddCertificateContextToStore', 'PFXExportCertStoreEx', 'PFXImportCertStore', 'CryptGenKey', 'CryptDestroyKey', 'CryptAcquireContextA', 'CryptAcquireContextW', 'CryptReleaseContext', 'CryptExportKey', 'CertGetCertificateContextProperty', 'CertEnumCertificateContextProperties', 'CryptEncryptMessage', 'CryptDecryptMessage', 'CryptAcquireCertificatePrivateKey', 'CertDuplicateCertificateContext', 'CertEnumCertificatesInStore', 'CryptEncodeObjectEx', 'CertCreateCertificateContext', 'CertCompareCertificate', 'TpCallbackSendAlpcMessageOnCompletion'] +functions = ['ExitProcess', 'TerminateProcess', 'GetLastError', 'GetCurrentProcess', 'CreateFileA', 'CreateFileW', 'NtCreateFile', 'LdrLoadDll', 'NtQuerySystemInformation', 'NtQueryInformationProcess', 'NtQueryVirtualMemory', 'NtCreateThreadEx', 'NtQueryInformationThread', 'GetExitCodeThread', 'GetExitCodeProcess', 'VirtualAlloc', 'VirtualAllocEx', 'NtProtectVirtualMemory', 'VirtualFree', 'VirtualFreeEx', 'VirtualProtect', 'VirtualProtectEx', 'VirtualQuery', 'VirtualQueryEx', 'QueryWorkingSet', 'QueryWorkingSetEx', 'GetModuleFileNameA', 'GetModuleFileNameW', 'CreateThread', 'CreateRemoteThread', 'VirtualProtect', 'CreateProcessA', 'CreateProcessW', 'CreateProcessAsUserA', 'CreateProcessAsUserW', 'GetThreadContext', 'NtGetContextThread', 'SetThreadContext', 'NtSetContextThread', 'OpenThread', 'OpenProcess', 'CloseHandle', 'ReadProcessMemory', 'NtWow64ReadVirtualMemory64', 'NtReadVirtualMemory', 'WriteProcessMemory', 'NtWow64WriteVirtualMemory64', 'CreateToolhelp32Snapshot', 'Thread32First', 'Thread32Next', 'Process32First', 'Process32Next', 'Process32FirstW', 'Process32NextW', 'GetProcAddress', 'LoadLibraryA', 'LoadLibraryW', 'OpenProcessToken', 'OpenThreadToken', 'LookupPrivilegeValueA', 'LookupPrivilegeValueW', 'LookupPrivilegeNameA', 'LookupPrivilegeNameW', 'AdjustTokenPrivileges', 'FindResourceA', 'FindResourceW', 'SizeofResource', 'LoadResource', 'LockResource', 'GetVersionExA', 'GetVersionExW', 'GetVersion', 'GetCurrentThread', 'GetCurrentThreadId', 'GetCurrentProcessorNumber', 'AllocConsole', 'FreeConsole', 'GetStdHandle', 'SetStdHandle', 'SetThreadAffinityMask', 'ReadFile', 'WriteFile', 'GetExtendedTcpTable', 'GetExtendedUdpTable', 'SetTcpEntry', 'AddVectoredContinueHandler', 'AddVectoredExceptionHandler', 'TerminateThread', 'ExitThread', 'RemoveVectoredExceptionHandler', 'ResumeThread', 'SuspendThread', 'WaitForSingleObject', 'GetThreadId', 'LoadLibraryExA', 'LoadLibraryExW', 'SymInitialize', 'SymFromName', 'SymLoadModuleEx', 'SymSetOptions', 'SymGetTypeInfo', 'DeviceIoControl', 'GetTokenInformation', 'RegOpenKeyExA', 'RegOpenKeyExW', 'RegGetValueA', 'RegGetValueW', 'RegCloseKey', 'Wow64DisableWow64FsRedirection', 'Wow64RevertWow64FsRedirection', 'Wow64EnableWow64FsRedirection', 'Wow64GetThreadContext', 'SetConsoleCtrlHandler', 'WinVerifyTrust', 'GlobalAlloc', 'GlobalFree', 'GlobalUnlock', 'GlobalLock', 'OpenClipboard', 'EmptyClipboard', 'CloseClipboard', 'SetClipboardData', 'GetClipboardData', 'EnumClipboardFormats', 'GetClipboardFormatNameA', 'GetClipboardFormatNameW', 'WinVerifyTrust', 'OpenProcessToken', 'OpenThreadToken', 'GetTokenInformation', 'SetTokenInformation', 'GetSidIdentifierAuthority', 'GetSidSubAuthority', 'GetSidSubAuthorityCount', 'GetLengthSid', 'CreateWellKnownSid', 'DebugBreak', 'WaitForDebugEvent', 'ContinueDebugEvent', 'DebugActiveProcess', 'DebugActiveProcessStop', 'DebugSetProcessKillOnExit', 'DebugBreakProcess', 'GetProcessId', 'Wow64SetThreadContext', 'GetMappedFileNameW', 'GetMappedFileNameA', 'RtlInitString', 'RtlInitUnicodeString', 'RtlAnsiStringToUnicodeString', 'RtlDecompressBuffer', 'NtCreateSection', 'NtOpenSection', 'NtMapViewOfSection', 'NtUnmapViewOfSection', 'OpenEventA', 'OpenEventW', 'NtOpenEvent', 'NtAlpcCreatePort', 'NtAlpcQueryInformation', 'NtAlpcConnectPort', 'NtAlpcConnectPortEx', 'NtAlpcAcceptConnectPort', 'AlpcInitializeMessageAttribute', 'AlpcGetMessageAttribute', 'NtAlpcSendWaitReceivePort', 'NtAlpcDisconnectPort', 'NtAlpcCreatePortSection', 'NtAlpcDeletePortSection', 'NtAlpcCreateResourceReserve', 'NtAlpcDeleteResourceReserve', 'NtAlpcCreateSectionView', 'NtAlpcDeleteSectionView', 'NtAlpcCreateSecurityContext', 'NtAlpcDeleteSecurityContext', 'NtAlpcRevokeSecurityContext', 'lstrcmpA', 'lstrcmpW', 'CreateFileMappingA', 'CreateFileMappingW', 'MapViewOfFile', 'OpenSCManagerA', 'OpenSCManagerW', 'CloseServiceHandle', 'EnumServicesStatusExA', 'EnumServicesStatusExW', 'StartServiceA', 'StartServiceW', 'OpenServiceA', 'OpenServiceW', 'EnumWindows', 'GetWindowTextA', 'GetWindowTextW', 'GetWindowModuleFileNameA', 'GetWindowModuleFileNameW', 'GetLogicalDriveStringsA', 'GetLogicalDriveStringsW', 'GetVolumeInformationA', 'GetVolumeInformationW', 'GetVolumeNameForVolumeMountPointA', 'GetVolumeNameForVolumeMountPointW', 'GetDriveTypeA', 'GetDriveTypeW', 'QueryDosDeviceA', 'QueryDosDeviceW', 'NtQueryObject', 'DuplicateHandle', 'ZwDuplicateObject', 'GetModuleBaseNameA', 'GetModuleBaseNameW', 'GetProcessImageFileNameA', 'GetProcessImageFileNameW', 'GetFileVersionInfoA', 'GetFileVersionInfoW', 'GetFileVersionInfoSizeA', 'GetFileVersionInfoSizeW', 'VerQueryValueA', 'VerQueryValueW', 'GetSystemMetrics', 'GetComputerNameA', 'GetComputerNameW', 'LookupAccountSidA', 'LookupAccountSidW', 'CoInitializeEx', 'CoInitializeSecurity', 'CoCreateInstance', 'GetInterfaceInfo', 'GetIfTable', 'GetIpAddrTable', 'NtOpenDirectoryObject', 'NtQueryDirectoryObject', 'NtQuerySymbolicLinkObject', 'NtOpenSymbolicLinkObject', 'GetProcessTimes', 'GetShortPathNameA', 'GetShortPathNameW', 'GetLongPathNameA', 'GetLongPathNameW', 'GetProcessDEPPolicy', 'GetCursorPos', 'WindowFromPoint', 'GetWindowRect', 'GetNamedSecurityInfoA', 'GetNamedSecurityInfoW', 'GetSecurityInfo', 'ConvertStringSidToSidA', 'ConvertStringSidToSidW', 'ConvertSidToStringSidA', 'ConvertSidToStringSidW', 'LocalFree', 'RegQueryValueExA', 'RegQueryValueExW', 'ShellExecuteA', 'ShellExecuteW', 'InitializeProcThreadAttributeList', 'UpdateProcThreadAttribute', 'DeleteProcThreadAttributeList', 'MessageBoxA', 'MessageBoxW', 'GetWindowsDirectoryA', 'GetWindowsDirectoryW', 'RtlGetUnloadEventTraceEx', 'CryptCATAdminCalcHashFromFileHandle', 'CryptCATAdminEnumCatalogFromHash', 'CryptCATAdminAcquireContext', 'CryptCATCatalogInfoFromContext', 'CryptCATAdminReleaseCatalogContext', 'CryptCATAdminReleaseContext', 'CryptCATGetAttrInfo', 'CryptCATGetMemberInfo', 'CryptCATGetAttrInfo', 'CryptCATEnumerateCatAttr', 'CryptCATEnumerateAttr', 'CryptCATEnumerateMember', 'CryptQueryObject', 'CryptMsgGetParam', 'CryptDecodeObject', 'CertFindCertificateInStore', 'CertGetNameStringA', 'CertGetNameStringW', 'CertGetCertificateChain', 'CertCreateSelfSignCertificate', 'CertStrToNameA', 'CertStrToNameW', 'CertOpenStore', 'CertAddCertificateContextToStore', 'PFXExportCertStoreEx', 'PFXImportCertStore', 'CryptGenKey', 'CryptDestroyKey', 'CryptAcquireContextA', 'CryptAcquireContextW', 'CryptReleaseContext', 'CryptExportKey', 'CertGetCertificateContextProperty', 'CertEnumCertificateContextProperties', 'CryptEncryptMessage', 'CryptDecryptMessage', 'CryptAcquireCertificatePrivateKey', 'CertDuplicateCertificateContext', 'CertEnumCertificatesInStore', 'CryptEncodeObjectEx', 'CertCreateCertificateContext', 'CertCompareCertificate', 'CertEnumCTLsInStore', 'TpCallbackSendAlpcMessageOnCompletion'] #def ExitProcess(uExitCode): @@ -1529,6 +1529,11 @@ CertCreateCertificateContextParams = ((1, 'dwCertEncodingType'), (1, 'pbCertEnco CertCompareCertificatePrototype = WINFUNCTYPE(BOOL, DWORD, PCERT_INFO, PCERT_INFO) CertCompareCertificateParams = ((1, 'dwCertEncodingType'), (1, 'pCertId1'), (1, 'pCertId2')) +#def CertEnumCTLsInStore(hCertStore, pPrevCtlContext): +# return CertEnumCTLsInStore.ctypes_function(hCertStore, pPrevCtlContext) +CertEnumCTLsInStorePrototype = WINFUNCTYPE(PCCTL_CONTEXT, HCERTSTORE, PCCTL_CONTEXT) +CertEnumCTLsInStoreParams = ((1, 'hCertStore'), (1, 'pPrevCtlContext')) + #def TpCallbackSendAlpcMessageOnCompletion(TpHandle, PortHandle, Flags, SendMessage): # return TpCallbackSendAlpcMessageOnCompletion.ctypes_function(TpHandle, PortHandle, Flags, SendMessage) TpCallbackSendAlpcMessageOnCompletionPrototype = WINFUNCTYPE(NTSTATUS, HANDLE, HANDLE, ULONG, PPORT_MESSAGE) diff --git a/windows/generated_def/winstructs.py b/windows/generated_def/winstructs.py index 59bc982..540bef5 100644 --- a/windows/generated_def/winstructs.py +++ b/windows/generated_def/winstructs.py @@ -2680,6 +2680,44 @@ PDATA_BLOB = POINTER(_CRYPTOAPI_BLOB) PCRYPT_ATTR_BLOB = POINTER(_CRYPTOAPI_BLOB) CRYPT_ATTR_BLOB = _CRYPTOAPI_BLOB +class _CRYPTOAPI_BLOB(_CRYPTOAPI_BLOB): + @classmethod + def from_string(cls, buf): + self = cls() + self.cbData = len(buf) + self.pbData = (BYTE * self.cbData)(*bytearray(buf)) + return self + + @property + def data(self): + return bytearray(self.pbData[:self.cbData]) +CRYPT_INTEGER_BLOB = _CRYPTOAPI_BLOB +PCRYPT_DATA_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_OBJID_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_DER_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRL_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_UINT_BLOB = POINTER(_CRYPTOAPI_BLOB) +CERT_NAME_BLOB = _CRYPTOAPI_BLOB +PCRYPT_DIGEST_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_INTEGER_BLOB = POINTER(_CRYPTOAPI_BLOB) +CERT_RDN_VALUE_BLOB = _CRYPTOAPI_BLOB +PCERT_NAME_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_HASH_BLOB = POINTER(_CRYPTOAPI_BLOB) +CRYPT_DATA_BLOB = _CRYPTOAPI_BLOB +DATA_BLOB = _CRYPTOAPI_BLOB +CRYPT_UINT_BLOB = _CRYPTOAPI_BLOB +PCERT_RDN_VALUE_BLOB = POINTER(_CRYPTOAPI_BLOB) +CRYPT_HASH_BLOB = _CRYPTOAPI_BLOB +CRL_BLOB = _CRYPTOAPI_BLOB +PCERT_BLOB = POINTER(_CRYPTOAPI_BLOB) +CRYPT_DIGEST_BLOB = _CRYPTOAPI_BLOB +CRYPT_OBJID_BLOB = _CRYPTOAPI_BLOB +CERT_BLOB = _CRYPTOAPI_BLOB +CRYPT_DER_BLOB = _CRYPTOAPI_BLOB +PDATA_BLOB = POINTER(_CRYPTOAPI_BLOB) +PCRYPT_ATTR_BLOB = POINTER(_CRYPTOAPI_BLOB) +CRYPT_ATTR_BLOB = _CRYPTOAPI_BLOB + class CRYPTCATATTRIBUTE_(Structure): _fields_ = [ ("cbStruct", DWORD), diff --git a/windows/utils/pythonutils.py b/windows/utils/pythonutils.py index 10c2c17..b5ced8e 100644 --- a/windows/utils/pythonutils.py +++ b/windows/utils/pythonutils.py @@ -56,4 +56,7 @@ def print_ctypes_struct(struct, name="", ident=0, hexa=False): except Exception as e: print("Error while printing <{0}> : {1}".format(fname, e)) continue - print_ctypes_struct(value, "{0}.{1}".format(name, fname), hexa=hexa) \ No newline at end of file + print_ctypes_struct(value, "{0}.{1}".format(name, fname), hexa=hexa) + +def sprint(struct, name="struct", hexa=True): + return print_ctypes_struct(struct, name=name, hexa=hexa) \ No newline at end of file diff --git a/windows/winobject/network.py b/windows/winobject/network.py index 1a2a15e..13c4fe2 100644 --- a/windows/winobject/network.py +++ b/windows/winobject/network.py @@ -394,7 +394,7 @@ class FirewallRule(cominterfaces.INetFwRule): return icmp_type_and_code.value def __repr__(self): - return u'<{0} "{1}">'.format(type(self).__name__, self.name) + return u'<{0} "{1}">'.format(type(self).__name__, self.name).encode("ascii", errors='backslashreplace') class Network(object): NetFwPolicy2 = windows.com.IID.from_string("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD") diff --git a/windows/winproxy.py b/windows/winproxy.py index ebd485e..732c6fd 100644 --- a/windows/winproxy.py +++ b/windows/winproxy.py @@ -1380,6 +1380,10 @@ def CertCompareCertificate(dwCertEncodingType, pCertId1, pCertId2): """ return CertCompareCertificate.ctypes_function(dwCertEncodingType, pCertId1, pCertId2) +@Crypt32Proxy('CertEnumCTLsInStore') +def CertEnumCTLsInStore(hCertStore, pPrevCtlContext): + return CertEnumCTLsInStore.ctypes_function(hCertStore, pPrevCtlContext) + @Crypt32Proxy('CryptEncodeObjectEx') def CryptEncodeObjectEx(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded):