From 9cb9c2a9a0d8716b71c48a4bf93fb08337bc1298 Mon Sep 17 00:00:00 2001 From: Clement Rouault Date: Thu, 13 Apr 2017 11:42:52 +0200 Subject: [PATCH] Update doc build --- TODO | 6 + docs/build/html/.buildinfo | 2 +- docs/build/html/_modules/index.html | 21 +- .../_modules/windows/crypto/certificate.html | 545 + .../windows/crypto/encrypt_decrypt.html | 199 + .../_modules/windows/crypto/generation.html | 144 + .../_modules/windows/debug/breakpoints.html | 32 +- .../html/_modules/windows/debug/debugger.html | 97 +- .../html/_modules/windows/debug/localdbg.html | 21 +- docs/build/html/_modules/windows/hooks.html | 25 +- .../_modules/windows/native_exec/cpuid.html | 21 +- .../windows/native_exec/native_function.html | 35 +- .../windows/native_exec/simple_x86.html | 59 +- .../build/html/_modules/windows/pe_parse.html | 951 +- .../html/_modules/windows/remotectypes.html | 89 +- .../build/html/_modules/windows/syswow64.html | 35 +- .../html/_modules/windows/utils/winutils.html | 34 +- .../_modules/windows/winobject/exception.html | 37 +- .../_modules/windows/winobject/handle.html | 43 +- .../_modules/windows/winobject/network.html | 23 +- .../_modules/windows/winobject/process.html | 124 +- .../_modules/windows/winobject/registry.html | 31 +- .../_modules/windows/winobject/service.html | 25 +- .../_modules/windows/winobject/system.html | 23 +- .../_modules/windows/winobject/volume.html | 23 +- .../html/_modules/windows/winobject/wmi.html | 33 +- .../build/html/_modules/windows/wintrust.html | 23 +- docs/build/html/_sources/com.rst.txt | 44 + docs/build/html/_sources/crypto.rst.txt | 101 + docs/build/html/_sources/debug.rst.txt | 88 + docs/build/html/_sources/exception.rst.txt | 99 + docs/build/html/_sources/handle.rst.txt | 10 + docs/build/html/_sources/iat_hook.rst.txt | 113 + docs/build/html/_sources/index.rst.txt | 36 + docs/build/html/_sources/internals.rst.txt | 125 + docs/build/html/_sources/native_exec.rst.txt | 236 + docs/build/html/_sources/network.rst.txt | 27 + docs/build/html/_sources/process.rst.txt | 128 + docs/build/html/_sources/registry.rst.txt | 38 + docs/build/html/_sources/sample.rst.txt | 705 ++ docs/build/html/_sources/service.rst.txt | 15 + docs/build/html/_sources/utils.rst.txt | 34 + docs/build/html/_sources/various.rst.txt | 19 + docs/build/html/_sources/volume.rst.txt | 16 + docs/build/html/_sources/windows.rst.txt | 34 + docs/build/html/_sources/winproxy.rst.txt | 1151 ++ docs/build/html/_sources/wintrust.rst.txt | 40 + docs/build/html/_sources/wip.rst.txt | 6 + docs/build/html/_sources/wmi.rst.txt | 10 + docs/build/html/_static/basic.css | 64 +- docs/build/html/_static/classic.css | 4 +- docs/build/html/_static/comment-bright.png | Bin 3500 -> 756 bytes docs/build/html/_static/comment-close.png | Bin 3578 -> 829 bytes docs/build/html/_static/comment.png | Bin 3445 -> 641 bytes docs/build/html/_static/down-pressed.png | Bin 347 -> 222 bytes docs/build/html/_static/down.png | Bin 347 -> 202 bytes docs/build/html/_static/file.png | Bin 358 -> 286 bytes docs/build/html/_static/jquery-3.1.0.js | 10074 ++++++++++++++++ docs/build/html/_static/jquery.js | 8 +- docs/build/html/_static/minus.png | Bin 173 -> 90 bytes docs/build/html/_static/plus.png | Bin 173 -> 90 bytes docs/build/html/_static/pygments.css | 4 + docs/build/html/_static/searchtools.js | 115 +- docs/build/html/_static/up-pressed.png | Bin 345 -> 214 bytes docs/build/html/_static/up.png | Bin 345 -> 203 bytes docs/build/html/com.html | 18 +- docs/build/html/crypto.html | 627 + docs/build/html/debug.html | 18 +- docs/build/html/exception.html | 23 +- docs/build/html/genindex.html | 2836 ++--- docs/build/html/handle.html | 29 +- docs/build/html/iat_hook.html | 60 +- docs/build/html/index.html | 62 +- docs/build/html/internals.html | 46 +- docs/build/html/native_exec.html | 18 +- docs/build/html/network.html | 23 +- docs/build/html/process.html | 61 +- docs/build/html/py-modindex.html | 74 +- docs/build/html/registry.html | 23 +- docs/build/html/sample.html | 991 +- docs/build/html/search.html | 16 +- docs/build/html/searchindex.js | 2 +- docs/build/html/service.html | 23 +- docs/build/html/utils.html | 20 +- docs/build/html/various.html | 18 +- docs/build/html/volume.html | 23 +- docs/build/html/windows.html | 22 +- docs/build/html/winproxy.html | 394 +- docs/build/html/wintrust.html | 18 +- docs/build/html/wip.html | 36 +- docs/build/html/wmi.html | 23 +- 91 files changed, 18571 insertions(+), 2978 deletions(-) create mode 100644 docs/build/html/_modules/windows/crypto/certificate.html create mode 100644 docs/build/html/_modules/windows/crypto/encrypt_decrypt.html create mode 100644 docs/build/html/_modules/windows/crypto/generation.html create mode 100644 docs/build/html/_sources/com.rst.txt create mode 100644 docs/build/html/_sources/crypto.rst.txt create mode 100644 docs/build/html/_sources/debug.rst.txt create mode 100644 docs/build/html/_sources/exception.rst.txt create mode 100644 docs/build/html/_sources/handle.rst.txt create mode 100644 docs/build/html/_sources/iat_hook.rst.txt create mode 100644 docs/build/html/_sources/index.rst.txt create mode 100644 docs/build/html/_sources/internals.rst.txt create mode 100644 docs/build/html/_sources/native_exec.rst.txt create mode 100644 docs/build/html/_sources/network.rst.txt create mode 100644 docs/build/html/_sources/process.rst.txt create mode 100644 docs/build/html/_sources/registry.rst.txt create mode 100644 docs/build/html/_sources/sample.rst.txt create mode 100644 docs/build/html/_sources/service.rst.txt create mode 100644 docs/build/html/_sources/utils.rst.txt create mode 100644 docs/build/html/_sources/various.rst.txt create mode 100644 docs/build/html/_sources/volume.rst.txt create mode 100644 docs/build/html/_sources/windows.rst.txt create mode 100644 docs/build/html/_sources/winproxy.rst.txt create mode 100644 docs/build/html/_sources/wintrust.rst.txt create mode 100644 docs/build/html/_sources/wip.rst.txt create mode 100644 docs/build/html/_sources/wmi.rst.txt create mode 100644 docs/build/html/_static/jquery-3.1.0.js create mode 100644 docs/build/html/crypto.html diff --git a/TODO b/TODO index 95ce64d..92f79b3 100644 --- a/TODO +++ b/TODO @@ -22,6 +22,12 @@ TODO: - registry - test ! + - Clean pe_parse.py + + + - wintrust doc: + add : https://blogs.msdn.microsoft.com/winsdk/2016/01/05/why-cryptcatadmincalchashfromfilehandle-fails-with-a-seemingly-unexpected-error-code/ + Documentation * verif samples diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo index b2d676d..dec49d7 100644 --- a/docs/build/html/.buildinfo +++ b/docs/build/html/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 2dfc3e603de84cfef16e4ba472fec71f +config: bb938eea015b2c5861daa2467f1a95bd tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_modules/index.html b/docs/build/html/_modules/index.html index 7cd6c30..671a21f 100644 --- a/docs/build/html/_modules/index.html +++ b/docs/build/html/_modules/index.html @@ -6,7 +6,7 @@ - Overview: module code — PythonForWindows 0.2 documentation + Overview: module code — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -45,7 +47,10 @@

All modules for which code is available

-
\ No newline at end of file diff --git a/docs/build/html/_modules/windows/crypto/certificate.html b/docs/build/html/_modules/windows/crypto/certificate.html new file mode 100644 index 0000000..6ea460d --- /dev/null +++ b/docs/build/html/_modules/windows/crypto/certificate.html @@ -0,0 +1,545 @@ + + + + + + + + windows.crypto.certificate — PythonForWindows 0.2 documentation + + + + + + + + + + + + + + +
+
+
+
+ +

Source code for windows.crypto.certificate

+import itertools
+import ctypes
+
+import windows
+from windows import winproxy
+from windows.generated_def import *
+
+from windows.crypto import DEFAULT_ENCODING
+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
+    ]
+
+CRYPT_OBJECT_FORMAT_TYPE_DICT = {x:x for x in CRYPT_OBJECT_FORMAT_TYPE}
+
+## Move CryptObject to new .py ?
+
[docs]class CryptObject(object): + """Extract information from an CryptoAPI 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} + + def __init__(self, filename, content_type=CERT_QUERY_CONTENT_FLAG_ALL): + # No other API than filename for now.. + self.filename = filename + + dwEncoding = DWORD() + dwContentType = DWORD() + dwFormatType = DWORD() + hStore = PVOID() + hMsg = PVOID() + + winproxy.CryptQueryObject(CERT_QUERY_OBJECT_FILE, + LPWSTR(filename), + content_type, + CERT_QUERY_FORMAT_FLAG_BINARY, + 0, + dwEncoding, + dwContentType, + dwFormatType, + hStore, + hMsg, + None) + + self.hstore = hStore + self.hmsg = hMsg + self.encoding = dwEncoding + self.content_type = CRYPT_OBJECT_FORMAT_TYPE_DICT.get(dwContentType.value, dwContentType) + + def msg_get_param(self, param_type, index=0): + signer_info = DWORD() + # https://msdn.microsoft.com/en-us/library/windows/desktop/aa380227(v=vs.85).aspx + winproxy.CryptMsgGetParam(self.hmsg, param_type, index, None, signer_info) + buffer = ctypes.c_buffer(signer_info.value) + winproxy.CryptMsgGetParam(self.hmsg, param_type, index, buffer, signer_info) + + if param_type in self.MSG_PARAM_KNOW_TYPES: + buffer = self.MSG_PARAM_KNOW_TYPES[param_type].from_buffer(buffer) + return buffer + + @property + def nb_signer(self): + """The number of signers for the CryptObject + + :type: :class:`int` + """ + return self.msg_get_param(CMSG_SIGNER_COUNT_PARAM).value + +
[docs] def get_signer_data(self, index=0): + """Returns the signer informations for signer nb ``index`` + + :return: :class:`CMSG_SIGNER_INFO` + """ + return self.msg_get_param(CMSG_SIGNER_INFO_PARAM, index)
+ +
[docs] def get_signer_certificate(self, index=0): + """Return the certificate used for signer nb ``index`` + + :return: :class:`CertificateContext` + """ + data = self.get_signer_data(index) + cert_info = CERT_INFO() + cert_info.Issuer = data.Issuer + cert_info.SerialNumber = data.SerialNumber + rawcertcontext = winproxy.CertFindCertificateInStore(self.hstore, self.encoding, 0, CERT_FIND_SUBJECT_CERT, byref(cert_info), None) + #return rawcertcontext + return CertificateContext(rawcertcontext[0])
+ + def get_raw_cert(self, index=0): + return self.msg_get_param(CMSG_CERT_PARAM, index) + +
[docs] def get_cert(self, index=0): + """Return embded certificate number ``index``. + + note: not all embded certificate are directly used to sign the :class:`CryptObject`. + + :return: :class:`CertificateContext` + """ + return CertificateContext.from_buffer(self.get_raw_cert(index))
+ + cert = property(get_cert) + + @property + def nb_cert(self): + """The number of certificate embded in the :class:`CryptObject` + + :type: :class:`int` + """ + return self.msg_get_param(CMSG_CERT_COUNT_PARAM).value + + def __repr__(self): + return '<{0} "{1}" content_type={2}>'.format(type(self).__name__, self.filename, self.content_type)
+ + +
[docs]class EHCERTSTORE(HCERTSTORE): + """A certificate store""" + @property + def certs(self): + """The certificates in the store + + :type: [:class:`CertificateContext`] -- A list of Certificate + """ + res = [] + last = None + while True: + try: + cert = winproxy.CertEnumCertificatesInStore(self, last) + except winproxy.Kernel32Error as e: + if (e.winerror & 0xffffffff) in (CRYPT_E_NOT_FOUND,): + return tuple(res) + raise + # Need to duplicate as CertEnumCertificatesInStore will free the context 'last' + ecert = windows.crypto.CertificateContext(cert[0]) + res.append(ecert.duplicate()) + last = ecert + raise RuntimeError("Out of infinit loop") + +
[docs] def add_certificate(self, certificate): + """Add a certificate to the store""" + winproxy.CertAddCertificateContextToStore(self, certificate, CERT_STORE_ADD_NEW, None)
+ + @classmethod +
[docs] 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) + return ctypes.cast(res, cls)
+ + + # See https://msdn.microsoft.com/en-us/library/windows/desktop/aa388136(v=vs.85).aspx + @classmethod +
[docs] def from_system_store(cls, store_name): + """Create a new :class:`EHCERTSTORE` from system store``store_name`` + (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa388136(v=vs.85).aspx) + """ + res = winproxy.CertOpenStore(CERT_STORE_PROV_SYSTEM_A, DEFAULT_ENCODING, None, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_READONLY_FLAG, store_name) + return ctypes.cast(res, cls)
+ + @classmethod +
[docs] def new_in_memory(cls): + """Create a new temporary :class:`EHCERTSTORE` in memory""" + res = winproxy.CertOpenStore(CERT_STORE_PROV_MEMORY, DEFAULT_ENCODING, None, 0, None) + return ctypes.cast(res, cls)
+ + # Add API arround 'CertFindCertificateInStore' ? + +# 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' +
[docs]def import_pfx(pfx, password=None, flags=CRYPT_USER_KEYSET | PKCS12_NO_PERSIST_KEY): + """Import the file ``pfx`` with the ``password``. + + ``default flags = PKCS12_NO_PERSIST_KEY | CRYPT_USER_KEYSET``. + + ``PKCS12_NO_PERSIST_KEY`` tells ``CryptoAPI`` to NOT save the keys in a on-disk container. + + :return: :class:`EHCERTSTORE` + """ + if isinstance(pfx, basestring): + pfx = ECRYPT_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 ? +
[docs]class CertificateContext(PCCERT_CONTEXT): + """Represent a Certificate. + + note: It is a pointer ctypes structure (``PCCERT_CONTEXT``) + """ + _type_ = PCCERT_CONTEXT._type_ # Not herited from PCCERT_CONTEXT + + + def __repr__(self): + return '<{0} "{1}" serial="{2}">'.format(type(self).__name__, self.name, self.serial) + + @property + def raw_serial(self): + """The raw serial number of the certificate. + + :type: [:class:`int`]: A list of int ``0 <= x <= 255``""" + serial_number = self[0].pCertInfo[0].SerialNumber + return [(c & 0xff) for c in serial_number.pbData[:serial_number.cbData][::-1]] + + @property + def serial(self): + """The string representation of the certificate's serial. + + :type: :class:`str` + """ + serial_number = self[0].pCertInfo[0].SerialNumber + serial_bytes = self.raw_serial + return " ".join("{:02x}".format(x) for x in serial_bytes) + + +
[docs] def get_name(self, nametype=CERT_NAME_SIMPLE_DISPLAY_TYPE, flags=0): + """Retrieve the subject or issuer name of the certificate. See ``CertGetNameStringA`` + + :returns: :class:`str` + """ + size = winproxy.CertGetNameStringA(self, nametype, flags, None, None, 0) + namebuff = ctypes.c_buffer(size) + size = winproxy.CertGetNameStringA(self, nametype, flags, None, namebuff, size) + return namebuff[:-1]
+ + name = property(get_name) + """The name of the certificate. + + :type: :class:`str`""" + + @property + def issuer(self): + """The name of the certificate's issuer. + + :type: :class:`str`""" + return self.get_name(flags=CERT_NAME_ISSUER_FLAG) + + @property + def store(self): + """The certificate store that contains the certificate + + :type: :class:`EHCERTSTORE` + """ + return EHCERTSTORE(self[0].hCertStore) + + def get_raw_certificate_chains(self): # Rename to all_chains ? + chain_context = EPCCERT_CHAIN_CONTEXT() + + enhkey_usage = CERT_ENHKEY_USAGE() + enhkey_usage.cUsageIdentifier = 0 + enhkey_usage.rgpszUsageIdentifier = None + + cert_usage = CERT_USAGE_MATCH() + cert_usage.dwType = USAGE_MATCH_TYPE_AND + cert_usage.Usage = enhkey_usage + + chain_para = CERT_CHAIN_PARA() + chain_para.cbSize = sizeof(chain_para) + chain_para.RequestedUsage = cert_usage + + winproxy.CertGetCertificateChain(None, self, None, self[0].hCertStore, byref(chain_para), 0, None, byref(chain_context)) + #return CertficateChain(chain_context) + return chain_context + + @property # fixedproperty ? + def chains(self): + """The list of chain context available for this certificate. Each elements of this list is a list of ``CertificateContext`` that should + go from the ``self`` certificate to a trusted certificate. + + :type: [[:class:`CertificateContext`]] -- A list of chain (list) of :class:`CertificateContext` + """ + chain_context = self.get_raw_certificate_chains() + res = [] + for chain in chain_context.chains: + chain_res = [elt.cert for elt in chain.elements] + res.append(chain_res) + return res + + # API Arround CertSelectCertificateChains ? + # https://msdn.microsoft.com/en-us/library/windows/desktop/dd433797(v=vs.85).aspx + +
[docs] def duplicate(self): + """Duplicate the certificate by incrementing the internal refcount. (see ``CertDuplicateCertificateContext``) + + note: The object returned is ``self`` + + :return: :class:`CertificateContext` + """ + res = winproxy.CertDuplicateCertificateContext(self) + # Check what the doc says: the pointer returned is actually the PCERT in parameter + # 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: + raise ValueError("CertDuplicateCertificateContext did not returned the argument (check doc)") + return self
+ + def enum_properties(self): + prop = 0 + res = [] + while True: + prop = winproxy.CertEnumCertificateContextProperties(self, prop) + if not prop: + return res + res.append(prop) + raise RuntimeError("Unreachable code") + + properties = property(enum_properties) + + #def get_property(self): + # https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079(v=vs.85).aspx + # - Usefull: + # CERT_SHA1_HASH_PROP_ID + + + @property + def encoded(self): + """The encoded certificate. + + :type: :class:`bytearray`""" + return bytearray(self[0].pbCertEncoded[:self[0].cbCertEncoded]) + + @classmethod +
[docs] def from_file(cls, filename): + """Create a :class:`CertificateContext` from the file ``filename`` + + :return: :class:`CertificateContext` + """ + with open(filename, "rb") as f: + data = f.read() + buf = (ctypes.c_ubyte * len(data))(*bytearray(data)) + res = windows.winproxy.CertCreateCertificateContext(windows.crypto.DEFAULT_ENCODING, buf, len(data)) + return ctypes.cast(res, cls)
+ + @classmethod +
[docs] def from_buffer(cls, data): + """Create a :class:`CertificateContext` from the buffer ``data`` + + :return: :class:`CertificateContext` + """ + buf = (ctypes.c_ubyte * len(data))(*bytearray(data)) + res = windows.winproxy.CertCreateCertificateContext(windows.crypto.DEFAULT_ENCODING, buf, len(data)) + return ctypes.cast(res, cls)
+ + def __eq__(self, other): + if not isinstance(other, CertificateContext): + return NotImplemented + return windows.winproxy.CertCompareCertificate(DEFAULT_ENCODING, self[0].pCertInfo, other[0].pCertInfo)
+ + # CertCompareCertificate ? + # https://msdn.microsoft.com/en-us/library/windows/desktop/aa376027(v=vs.85).aspx + + +# class CertficateChain(object): +# def __init__(self, pc_chain_context): +# self.chain = pc_chain_context[0] +# +# def to_list(self): +# res = [] +# for i in range(self.chain.rgpChain[0][0].cElement): +# res.append(CertificateContext(self.chain.rgpChain[0][0].rgpElement[i][0].pCertContext[0])) +# return res + + +# Those classes are more of a POC than anything else + +class EPCCERT_CHAIN_CONTEXT(PCCERT_CHAIN_CONTEXT): + _type_ = 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) + res.append(simple_chain) + return res + + @property + def all_cert(self): + res = [] + for chain in self.chains: + ch = [] + res.append(ch) + for element in chain.elements: + ch.append(element.cert) + return res + +class EPCCERT_SIMPLE_CHAIN(PCCERT_SIMPLE_CHAIN): + _type_ = PCCERT_SIMPLE_CHAIN._type_ + + @property + def elements(self): + res = [] + for i in range(self[0].cElement): + element = ctypes.cast(self[0].rgpElement[i], EPCERT_CHAIN_ELEMENT) + res.append(element) + return res + +class EPCERT_CHAIN_ELEMENT(PCERT_CHAIN_ELEMENT): + _type_ = PCERT_CHAIN_ELEMENT._type_ + + @property + def cert(self): + return ctypes.cast(self[0].pCertContext, CertificateContext) + + +# Move this in another .py ? +
[docs]class CryptContext(HCRYPTPROV): + """ A context manager arround ``CryptAcquireContextW`` & ``CryptReleaseContext``""" + _type_ = HCRYPTPROV._type_ + + def __init__(self, pszContainer=None, pszProvider=None, dwProvType=0, dwFlags=0, retrycreate=False): + self.pszContainer = pszContainer + self.pszProvider = pszProvider + self.dwProvType = dwProvType + self.dwFlags = dwFlags + self.retrycreate = True + #self.value = HCRYPTPROV() + pass + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *args): + self.release() + + def acquire(self): + try: + return winproxy.CryptAcquireContextW(self, self.pszContainer, self.pszProvider, self.dwProvType, self.dwFlags) + except WindowsError as e: + if not self.retrycreate: + raise + return winproxy.CryptAcquireContextW(self, self.pszContainer, self.pszProvider, self.dwProvType, self.dwFlags | CRYPT_NEWKEYSET) + + def release(self): + return winproxy.CryptReleaseContext(self, False)
+
+ +
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/crypto/encrypt_decrypt.html b/docs/build/html/_modules/windows/crypto/encrypt_decrypt.html new file mode 100644 index 0000000..87bc67f --- /dev/null +++ b/docs/build/html/_modules/windows/crypto/encrypt_decrypt.html @@ -0,0 +1,199 @@ + + + + + + + + windows.crypto.encrypt_decrypt — PythonForWindows 0.2 documentation + + + + + + + + + + + + + + +
+
+
+
+ +

Source code for windows.crypto.encrypt_decrypt

+from os import urandom
+
+from windows import winproxy
+from windows.crypto import DEFAULT_ENCODING
+from windows.crypto.helper import ECRYPT_DATA_BLOB
+from windows.generated_def import *
+
+def encode_init_vector(data):
+    blob = ECRYPT_DATA_BLOB.from_string(data)
+    size = DWORD()
+    buf = None
+    winproxy.CryptEncodeObjectEx(DEFAULT_ENCODING, X509_OCTET_STRING, ctypes.byref(blob), 0, None, buf, size)
+    buf = (BYTE * size.value)()
+    winproxy.CryptEncodeObjectEx(DEFAULT_ENCODING, X509_OCTET_STRING, ctypes.byref(blob), 0, None, buf, size)
+    return buf[:]
+
+
+class GenerateInitVector(object):
+    def __repr__(self):
+        return "GenerateInitVector()"
+
+    def generate_init_vector(self, algo):
+        if algo in [szOID_OIWSEC_desCBC, szOID_RSA_DES_EDE3_CBC]:
+            return urandom(8)
+        if algo in [szOID_NIST_AES128_CBC, szOID_NIST_AES192_CBC, szOID_NIST_AES256_CBC]:
+            return urandom(16)
+        return None
+geninitvector = GenerateInitVector()
+
+
+
[docs]def encrypt(cert_or_certlist, msg, algo=szOID_RSA_DES_EDE3_CBC, initvector=geninitvector): + """Encrypt ``msg`` with the certificate(s) in ``cert_or_certlist`` using ``algo`` with the initial + vector ``initvector``. + + If ``geninitvector`` is left as it is, it will generate a random one. + + Algorithms supported by ``GenerateInitVector`` are: + + * ``szOID_OIWSEC_desCBC`` + * ``szOID_RSA_DES_EDE3_CBC`` + * ``szOID_NIST_AES128_CBC`` + * ``szOID_NIST_AES192_CBC`` + * ``szOID_NIST_AES256_CBC`` + + :return: :class:`bytearray`: The encrypted message + """ + alg_ident = CRYPT_ALGORITHM_IDENTIFIER() + alg_ident.pszObjId = algo + if isinstance(cert_or_certlist, PCERT_CONTEXT): + certlist = (cert_or_certlist,) + else: + certlist = tuple(cert_or_certlist) + + # Set (compute if needed) the IV + if initvector is None: + alg_ident.Parameters.cbData = 0 + elif initvector is geninitvector: + initvector = initvector.generate_init_vector(algo) + if initvector is None: + raise ValueError("I don't know how to generate an <initvector> for <{0}> please provide one (or None)".format(algo)) + initvector_encoded = encode_init_vector(initvector) + alg_ident.Parameters = ECRYPT_DATA_BLOB.from_string(initvector_encoded) + else: + initvector_encoded = encode_init_vector(initvector) + alg_ident.Parameters = ECRYPT_DATA_BLOB.from_string(initvector_encoded) + + # Setup encryption parameters + param = CRYPT_ENCRYPT_MESSAGE_PARA() + param.cbSize = ctypes.sizeof(param) + param.dwMsgEncodingType = DEFAULT_ENCODING + param.hCryptProv = None + param.ContentEncryptionAlgorithm = alg_ident + param.pvEncryptionAuxInfo = None + param.dwFlags = 0 + param.dwInnerContentType = 0 + + certs = (PCERT_CONTEXT * len(certlist))(*certlist) + #Ask the output buffer size + size = DWORD() + winproxy.CryptEncryptMessage(param, len(certs), certs, msg, len(msg), None, size) + #Encrypt the msg + buf = (BYTE * size.value)() + winproxy.CryptEncryptMessage(param, len(certs), certs, msg, len(msg), buf, size) + return bytearray(buf[:size.value])
+ + +
[docs]def decrypt(cert_store, encrypted): + """Try to decrypt the ``encrypted`` msg with any certificate in ``cert_store``. + + If there is no certificate able to decrypt the message ``Kernel32Error(winerror=0x8009200c)`` is raised. + + :return: :class:`str`: The decrypted message + """ + # Setup decryption parameters + dparam = CRYPT_DECRYPT_MESSAGE_PARA() + dparam.cbSize = ctypes.sizeof(dparam) + dparam.dwMsgAndCertEncodingType = DEFAULT_ENCODING + dparam.cCertStore = 1 + dparam.rghCertStore = (cert_store,) + dparam.dwFlags = 0 + + #Ask the output buffer size + buf = (BYTE * len(encrypted)).from_buffer_copy(encrypted) + dcryptsize = DWORD() + winproxy.CryptDecryptMessage(dparam, buf, ctypes.sizeof(buf), None, dcryptsize, None) + #Decrypt the msg + dcryptbuff = (BYTE * dcryptsize.value)() + winproxy.CryptDecryptMessage(dparam, buf, ctypes.sizeof(buf), dcryptbuff, dcryptsize, None) + return str(bytearray(dcryptbuff[:dcryptsize.value]))
+
+ +
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/crypto/generation.html b/docs/build/html/_modules/windows/crypto/generation.html new file mode 100644 index 0000000..240afd3 --- /dev/null +++ b/docs/build/html/_modules/windows/crypto/generation.html @@ -0,0 +1,144 @@ + + + + + + + + windows.crypto.generation — PythonForWindows 0.2 documentation + + + + + + + + + + + + + + +
+
+
+
+ +

Source code for windows.crypto.generation

+from windows import winproxy
+from windows.generated_def import *
+
+from windows.crypto.helper import ECRYPT_DATA_BLOB
+from windows.crypto import DEFAULT_ENCODING, EHCERTSTORE
+
+
+
[docs]def generate_selfsigned_certificate(name="CN=DEFAULT", prov=None, key_info=None, flags=0, signature_algo=None): + """Generate a selfsigned certificate. + + See https://msdn.microsoft.com/en-us/library/windows/desktop/aa376039(v=vs.85).aspx + + :return: :class:`windows.crypto.CertificateContext` + """ + size = ULONG(len(name) + 0x100) + buffer = (ctypes.c_ubyte * size.value)() + winproxy.CertStrToNameA(X509_ASN_ENCODING, name, CERT_OID_NAME_STR, None, buffer, size, None) + blobname = ECRYPT_DATA_BLOB(size.value, buffer) + cert = winproxy.CertCreateSelfSignCertificate(prov, blobname, flags, key_info, signature_algo, None, None, None) + return windows.crypto.CertificateContext(cert[0])
+ + +
[docs]def generate_key(prov, keytype=AT_KEYEXCHANGE, flags=CRYPT_EXPORTABLE): + """Generate a keypair if type ``keytype``. + + :return: :class:`HCRYPTKEY` + """ + key = HCRYPTKEY() + winproxy.CryptGenKey(prov, keytype, flags , key) + return key
+ # print(key[0]) + # print("[OK] Key created") + # size = DWORD() + # winproxy.CryptExportKey(key, None, PRIVATEKEYBLOB, 0, None, size) + # buffer = (BYTE * size.value)() + # print("needed size = {0}".format(size)) + # winproxy.CryptExportKey(key, None, PRIVATEKEYBLOB, 0, buffer, size) + # print("[OK] Key in buffer") + # keyraw = bytearray(buffer) + # # openssl.exe rsa -in key.out -inform MS\PRIVATEKEYBLOB -text + # save_as(keyraw, "key.out") + # #res = ctypes.WinDLL("advapi32").CryptReleaseContext(prov, 0) + # return key + +
[docs]def generate_pfx(hstore, password=None): + """Generate a pfx protected by ``password`` contaning the certificates in ``hstore`` + + :return: :class:`bytearray` -- The raw PFX + """ + blob = ECRYPT_DATA_BLOB(0, None) + winproxy.PFXExportCertStoreEx(hstore, blob, password, None, EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY) + blob.pbData = (ctypes.c_ubyte * blob.cbData)() + winproxy.PFXExportCertStoreEx(hstore, blob, password, None, EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY) + return blob.data
+
+ +
+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/debug/breakpoints.html b/docs/build/html/_modules/windows/debug/breakpoints.html index 66b0c42..741c9da 100644 --- a/docs/build/html/_modules/windows/debug/breakpoints.html +++ b/docs/build/html/_modules/windows/debug/breakpoints.html @@ -6,7 +6,7 @@ - windows.debug.breakpoints — PythonForWindows 0.2 documentation + windows.debug.breakpoints — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -99,7 +100,7 @@ """``size``: the size of the memory breakpoint. ``events``: a string representing the events that interest the BP (any of "RWX")""" - super(MemoryBreakpoint, self).__init__(addr) + super(MemoryBreakpoint, self).__init__(addr) self.size = size if size is not None else self.DEFAULT_SIZE events = events if events is not None else self.DEFAULT_EVENTS self.events = set(events) @@ -126,14 +127,15 @@ def __init__(self, target, addr=None): if addr is None: addr = "{0}!{1}".format(target.target_dll, target.target_func) - super(FunctionParamDumpBP, self).__init__(addr) + super(FunctionParamDumpBP, self).__init__(addr) self.target = target self.target_args = target.prototype._argtypes_ + self.target_params = target.params def extract_arguments_32bits(self, cproc, cthread): x = windows.debug.X86ArgumentRetriever() res = OrderedDict() - for i, (name, type) in enumerate(zip(self.target.params, self.target_args)): + for i, (name, type) in enumerate(zip(self.target_params, self.target_args)): value = x.get_arg(i, cproc, cthread) rt = windows.remotectypes.transform_type_to_remote32bits(type) if issubclass(rt, windows.remotectypes.RemoteValue): @@ -151,7 +153,7 @@ def extract_arguments_64bits(self, cproc, cthread): x = windows.debug.X64ArgumentRetriever() res = OrderedDict() - for i, (name, type) in enumerate(zip(self.target.params, self.target_args)): + for i, (name, type) in enumerate(zip(self.target_params, self.target_args)): value = x.get_arg(i, cproc, cthread) rt = windows.remotectypes.transform_type_to_remote64bits(type) if issubclass(rt, windows.remotectypes.RemoteValue): @@ -180,7 +182,7 @@ class FunctionRetBP(Breakpoint): def __init__(self, addr, initial_breakpoint): - super(FunctionRetBP, self).__init__(addr) + super(FunctionRetBP, self).__init__(addr) self.initial_breakpoint = initial_breakpoint def trigger(self, dbg, exc): @@ -236,13 +238,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/debug/debugger.html b/docs/build/html/_modules/windows/debug/debugger.html index 0e1e51b..311eac8 100644 --- a/docs/build/html/_modules/windows/debug/debugger.html +++ b/docs/build/html/_modules/windows/debug/debugger.html @@ -6,7 +6,7 @@ - windows.debug.debugger — PythonForWindows 0.2 documentation + windows.debug.debugger — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -105,7 +106,7 @@ self.breakpoints = {} self._pending_breakpoints = {} #Breakpoints to put in new process / threads # Values rewritten by "\xcc" - self._memory_save = defaultdict(dict) + self._memory_save = dict() # Dict of {tid : {drx taken : BP}} self._hardware_breakpoint = {} # Breakpoints to reput.. @@ -124,18 +125,29 @@ @classmethod -
    [docs] def attach(cls, target): +
    [docs] def attach(cls, target): """attach to ``target`` (must be a :class:`WinProcess`) :rtype: :class:`Debugger`""" winproxy.DebugActiveProcess(target.pid) - return cls(target)
    + return cls(target)
    [docs] def detach(self, target=None): """Detach from all debugged processes or process ``target``""" if target is None: - for proc in self.processes.values(): + targets = self.processes.values() + if not targets: + # We are not following any process + # maybe a attach/detach with Debugger.loop + # Just detach from the initial target + if self.target: + tpid = self.target.pid + self.target = None # Remove ref to process -> GC -> CloseHandle -> process is destroyed + windows.winproxy.DebugActiveProcessStop(tpid) + return + for proc in targets: self.detach(proc) + del targets return if not isinstance(target, WinProcess): raise ValueError("Detach accept only WinProcess") @@ -158,26 +170,36 @@ del self._explicit_single_step[thread.tid] del self._breakpoint_to_reput[thread.tid] del self.threads[thread.tid] + ctx = thread.context + if ctx.EEFlags.TF: # Remove TRAPFlag before detaching (or it will lead to a crash) + ctx.EEFlags.TF = 0 + thread.set_context(ctx) del self.processes[target.pid] del self._watched_pages[target.pid] + del self._module_by_process[target.pid] + if target is self.current_process: self._finish_debug_event(self.REMOVE_ME_debug_event, DBG_CONTINUE) + self.current_process = None + self.current_thread = None + if target.pid == self.target.pid: + self.target = None windows.winproxy.DebugActiveProcessStop(target.pid)
    def _killed_in_action(self): """Return ``True`` if current process have been detached by user callback""" - return self.current_process.pid not in self.processes - + # Fix ? _handle_exit_process remove from processes but need a FinishDebugEvent + return self.current_process is None or self.current_process.pid not in self.processes @classmethod -
    [docs] def debug(cls, path, args=None, dwCreationFlags=0, show_windows=False): +
    [docs] def debug(cls, path, args=None, dwCreationFlags=0, show_windows=False): """Create a process and debug it. :rtype: :class:`Debugger`""" dwCreationFlags |= DEBUG_PROCESS c = windows.utils.create_process(path, args=args, dwCreationFlags=dwCreationFlags, show_windows=show_windows) - return cls(c)
    + return cls(c)
    def _init_dispatch_handlers(self): dbg_evt_dispatch = {} @@ -219,6 +241,7 @@ return x def _resolve(self, addr, target): + dbgprint("Resolving <{0}> in <{1}>".format(addr, target), "DBG") if not isinstance(addr, basestring): return addr dll, api = addr.split("!") @@ -239,6 +262,7 @@ pass exports = mod[0].exports if api not in exports: + dbgprint("Error resolving <{0}> in <{1}>".format(addr, target), "DBG") raise ValueError("Unknown API <{0}> in DLL {1}".format(api, dll)) return exports[api] @@ -436,6 +460,8 @@ for bp in self._pending_breakpoints_new[None]: if isinstance(bp.addr, basestring): target_dll = bp.addr.lower().split("!")[0] + # Cannot work AS-IS yet. Implement it ? + # if target_dll == "*" or target_dll == dll_name: if target_dll == dll_name: _setup_method = getattr(self, "_setup_breakpoint_" + bp.type) if bp.apply_to_target(self.current_process): @@ -499,6 +525,7 @@ thread.set_syswow_context(ctx) else: thread.set_context(ctx) + del thread continue_flag = self._dispatch_breakpoint(exception, excp_addr) if self._killed_in_action(): return continue_flag @@ -537,6 +564,8 @@ continue_flag = self.on_single_step(exception) if self._killed_in_action(): return continue_flag + # Does not handle case where EEFlags.TF was by the debugge before trigering the exception + # Should set the flag explicitly in single_step ? and not just use EEFlags.TF ? self._explicit_single_step[self.current_thread.tid] = self.current_thread.context.EEFlags.TF return continue_flag else: @@ -544,6 +573,8 @@ continue_flag = self.on_exception(exception) if self._killed_in_action(): return continue_flag + # Does not handle case where EEFlags.TF was by the debugge before trigering the exception + # Should set the flag explicitly in single_step ? and not just use EEFlags.TF ? self._explicit_single_step[self.current_thread.tid] = self.current_thread.context.EEFlags.TF return continue_flag @@ -604,9 +635,9 @@ self._update_debugger_state(debug_event) if windows.current_process.bitness == 32: - exception.__class__ = winexception.EEXCEPTION_DEBUG_INFO32 + exception.__class__ = winexception.EEXCEPTION_DEBUG_INFO32 else: - exception.__class__ = winexception.EEXCEPTION_DEBUG_INFO64 + exception.__class__ = winexception.EEXCEPTION_DEBUG_INFO64 excp_code = exception.ExceptionRecord.ExceptionCode excp_addr = exception.ExceptionRecord.ExceptionAddress @@ -657,9 +688,16 @@ proc_handle = HANDLE() thread_handle = HANDLE() cp_handle = windows.current_process.handle + winproxy.DuplicateHandle(cp_handle, create_process.hProcess, cp_handle, ctypes.byref(proc_handle), dwOptions=DUPLICATE_SAME_ACCESS) winproxy.DuplicateHandle(cp_handle, create_process.hThread, cp_handle, ctypes.byref(thread_handle), dwOptions=DUPLICATE_SAME_ACCESS) + dbgprint(" Got PROC handle {0:#x}".format(create_process.hProcess, self), "HANDLE") + dbgprint(" PROC handle duplicated: {0:#x}".format(proc_handle.value), "HANDLE") + + dbgprint(" Got THREAD handle {0:#x}".format(create_process.hThread, self), "HANDLE") + dbgprint(" THREAD handle duplicated: {0:#x}".format(thread_handle.value), "HANDLE") + self.current_process = WinProcess._from_handle(proc_handle.value) self.current_thread = WinThread._from_handle(thread_handle.value) @@ -670,6 +708,7 @@ self.processes[self.current_process.pid] = self.current_process self._watched_pages[self.current_process.pid] = {} #defaultdict(list) self.breakpoints[self.current_process.pid] = {} + self._memory_save[self.current_process.pid] = {} self._module_by_process[self.current_process.pid] = {} self._update_debugger_state(debug_event) self._setup_pending_breakpoints_new_process(self.current_process) @@ -689,6 +728,16 @@ del self._breakpoint_to_reput[self.current_thread.tid] del self.processes[self.current_process.pid] del self._watched_pages[self.current_process.pid] + del self._memory_save[self.current_process.pid] + del self._module_by_process[self.current_process.pid] + + cpid = self.current_process.pid + self.current_thread = None + self.current_process = None + + if cpid == self.target.pid: + self.target = None + return retvalue def _handle_create_thread(self, debug_event): @@ -766,7 +815,11 @@ dbg_continue_flag = self._dispatch_debug_event(debug_event) if dbg_continue_flag is None: dbg_continue_flag = DBG_CONTINUE - if not self._killed_in_action(): + if debug_event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT or not self._killed_in_action(): + #if not self._killed_in_action(): + # should we always _finish_debug_event even if process was killed ? + # rhaaa _killed_in_action is a REALLY bad name, it's not killed, it's detached + # TODO: FIXME self._finish_debug_event(debug_event, dbg_continue_flag) if not self.processes: break @@ -854,7 +907,7 @@ if target is None: target = self.current_process res = {} - cp_watch_page = self._watched_pages[self.current_process.pid] + cp_watch_page = self._watched_pages[target.pid] page_protection = DWORD() for page_addr, watched_page in cp_watch_page.items(): target.virtual_protect(page_addr, PAGE_SIZE, watched_page.original_prot, page_protection) @@ -981,13 +1034,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/debug/localdbg.html b/docs/build/html/_modules/windows/debug/localdbg.html index f3a7113..cd14d25 100644 --- a/docs/build/html/_modules/windows/debug/localdbg.html +++ b/docs/build/html/_modules/windows/debug/localdbg.html @@ -6,7 +6,7 @@ - windows.debug.localdbg — PythonForWindows 0.2 documentation + windows.debug.localdbg — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -333,13 +334,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/hooks.html b/docs/build/html/_modules/windows/hooks.html index 156e8a9..d6718f7 100644 --- a/docs/build/html/_modules/windows/hooks.html +++ b/docs/build/html/_modules/windows/hooks.html @@ -6,7 +6,7 @@ - windows.hooks — PythonForWindows 0.2 documentation + windows.hooks — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -76,7 +77,7 @@ def add_callback_to_module(callback): - setattr(sys.modules[__name__], type(callback).__name__, callback) + setattr(sys.modules[__name__], type(callback).__name__, callback) # Generate IATCallback decorator for all known functions for func in winfuncs.functions: @@ -86,7 +87,7 @@ class CallBackDeclaration(KnownCallback): types = (prototype._restype_,) + prototype._argtypes_ - CallBackDeclaration.__name__ = callback_name + CallBackDeclaration.__name__ = callback_name add_callback_to_module(CallBackDeclaration()) @@ -179,13 +180,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/native_exec/cpuid.html b/docs/build/html/_modules/windows/native_exec/cpuid.html index a57355e..117b557 100644 --- a/docs/build/html/_modules/windows/native_exec/cpuid.html +++ b/docs/build/html/_modules/windows/native_exec/cpuid.html @@ -6,7 +6,7 @@ - windows.native_exec.cpuid — PythonForWindows 0.2 documentation + windows.native_exec.cpuid — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -236,13 +237,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/native_exec/native_function.html b/docs/build/html/_modules/windows/native_exec/native_function.html index 57b3f95..408af88 100644 --- a/docs/build/html/_modules/windows/native_exec/native_function.html +++ b/docs/build/html/_modules/windows/native_exec/native_function.html @@ -6,7 +6,7 @@ - windows.native_exec.native_function — PythonForWindows 0.2 documentation + windows.native_exec.native_function — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -79,7 +80,7 @@ m.ob_refcnt += 1 @classmethod - def get_map(cls, size): + def get_map(cls, size): """ Dispatch to the good mmap implem depending on the current system """ systems = {'windows': Win32MyMap, 'linux': UnixMyMap} @@ -91,7 +92,7 @@ class Win32MyMap(MyMap): @classmethod - def get_map(cls, size): + def get_map(cls, size): addr = windows.winproxy.VirtualAlloc(0, size, 0x1000, 0x40) new_map = (ctypes.c_char * size).from_address(addr) new_map.addr = addr @@ -102,9 +103,9 @@ class UnixMyMap(MyMap): @classmethod - def get_map(cls, size): + def get_map(cls, size): prot = mmap.PROT_EXEC | mmap.PROT_WRITE | mmap.PROT_READ - return cls(-1, size, prot=prot) + return cls(-1, size, prot=prot) class CustomAllocator(object): @@ -116,11 +117,11 @@ self.names = [] @classmethod - def get_int_size(cls): + def get_int_size(cls): bits = platform.architecture()[0] - if bits not in cls.int_size: + if bits not in cls.int_size: raise ValueError("Unknow platform bits <{0}>".format(bits)) - return cls.int_size[bits] + return cls.int_size[bits] def get_new_page(self, size): self.maps.append(MyMap.get_map(size)) @@ -193,13 +194,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/native_exec/simple_x86.html b/docs/build/html/_modules/windows/native_exec/simple_x86.html index bf69fab..ed13bb3 100644 --- a/docs/build/html/_modules/windows/native_exec/simple_x86.html +++ b/docs/build/html/_modules/windows/native_exec/simple_x86.html @@ -6,7 +6,7 @@ - windows.native_exec.simple_x86 — PythonForWindows 0.2 documentation + windows.native_exec.simple_x86 — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -96,19 +97,19 @@ return int("".join([str(i) for i in self.array]), 2) @classmethod - def from_string(cls, str_base): + def from_string(cls, str_base): l = [] for c in bytearray(reversed(str_base)): for i in range(8): l.append(c & 1) c = c >> 1 - return cls(len(str_base) * 8, list(reversed(l))) + return cls(len(str_base) * 8, list(reversed(l))) @classmethod - def from_int(cls, size, x): + def from_int(cls, size, x): if x < 0: x = x & ((2 ** size) - 1) - return cls(size, bin(x)[2:]) + return cls(size, bin(x)[2:]) # Prefix @@ -281,8 +282,8 @@ return (None, None) @classmethod - def get_reg_bits(cls, name): - return cls.reg_opcode[name.upper()] + def get_reg_bits(cls, name): + return cls.reg_opcode[name.upper()] # Instruction Parameters @@ -431,7 +432,7 @@ class ModRM_REG__REG(object): @classmethod - def match(cls, arg1, arg2): + def match(cls, arg1, arg2): return X86.is_reg(arg1) and X86.is_reg(arg2) def __init__(self, arg1, arg2, reversed, instr_state): @@ -449,7 +450,7 @@ class ModRM_REG__MEM(object): @classmethod - def match(cls, arg1, arg2): + def match(cls, arg1, arg2): return X86.is_reg(arg1) and X86.is_mem_acces(arg2) def setup_reg_as_register(self, regname, instr_state): @@ -600,10 +601,10 @@ self.value = sum(res, BitArray(0, "")) self.prefix = prefix return - raise ValueError("Cannot encode <{0} {1}>:(".format(type(self).__name__, initial_args)) + raise ValueError("Cannot encode <{0} {1}>:(".format(type(self).__name__, initial_args)) def get_code(self): - prefix_opcode = b"".join(chr(p.PREFIX_VALUE) for p in self.prefix) + prefix_opcode = b"".join(chr(p.PREFIX_VALUE) for p in self.prefix) return prefix_opcode + bytes(self.value.dump()) #def __add__(self, other): @@ -633,12 +634,12 @@ class JmpType(Instruction): """Dispatcher between a real jump or DelayedJump if parameters is a label""" - def __new__(cls, *initial_args): + def __new__(cls, *initial_args): if len(initial_args) == 1: arg = initial_args[0] if isinstance(arg, str) and arg[0] == ":": - return DelayedJump(cls, arg) - return super(JmpType, cls).__new__(cls, *initial_args) + return DelayedJump(cls, arg) + return super(JmpType, cls).__new__(cls, *initial_args) class JmpImm(object): @@ -828,6 +829,16 @@ encoding = [(RawBits.from_int(8, 0xAF),)] +class StosB(Instruction): + encoding = [(RawBits.from_int(8, 0xAA),)] + +class StosW(Instruction): + encoding = [(RawBits.from_int(16, 0x66AB),)] + +class StosD(Instruction): + encoding = [(RawBits.from_int(8, 0xAB),)] + + class CmpsB(Instruction): default_32_bits = True encoding = [(RawBits.from_int(8, 0xa6),)] @@ -892,7 +903,7 @@ def get_code(self): if self.expected_labels: raise ValueError("Unresolved labels: {0}".format(self.expected_labels.keys())) - return b"".join([x[1].get_code() for x in sorted(self.instrs.items())]) + return b"".join([x[1].get_code() for x in sorted(self.instrs.items())]) def add_instruction(self, instruction): if isinstance(instruction, Label): @@ -1117,13 +1128,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/pe_parse.html b/docs/build/html/_modules/windows/pe_parse.html index da3f2e5..6a846d8 100644 --- a/docs/build/html/_modules/windows/pe_parse.html +++ b/docs/build/html/_modules/windows/pe_parse.html @@ -6,7 +6,7 @@ - windows.pe_parse — PythonForWindows 0.2 documentation + windows.pe_parse — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -83,7 +84,7 @@ else: raise NotImplementedError("Parsing {0} PE from {1} Process".format(targetedbitness, proc_bitness)) - def create_structure_at(structcls, addr): + def create_structure_at(structcls, addr): # Il reste une closure sur 'target' ici !! return ctypes_structure_transformer(structcls)(addr, target) return ctypes_structure_transformer, create_structure_at @@ -99,6 +100,351 @@ raise ValueError("Unknow PE target machine <0x{0:x}>".format(machine)) +# def GetPEFile(baseaddr, target=None, force_bitness=None): +# """Returns a :class:`PEFile` to explore a PE loaded at `baseaddr` in process `target`. +# +# :rtype: :class:`PEFile` +# +# .. note:: +# +# If target is ``None`` it refers to the curent process +# """ +# proc_bitness = windows.current_process.bitness +# +# if force_bitness is None: +# targetedbitness = get_pe_bitness(baseaddr, target) +# else: +# targetedbitness = force_bitness +# +# transformers = get_structure_transformer_for_target(target, targetedbitness) +# ctypes_structure_transformer, create_structure_at = transformers +# +# if targetedbitness == 32: +# IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG32 +# else: +# IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG64 +# +# def get_string(addr): +# if target is None: +# return ctypes.c_char_p(addr).value +# return target.read_string(addr) +# +# class RVA(DWORD): +# @property +# def addr(self): +# return baseaddr + self.value +# +# def __repr__(self): +# return "<DWORD {0} (RVA to '{1}')>".format(self.value, hex(self.addr)) +# +# class StringRVa(RVA): +# if target is None: +# @property +# def str(self): +# return get_string(self.addr).decode() +# else: +# @property +# def str(self): +# return get_string(self.addr).decode() +# +# def __repr__(self): +# return "<DWORD {0} (String RVA to '{1}')>".format(self.value, self.str) +# +# def __int__(self): +# return self.value +# +# class IMPORT_BY_NAME(ctypes.Structure): +# _fields_ = [ +# ("Hint", WORD), +# ("Name", BYTE) +# ] +# +# class THUNK_DATA(ctypes.Union): +# _fields_ = [ +# ("Ordinal", PVOID), +# ("AddressOfData", PVOID) +# ] +# +# class IATEntry(ctypes.Structure): +# """Represent an entry in the IAT of a module +# Can be used to get resolved value and setup hook +# """ +# _fields_ = [ +# ("value", PVOID)] +# +# +# +# @classmethod +# def create(cls, addr, ord, name): +# self = create_structure_at(cls, addr) +# self.addr = addr +# self.ord = ord +# self.name = name +# self.hook = None +# self.nonhookvalue = self.value +# return self +# +# def __repr__(self): +# return '<{0} "{1}" ordinal {2}>'.format(self.__class__.__name__, self.name, self.ord) +# +# def set_hook(self, callback, types=None): +# """Setup a hook on the entry and return it. +# You MUST keep a reference to the hook while the hook is enabled. +# +# :param callback: the hook +# +# .. note:: +# +# see :ref:`hook_protocol` +# +# :rtype: :class:`windows.hooks.IATHook` +# +# .. warning:: +# +# This works only for PEFile with the current process as target. +# """ +# if target is not None: +# raise NotImplementedError("Setting hook in remote process (use python code injection)") +# +# hook = hooks.IATHook(self, callback, types) +# self.hook = hook +# hook.enable() +# return hook +# +# def remove_hook(self): +# """Remove the hook on the entry""" +# if self.hook is None: +# return False +# self.hook.disable() +# self.hook = None +# return True +# +# class PEFile(object): +# """Represent a PE loaded in a process (current or remote)""" +# #def __del__(self): +# # print("YOLODEL") +# # import pprint +# # pprint.pprint(vars(self)) +# +# def __init__(self): +# self.baseaddr = baseaddr +# self.bitness = targetedbitness +# +# def get_DOS_HEADER(self): +# return create_structure_at(IMAGE_DOS_HEADER, baseaddr) +# +# def get_NT_HEADER(self): +# return self.get_DOS_HEADER().get_NT_HEADER() +# +# def get_OptionalHeader(self): +# return self.get_NT_HEADER().OptionalHeader +# +# def get_DataDirectory(self): +# # This won't work if we load a PE32 in a 64bit process +# # PE32 .NET... +# #return self.get_OptionalHeader().DataDirectory +# DataDirectory_type = IMAGE_DATA_DIRECTORY * IMAGE_NUMBEROF_DIRECTORY_ENTRIES +# SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader +# if target is None: +# opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) +# else: +# opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr +# DataDirectory_addr = opt_header_addr + SizeOfOptionalHeader - ctypes.sizeof(DataDirectory_type) +# return create_structure_at(DataDirectory_type, DataDirectory_addr) +# +# +# def get_IMPORT_DESCRIPTORS(self): +# import_datadir = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_IMPORT] +# if import_datadir.VirtualAddress == 0: +# return [] +# import_descriptor_addr = RVA(import_datadir.VirtualAddress).addr +# current_import_descriptor = create_structure_at(self.IMAGE_IMPORT_DESCRIPTOR, import_descriptor_addr) +# res = [] +# while current_import_descriptor.FirstThunk: +# res.append(current_import_descriptor) +# import_descriptor_addr += ctypes.sizeof(self.IMAGE_IMPORT_DESCRIPTOR) +# current_import_descriptor = create_structure_at(self.IMAGE_IMPORT_DESCRIPTOR, import_descriptor_addr) +# return res +# +# def get_EXPORT_DIRECTORY(self): +# export_directory_rva = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress +# if export_directory_rva == 0: +# return None +# export_directory_addr = baseaddr + export_directory_rva +# return create_structure_at(self._IMAGE_EXPORT_DIRECTORY, export_directory_addr) +# +# class PESection((IMAGE_SECTION_HEADER)): +# if target is None: +# @property +# def name(self): +# return get_string(ctypes.addressof(self.Name))[:8] +# else: +# @property +# def name(self): +# return get_string(self._base_addr)[:8] +# +# @property +# def start(self): +# return baseaddr + self.VirtualAddress +# +# @property +# def size(self): +# return self.VirtualSize +# +# def __repr__(self): +# return "<PESection \"{0}\">".format(self.name) +# +# @utils.fixedpropety +# def sections(self): +# nt_header = self.get_NT_HEADER() +# nb_section = nt_header.FileHeader.NumberOfSections +# SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader +# if target is None: +# opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) +# else: +# opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr +# base_section = opt_header_addr + SizeOfOptionalHeader +# sections_array = create_structure_at((self.PESection * nb_section), base_section) +# return list(sections_array) +# +# @utils.fixedpropety +# def exports(self): +# """The exports of the PE in a dict. Keys are ordinal (:class:`int`) and name (:class:`str`). +# The values are the addresses of the exports. +# +# :type: {(:class:`int` or :class:`str`) : :class:`int`}""" +# res = {} +# exp_dir = self.get_EXPORT_DIRECTORY() +# if exp_dir is None: +# return res +# raw_exports = exp_dir.get_exports() +# for id, rva_addr, rva_name in raw_exports: +# res[id] = rva_addr.addr +# if rva_name is not None: +# res[rva_name.str] = rva_addr.addr +# return res +# +# @utils.fixedpropety +# def export_name(self): +# """The Name attribute of the ``EXPORT_DIRECTORY``""" +# try: +# return self.get_EXPORT_DIRECTORY().Name.str +# except AttributeError: +# return None +# +# # TODO: get imports by parsing other modules exports if no INT +# @utils.fixedpropety +# def imports(self): +# """The imports of the PE in a dict. +# Keys are the names of DLL to import from and values are :class:`list` +# of :class:`IATEntry` +# +# :type: {:class:`str` : [:class:`IATEntry`]}""" +# res = {} +# for import_descriptor in self.get_IMPORT_DESCRIPTORS(): +# INT = import_descriptor.get_INT() +# IAT = import_descriptor.get_IAT() +# if INT is not None: +# for iat_entry, (ord, name) in zip(IAT, INT): +# # str(name.decode()) -> python2 and python3 compatible for str result +# iat_entry.ord = ord +# iat_entry.name = str(name.decode()) if name else "" +# res.setdefault(import_descriptor.Name.str.lower(), []).extend(IAT) +# return res +# +# # Will be usable as `self.IMAGE_IMPORT_DESCRIPTOR` +# class IMAGE_IMPORT_DESCRIPTOR(ctypes.Structure): +# _fields_ = transform_ctypes_fields(IMAGE_IMPORT_DESCRIPTOR, {"Name": StringRVa, "OriginalFirstThunk": RVA, "FirstThunk": RVA}) +# +# def get_INT(self): +# if not self.OriginalFirstThunk.value: +# return None +# int_addr = self.OriginalFirstThunk.addr +# int_entry = create_structure_at(THUNK_DATA, int_addr) +# res = [] +# while int_entry.Ordinal: +# if int_entry.Ordinal & IMAGE_ORDINAL_FLAG: +# res += [(int_entry.Ordinal & 0x7fffffff, None)] +# else: +# import_by_name = create_structure_at(IMPORT_BY_NAME, baseaddr + int_entry.AddressOfData) +# name_address = baseaddr + int_entry.AddressOfData + type(import_by_name).Name.offset +# if target is None: +# name = get_string(name_address) +# else: +# name = get_string(name_address).decode() +# res.append((import_by_name.Hint, name)) +# int_addr += ctypes.sizeof(type(int_entry)) +# int_entry = create_structure_at(THUNK_DATA, int_addr) +# return res +# +# def get_IAT(self): +# iat_addr = self.FirstThunk.addr +# iat_entry = create_structure_at(THUNK_DATA, iat_addr) +# res = [] +# while iat_entry.Ordinal: +# res.append(IATEntry.create(iat_addr, -1, "??")) +# iat_addr += ctypes.sizeof(type(iat_entry)) +# iat_entry = create_structure_at(THUNK_DATA, iat_addr) +# return res +# +# # Will be usable as `self._IMAGE_EXPORT_DIRECTORY` +# class _IMAGE_EXPORT_DIRECTORY(ctypes.Structure): +# _fields_ = transform_ctypes_fields(IMAGE_EXPORT_DIRECTORY, {"Name": StringRVa, "AddressOfFunctions": RVA, "AddressOfNames": RVA, "AddressOfNameOrdinals": RVA}) +# +# def get_exports(self): +# NameOrdinals = create_structure_at((WORD * self.NumberOfNames), self.AddressOfNameOrdinals.addr) +# NameOrdinals = list(NameOrdinals) +# Functions = create_structure_at((RVA * self.NumberOfFunctions), self.AddressOfFunctions.addr) +# Names = create_structure_at((StringRVa * self.NumberOfNames), self.AddressOfNames.addr) +# res = [] +# for nb, func in enumerate(Functions): +# if nb in NameOrdinals: +# name = Names[NameOrdinals.index(nb)] +# else: +# name = None +# res.append((nb, func, name)) +# return res +# +# current_pe = PEFile() +# +# class IMAGE_DOS_HEADER(ctypes.Structure): +# _fields_ = [ +# ("e_magic", CHAR * 2), +# ("e_cblp", WORD), +# ("e_cp", WORD), +# ("e_crlc", WORD), +# ("e_cparhdr", WORD), +# ("e_minalloc", WORD), +# ("e_maxalloc", WORD), +# ("e_ss", WORD), +# ("e_sp", WORD), +# ("e_csum", WORD), +# ("e_ip", WORD), +# ("e_cs", WORD), +# ("e_lfarlc", WORD), +# ("e_ovno", WORD), +# ("e_res", WORD * 4), +# ("e_oemid", WORD), +# ("e_oeminfo", WORD), +# ("e_res2", WORD * 10), +# ("e_lfanew", DWORD), +# ] +# +# def get_NT_HEADER(self): +# if targetedbitness == 32: +# return create_structure_at(IMAGE_NT_HEADERS32, baseaddr + self.e_lfanew) +# return create_structure_at(IMAGE_NT_HEADERS64, baseaddr + self.e_lfanew) +# return current_pe + + + + +## == PEPARSE V2 == + + +import collections +CtypesStructureTransformers = collections.namedtuple("CtypesStructureTransformers", ["ctypes_structure_transformer", "create_structure_at"]) +
    [docs]def GetPEFile(baseaddr, target=None, force_bitness=None): """Returns a :class:`PEFile` to explore a PE loaded at `baseaddr` in process `target`. @@ -116,319 +462,332 @@ targetedbitness = force_bitness transformers = get_structure_transformer_for_target(target, targetedbitness) - ctypes_structure_transformer, create_structure_at = transformers + #ctypes_structure_transformer, create_structure_at = transformers + transfor_funcs = CtypesStructureTransformers(*transformers) # TODO: rename - if targetedbitness == 32: - IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG32 - else: - IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG64 + return PEFile(target, baseaddr, targetedbitness, transfor_funcs)
    - def get_string(addr): - if target is None: - return ctypes.c_char_p(addr).value - return target.read_string(addr) - class RVA(DWORD): - @property - def addr(self): - return baseaddr + self.value +class THUNK_DATA(ctypes.Union): + _fields_ = [ + ("Ordinal", PVOID), + ("AddressOfData", PVOID) + ] - def __repr__(self): - return "<DWORD {0} (RVA to '{1}')>".format(self.value, hex(self.addr)) +class IMPORT_BY_NAME(ctypes.Structure): + _fields_ = [ + ("Hint", WORD), + ("Name", BYTE) + ] - class StringRVa(RVA): - if target is None: - @property - def str(self): - return get_string(self.addr).decode() - else: - @property - def str(self): - return get_string(self.addr).decode() - def __repr__(self): - return "<DWORD {0} (String RVA to '{1}')>".format(self.value, self.str) +def get_string(target, addr): + if target is None: + return ctypes.c_char_p(addr).value + return target.read_string(addr) - def __int__(self): - return self.value - class IMPORT_BY_NAME(ctypes.Structure): - _fields_ = [ - ("Hint", WORD), - ("Name", BYTE) - ] +class PESection(IMAGE_SECTION_HEADER): - class THUNK_DATA(ctypes.Union): - _fields_ = [ - ("Ordinal", PVOID), - ("AddressOfData", PVOID) - ] + @property + def name(self): + if self.target is None: + return get_string(self.target, ctypes.addressof(self.Name))[:8] + return get_string(self.target, self._base_addr)[:8] - class IATEntry(ctypes.Structure): - """Represent an entry in the IAT of a module - Can be used to get resolved value and setup hook + @property + def start(self): + return self.baseaddr + self.VirtualAddress + + @property + def size(self): + return self.VirtualSize + + def __repr__(self): + return "<PESection \"{0}\">".format(self.name) + + + @classmethod + def create(cls, pefile, addr): + self = pefile.transformers.create_structure_at(cls, addr) + self.baseaddr = pefile.baseaddr + self.target = pefile.target + return self + + +
    [docs]class IATEntry(ctypes.Structure): + """Represent an entry in the IAT of a module + Can be used to get resolved value and setup hook + """ + _fields_ = [ + ("value", PVOID)] + + + + @classmethod + def create(cls, addr, ord, name, target, transformers): + self = transformers.create_structure_at(cls, addr) + self.addr = addr + self.ord = ord + self.name = name + self.hook = None + self.nonhookvalue = self.value + self.target = target + return self + + def __repr__(self): + return '<{0} "{1}" ordinal {2}>'.format(self.__class__.__name__, self.name, self.ord) + +
    [docs] def set_hook(self, callback, types=None): + """Setup a hook on the entry and return it. + You MUST keep a reference to the hook while the hook is enabled. + + :param callback: the hook + + .. note:: + + see :ref:`hook_protocol` + + :rtype: :class:`windows.hooks.IATHook` + + .. warning:: + + This works only for PEFile with the current process as target. """ - _fields_ = [ - ("value", PVOID)] + if self.target is not None: + raise NotImplementedError("Setting hook in remote process (use python code injection)") + + hook = hooks.IATHook(self, callback, types) + self.hook = hook + hook.enable() + return hook
    + +
    [docs] def remove_hook(self): + """Remove the hook on the entry""" + if self.hook is None: + return False + self.hook.disable() + self.hook = None + return True
    - - @classmethod - def create(cls, addr, ord, name): - self = create_structure_at(cls, addr) - self.addr = addr - self.ord = ord - self.name = name - self.hook = None - self.nonhookvalue = self.value - return self - - def __repr__(self): - return '<{0} "{1}" ordinal {2}>'.format(self.__class__.__name__, self.name, self.ord) - - def set_hook(self, callback, types=None): - """Setup a hook on the entry and return it. - You MUST keep a reference to the hook while the hook is enabled. - - :param callback: the hook - - .. note:: - - see :ref:`hook_protocol` - - :rtype: :class:`windows.hooks.IATHook` - - .. warning:: - - This works only for PEFile with the current process as target. - """ - if target is not None: - raise NotImplementedError("Setting hook in remote process (use python code injection)") - - hook = hooks.IATHook(self, callback, types) - self.hook = hook - hook.enable() - return hook - - def remove_hook(self): - """Remove the hook on the entry""" - if self.hook is None: - return False - self.hook.disable() - self.hook = None - return True - - class PEFile(object): - """Represent a PE loaded in a process (current or remote)""" - def __init__(self): - self.baseaddr = baseaddr - self.bitness = targetedbitness - - def get_DOS_HEADER(self): - return create_structure_at(IMAGE_DOS_HEADER, baseaddr) - - def get_NT_HEADER(self): - return self.get_DOS_HEADER().get_NT_HEADER() - - def get_OptionalHeader(self): - return self.get_NT_HEADER().OptionalHeader - - def get_DataDirectory(self): - # This won't work if we load a PE32 in a 64bit process - # PE32 .NET... - #return self.get_OptionalHeader().DataDirectory - DataDirectory_type = IMAGE_DATA_DIRECTORY * IMAGE_NUMBEROF_DIRECTORY_ENTRIES - SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader - if target is None: - opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) +class IMAGE_IMPORT_DESCRIPTOR(IMAGE_IMPORT_DESCRIPTOR): # TODO: use explicite name winstructs.IMAGE_IMPORT_DESCRIPTOR + def get_INT(self): + if not self.OriginalFirstThunk: + return None + int_addr = self.OriginalFirstThunk + self.baseaddr + int_entry = self.transformers.create_structure_at(THUNK_DATA, int_addr) + res = [] + while int_entry.Ordinal: + if int_entry.Ordinal & self.IMAGE_ORDINAL_FLAG: + res += [(int_entry.Ordinal & 0x7fffffff, None)] else: - opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr - DataDirectory_addr = opt_header_addr + SizeOfOptionalHeader - ctypes.sizeof(DataDirectory_type) - return create_structure_at(DataDirectory_type, DataDirectory_addr) + import_by_name = self.transformers.create_structure_at(IMPORT_BY_NAME, self.baseaddr + int_entry.AddressOfData) + name_address = self.baseaddr + int_entry.AddressOfData + type(import_by_name).Name.offset + if self.target is None: + name = get_string(self.target, name_address) + else: + name = get_string(self.target, name_address).decode() + res.append((import_by_name.Hint, name)) + int_addr += ctypes.sizeof(type(int_entry)) + int_entry = self.transformers.create_structure_at(THUNK_DATA, int_addr) + return res + def get_IAT(self): + iat_addr = self.FirstThunk + self.baseaddr + iat_entry = self.transformers.create_structure_at(THUNK_DATA, iat_addr) + res = [] + while iat_entry.Ordinal: + res.append(IATEntry.create(iat_addr, -1, "??", self.target, self.transformers)) + iat_addr += ctypes.sizeof(type(iat_entry)) + iat_entry = self.transformers.create_structure_at(THUNK_DATA, iat_addr) + return res - def get_IMPORT_DESCRIPTORS(self): - import_datadir = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_IMPORT] - if import_datadir.VirtualAddress == 0: - return [] - import_descriptor_addr = RVA(import_datadir.VirtualAddress).addr - current_import_descriptor = create_structure_at(self.IMAGE_IMPORT_DESCRIPTOR, import_descriptor_addr) - res = [] - while current_import_descriptor.FirstThunk: - res.append(current_import_descriptor) - import_descriptor_addr += ctypes.sizeof(self.IMAGE_IMPORT_DESCRIPTOR) - current_import_descriptor = create_structure_at(self.IMAGE_IMPORT_DESCRIPTOR, import_descriptor_addr) - return res + @classmethod + def create(cls, pefile, addr): + self = pefile.transformers.create_structure_at(cls, addr) + self.baseaddr = pefile.baseaddr + self.transformers = pefile.transformers + self.IMAGE_ORDINAL_FLAG = pefile.IMAGE_ORDINAL_FLAG + self.target = pefile.target + return self - def get_EXPORT_DIRECTORY(self): - export_directory_rva = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress - if export_directory_rva == 0: - return None - export_directory_addr = baseaddr + export_directory_rva - return create_structure_at(self._IMAGE_EXPORT_DIRECTORY, export_directory_addr) - - class PESection((IMAGE_SECTION_HEADER)): - if target is None: - @property - def name(self): - return get_string(ctypes.addressof(self.Name))[:8] +class IMAGE_EXPORT_DIRECTORY(IMAGE_EXPORT_DIRECTORY): # TODO: use explicite name winstructs._IMAGE_EXPORT_DIRECTORY + def get_exports(self): + NameOrdinals = self.transformers.create_structure_at((WORD * self.NumberOfNames), self.AddressOfNameOrdinals + self.baseaddr) + NameOrdinals = list(NameOrdinals) + Functions = self.transformers.create_structure_at((DWORD * self.NumberOfFunctions), self.AddressOfFunctions + self.baseaddr) + Names = self.transformers.create_structure_at((DWORD * self.NumberOfNames), self.AddressOfNames + self.baseaddr) + res = [] + for nb, func in enumerate(Functions): + func += self.baseaddr + if nb in NameOrdinals: + name = get_string(self.target, Names[NameOrdinals.index(nb)] + self.baseaddr) else: - @property - def name(self): - return get_string(self._base_addr)[:8] + name = None + res.append((nb, func, name)) + return res - @property - def start(self): - return baseaddr + self.VirtualAddress + @classmethod + def create(cls, pefile, addr): + self = pefile.transformers.create_structure_at(cls, addr) + self.transformers = pefile.transformers + self.target = pefile.target + self.baseaddr = pefile.baseaddr + return self - @property - def size(self): - return self.VirtualSize - def __repr__(self): - return "<PESection \"{0}\">".format(self.name) +class IMAGE_DOS_HEADER(ctypes.Structure): + _fields_ = [ + ("e_magic", CHAR * 2), + ("e_cblp", WORD), + ("e_cp", WORD), + ("e_crlc", WORD), + ("e_cparhdr", WORD), + ("e_minalloc", WORD), + ("e_maxalloc", WORD), + ("e_ss", WORD), + ("e_sp", WORD), + ("e_csum", WORD), + ("e_ip", WORD), + ("e_cs", WORD), + ("e_lfarlc", WORD), + ("e_ovno", WORD), + ("e_res", WORD * 4), + ("e_oemid", WORD), + ("e_oeminfo", WORD), + ("e_res2", WORD * 10), + ("e_lfanew", DWORD), + ] - @utils.fixedpropety - def sections(self): - nt_header = self.get_NT_HEADER() - nb_section = nt_header.FileHeader.NumberOfSections - SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader - if target is None: - opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) - else: - opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr - base_section = opt_header_addr + SizeOfOptionalHeader - sections_array = create_structure_at((self.PESection * nb_section), base_section) - return list(sections_array) +
    [docs]class PEFile(object): + """Represent a PE loaded in a process (current or remote)""" - @utils.fixedpropety - def exports(self): - """The exports of the PE in a dict. Keys are ordinal (:class:`int`) and name (:class:`str`). - The values are the addresses of the exports. + def __init__(self, target, baseaddr, targetedbitness, transformers): + self.target = target + self.baseaddr = baseaddr + self.bitness = targetedbitness + self.transformers = transformers - :type: {(:class:`int` or :class:`str`) : :class:`int`}""" - res = {} - exp_dir = self.get_EXPORT_DIRECTORY() - if exp_dir is None: - return res - raw_exports = exp_dir.get_exports() - for id, rva_addr, rva_name in raw_exports: - res[id] = rva_addr.addr - if rva_name is not None: - res[rva_name.str] = rva_addr.addr + if targetedbitness == 32: + self.IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG32 + else: + self.IMAGE_ORDINAL_FLAG = IMAGE_ORDINAL_FLAG64 + + def get_string(self, addr): + if self.target is None: + return ctypes.c_char_p(addr).value + return self.target.read_string(addr) + + def get_DOS_HEADER(self): + return self.transformers.create_structure_at(IMAGE_DOS_HEADER, self.baseaddr) + + def get_NT_HEADER(self): + offset = self.get_DOS_HEADER().e_lfanew + if self.bitness == 32: + return self.transformers.create_structure_at(IMAGE_NT_HEADERS32, self.baseaddr + offset) + return self.transformers.create_structure_at(IMAGE_NT_HEADERS64, self.baseaddr + offset) + + def get_OptionalHeader(self): + return self.get_NT_HEADER().OptionalHeader + + def get_DataDirectory(self): + # This won't work if we load a PE32 in a 64bit process + # PE32 .NET... + # return self.get_OptionalHeader().DataDirectory + DataDirectory_type = IMAGE_DATA_DIRECTORY * IMAGE_NUMBEROF_DIRECTORY_ENTRIES + SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader + if self.target is None: + opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) + else: + opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr + DataDirectory_addr = opt_header_addr + SizeOfOptionalHeader - ctypes.sizeof(DataDirectory_type) + return self.transformers.create_structure_at(DataDirectory_type, DataDirectory_addr) + + + def get_IMPORT_DESCRIPTORS(self): + import_datadir = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_IMPORT] + if import_datadir.VirtualAddress == 0: + return [] + import_descriptor_addr = self.baseaddr + import_datadir.VirtualAddress + current_import_descriptor = IMAGE_IMPORT_DESCRIPTOR.create(self, import_descriptor_addr) + res = [] + while current_import_descriptor.FirstThunk: + res.append(current_import_descriptor) + import_descriptor_addr += ctypes.sizeof(IMAGE_IMPORT_DESCRIPTOR) + current_import_descriptor = IMAGE_IMPORT_DESCRIPTOR.create(self, import_descriptor_addr) + return res + + def get_EXPORT_DIRECTORY(self): + export_directory_rva = self.get_DataDirectory()[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress + if export_directory_rva == 0: + return None + export_directory_addr = self.baseaddr + export_directory_rva + exp_dir = IMAGE_EXPORT_DIRECTORY.create(self, export_directory_addr) + return exp_dir + + @utils.fixedpropety + def sections(self): + nt_header = self.get_NT_HEADER() + nb_section = nt_header.FileHeader.NumberOfSections + SizeOfOptionalHeader = self.get_NT_HEADER().FileHeader.SizeOfOptionalHeader + if self.target is None: + opt_header_addr = ctypes.addressof(self.get_NT_HEADER().OptionalHeader) + else: + opt_header_addr = self.get_NT_HEADER().OptionalHeader._base_addr + base_section = opt_header_addr + SizeOfOptionalHeader + #pe_section_type = IMAGE_SECTION_HEADER + return [PESection.create(self, base_section + (sizeof(IMAGE_SECTION_HEADER) * i)) for i in range(nb_section)] + #sections_array = self.transformers.create_structure_at((self.PESection * nb_section), base_section) + #return list(sections_array) + + @utils.fixedpropety + def exports(self): + """The exports of the PE in a dict. Keys are ordinal (:class:`int`) and name (:class:`str`). + The values are the addresses of the exports. + + :type: {(:class:`int` or :class:`str`) : :class:`int`}""" + res = {} + exp_dir = self.get_EXPORT_DIRECTORY() + if exp_dir is None: return res + raw_exports = exp_dir.get_exports() + for id, rva_addr, rva_name in raw_exports: + res[id] = rva_addr + if rva_name is not None: + res[rva_name] = rva_addr + return res - @utils.fixedpropety - def export_name(self): - """The Name attribute of the ``EXPORT_DIRECTORY``""" - try: - return self.get_EXPORT_DIRECTORY().Name.str - except AttributeError: - return None + @utils.fixedpropety + def export_name(self): + """The Name attribute of the ``EXPORT_DIRECTORY``""" + exp_dir = self.get_EXPORT_DIRECTORY() + if exp_dir is None: + return None + if not exp_dir.Name: + return None + return get_string(self.target, self.baseaddr + exp_dir.Name) - # TODO: get imports by parsing other modules exports if no INT - @utils.fixedpropety - def imports(self): - """The imports of the PE in a dict. - Keys are the names of DLL to import from and values are :class:`list` - of :class:`IATEntry` + # TODO: get imports by parsing other modules exports if no INT + @utils.fixedpropety + def imports(self): + """The imports of the PE in a dict. + Keys are the names of DLL to import from and values are :class:`list` + of :class:`IATEntry` - :type: {:class:`str` : [:class:`IATEntry`]}""" - res = {} - for import_descriptor in self.get_IMPORT_DESCRIPTORS(): - INT = import_descriptor.get_INT() - IAT = import_descriptor.get_IAT() - if INT is not None: - for iat_entry, (ord, name) in zip(IAT, INT): - # str(name.decode()) -> python2 and python3 compatible for str result - iat_entry.ord = ord - iat_entry.name = str(name.decode()) if name else "" - res.setdefault(import_descriptor.Name.str.lower(), []).extend(IAT) - return res - - # Will be usable as `self.IMAGE_IMPORT_DESCRIPTOR` - class IMAGE_IMPORT_DESCRIPTOR(ctypes.Structure): - _fields_ = transform_ctypes_fields(IMAGE_IMPORT_DESCRIPTOR, {"Name": StringRVa, "OriginalFirstThunk": RVA, "FirstThunk": RVA}) - - def get_INT(self): - if not self.OriginalFirstThunk.value: - return None - int_addr = self.OriginalFirstThunk.addr - int_entry = create_structure_at(THUNK_DATA, int_addr) - res = [] - while int_entry.Ordinal: - if int_entry.Ordinal & IMAGE_ORDINAL_FLAG: - res += [(int_entry.Ordinal & 0x7fffffff, None)] - else: - import_by_name = create_structure_at(IMPORT_BY_NAME, baseaddr + int_entry.AddressOfData) - name_address = baseaddr + int_entry.AddressOfData + type(import_by_name).Name.offset - if target is None: - name = get_string(name_address) - else: - name = get_string(name_address).decode() - res.append((import_by_name.Hint, name)) - int_addr += ctypes.sizeof(type(int_entry)) - int_entry = create_structure_at(THUNK_DATA, int_addr) - return res - - def get_IAT(self): - iat_addr = self.FirstThunk.addr - iat_entry = create_structure_at(THUNK_DATA, iat_addr) - res = [] - while iat_entry.Ordinal: - res.append(IATEntry.create(iat_addr, -1, "??")) - iat_addr += ctypes.sizeof(type(iat_entry)) - iat_entry = create_structure_at(THUNK_DATA, iat_addr) - return res - - # Will be usable as `self._IMAGE_EXPORT_DIRECTORY` - class _IMAGE_EXPORT_DIRECTORY(ctypes.Structure): - _fields_ = transform_ctypes_fields(IMAGE_EXPORT_DIRECTORY, {"Name": StringRVa, "AddressOfFunctions": RVA, "AddressOfNames": RVA, "AddressOfNameOrdinals": RVA}) - - def get_exports(self): - NameOrdinals = create_structure_at((WORD * self.NumberOfNames), self.AddressOfNameOrdinals.addr) - NameOrdinals = list(NameOrdinals) - Functions = create_structure_at((RVA * self.NumberOfFunctions), self.AddressOfFunctions.addr) - Names = create_structure_at((StringRVa * self.NumberOfNames), self.AddressOfNames.addr) - res = [] - for nb, func in enumerate(Functions): - if nb in NameOrdinals: - name = Names[NameOrdinals.index(nb)] - else: - name = None - res.append((nb, func, name)) - return res - - current_pe = PEFile() - - class IMAGE_DOS_HEADER(ctypes.Structure): - _fields_ = [ - ("e_magic", CHAR * 2), - ("e_cblp", WORD), - ("e_cp", WORD), - ("e_crlc", WORD), - ("e_cparhdr", WORD), - ("e_minalloc", WORD), - ("e_maxalloc", WORD), - ("e_ss", WORD), - ("e_sp", WORD), - ("e_csum", WORD), - ("e_ip", WORD), - ("e_cs", WORD), - ("e_lfarlc", WORD), - ("e_ovno", WORD), - ("e_res", WORD * 4), - ("e_oemid", WORD), - ("e_oeminfo", WORD), - ("e_res2", WORD * 10), - ("e_lfanew", DWORD), - ] - - def get_NT_HEADER(self): - if targetedbitness == 32: - return create_structure_at(IMAGE_NT_HEADERS32, baseaddr + self.e_lfanew) - return create_structure_at(IMAGE_NT_HEADERS64, baseaddr + self.e_lfanew) - return current_pe
    + :type: {:class:`str` : [:class:`IATEntry`]}""" + res = {} + for import_descriptor in self.get_IMPORT_DESCRIPTORS(): + INT = import_descriptor.get_INT() + IAT = import_descriptor.get_IAT() + if INT is not None: + for iat_entry, (ord, name) in zip(IAT, INT): + # str(name.decode()) -> python2 and python3 compatible for str result + iat_entry.ord = ord + iat_entry.name = str(name.decode()) if name else "" + name = get_string(self.target, self.baseaddr + import_descriptor.Name) + res.setdefault(name.lower(), []).extend(IAT) + return res @@ -459,13 +818,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/remotectypes.html b/docs/build/html/_modules/windows/remotectypes.html index c5649eb..4fc0bc8 100644 --- a/docs/build/html/_modules/windows/remotectypes.html +++ b/docs/build/html/_modules/windows/remotectypes.html @@ -6,7 +6,7 @@ - windows.remotectypes — PythonForWindows 0.2 documentation + windows.remotectypes — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -125,8 +126,8 @@ class RemoteValue(object): @classmethod - def from_buffer_with_target(cls, buffer, offset=0, target=None): - x = cls.from_buffer(buffer) + def from_buffer_with_target(cls, buffer, offset=0, target=None): + x = cls.from_buffer(buffer) x.target = target return x @@ -155,9 +156,27 @@ @property def value(self): base = self.raw_value - res = [] - for i in itertools.count(): - x = self.target.read_memory(base + (i * 0x100), 0x100) + # Simple case where target in a WinProcess + try: + return self.target.read_wstring(base) + except AttributeError as e: + pass + # Copy of Winprocess.read_wstring if target is a custom object + read_size = 0x100 + readden = 0 + # I am trying to do something smart here.. + while True: + try: + x = self.read_memory(addr + readden, read_size) + except winproxy.Kernel32Error as e: + if read_size == 2: + raise + # handle read_wstring at end of page + # Of read failed: read only the half of size + # read_size must remain a multiple of 2 + read_size = read_size / 2 + continue + readden += read_size utf16_chars = ["".join(c) for c in zip(*[iter(x)] * 2)] if "\x00\x00" in utf16_chars: res.extend(utf16_chars[:utf16_chars.index("\x00\x00")]) @@ -168,8 +187,8 @@ class RemoteStructurePointer(RemotePtr, ctypes.c_void_p): @classmethod - def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): - x = cls.from_buffer(buffer) + def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): + x = cls.from_buffer(buffer) x.target = target x.real_pointer_type = ptr_type return x @@ -180,7 +199,7 @@ return remote_pointed_type(self.raw_value, self.target) def __repr__(self): - return "<RemoteStructurePointer to {0}>".format(self.real_pointer_type._type_.__name__) + return "<RemoteStructurePointer to {0}>".format(self.real_pointer_type._type_.__name__) def create_remote_array(subtype, len): @@ -212,7 +231,7 @@ class RemotePtr64(RemoteValue): def __init__(self, value, target): self.target = target - super(RemotePtr64, self).__init__(value) + super(RemotePtr64, self).__init__(value) @property def raw_value(self): @@ -246,8 +265,8 @@ return self.value @classmethod - def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): - x = cls.from_buffer(buffer) + def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): + x = cls.from_buffer(buffer) x.target = target x.real_pointer_type = ptr_type return x @@ -270,7 +289,7 @@ class RemotePtr32(RemoteValue): def __init__(self, value, target): self.target = target - super(RemotePtr32, self).__init__(value) + super(RemotePtr32, self).__init__(value) @property def raw_value(self): @@ -304,8 +323,8 @@ return self.value @classmethod - def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): - x = cls.from_buffer(buffer) + def from_buffer_with_target_and_ptr_type(cls, buffer, offset=0, target=None, ptr_type=None): + x = cls.from_buffer(buffer) x.target = target x.real_pointer_type = ptr_type return x @@ -376,37 +395,37 @@ # Follow the ctypes usage: if it's not directly inherited from _SimpleCData # We do not apply the .value # Seems weird but it's mandatory AND useful :D (in pe_parse) - if _SimpleCData not in ftype.__bases__: + if _SimpleCData not in ftype.__bases__: return ftype.from_buffer(bytearray(s)) return ftype.from_buffer(bytearray(s)).value def __getattribute__(self, fieldname): if fieldname in type(self)._reserved_name: # Prevent recursion ! - return super(RemoteStructureUnion, self).__getattribute__(fieldname) + return super(RemoteStructureUnion, self).__getattribute__(fieldname) try: t = self._get_field_by_name(fieldname) except AttributeError: # Not a real attribute - return super(RemoteStructureUnion, self).__getattribute__(fieldname) + return super(RemoteStructureUnion, self).__getattribute__(fieldname) descr = self._get_field_descrptor_by_name(fieldname) return self._handle_field_getattr(t, descr.offset, descr.size) @classmethod - def from_structure(cls, structcls): - class MyStruct(cls, structcls): # inherit of structcls to keep property (see winobject.LoadedModule) + def from_structure(cls, structcls): + class MyStruct(cls, structcls): # inherit of structcls to keep property (see winobject.LoadedModule) _fields_ = structcls._fields_ - MyStruct.__name__ = "Remote" + structcls.__name__ + MyStruct.__name__ = "Remote" + structcls.__name__ return MyStruct @classmethod - def from_fields(cls, fields, base_cls=None): - bases = [cls] + def from_fields(cls, fields, base_cls=None): + bases = [cls] if base_cls: bases.append(base_cls) # inherit of structcls to keep property (see winobject.LoadedModule) RemoteStruct = type("RemoteStruct", tuple(bases), {"_fields_": fields}) if base_cls: - RemoteStruct.__name__ = "Remote" + base_cls.__name__ + RemoteStruct.__name__ = "Remote" + base_cls.__name__ return RemoteStruct @@ -430,7 +449,7 @@ return RemoteStructurePointer64.from_buffer_with_target_and_ptr_type(bytearray(self), target=self.target, ptr_type=self).contents def __repr__(self): - return "<RemotePtr64 to struct {0}>".format(type.__name__) + return "<RemotePtr64 to struct {0}>".format(type.__name__) return PointerToStruct64 def transform_structure_to_remote64bits(structcls): @@ -474,7 +493,7 @@ return RemoteStructurePointer32.from_buffer_with_target_and_ptr_type(bytearray(self), target=self.target, ptr_type=self).contents def __repr__(self): - return "<RemotePtr32 to struct {0}>".format(type.__name__) + return "<RemotePtr32 to struct {0}>".format(type.__name__) return PointerToStruct32 @@ -542,13 +561,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/syswow64.html b/docs/build/html/_modules/windows/syswow64.html index b108e1b..665d0c6 100644 --- a/docs/build/html/_modules/windows/syswow64.html +++ b/docs/build/html/_modules/windows/syswow64.html @@ -6,7 +6,7 @@ - windows.syswow64 — PythonForWindows 0.2 documentation + windows.syswow64 — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -93,7 +94,7 @@
    [docs]def generate_syswow64_call(target): nb_args = len(target.prototype._argtypes_) - target_addr = get_syswow_ntdll_exports()[target.__name__] + target_addr = get_syswow_ntdll_exports()[target.__name__] argument_buffer_len = (nb_args * 8) argument_buffer = windows.current_process.allocator.reserve_size(argument_buffer_len) alignement_information = windows.current_process.allocator.reserve_size(8) @@ -169,7 +170,7 @@ expected_arguments_number = len(target.prototype._argtypes_) def wrapper(*args): if len(args) != expected_arguments_number: - raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args))) + raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args))) # Transform args (ctypes byref possibly) to int writable_args = [] for i, value in enumerate(args): @@ -177,14 +178,14 @@ try: value = ctypes.cast(value, ctypes.c_void_p).value except ctypes.ArgumentError as e: - raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__)) + raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__)) writable_args.append(value) # Build buffer buffer = struct.pack("<" + "Q" * len(writable_args), *writable_args) ctypes.memmove(argument_buffer, buffer, len(buffer)) return native_caller() - wrapper.__name__ = "{0}<syswow64>".format(target.__name__,) - wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number) + wrapper.__name__ = "{0}<syswow64>".format(target.__name__,) + wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number) return wrapper
    @@ -259,7 +260,7 @@ try: self.raw_call = generate_syswow64_call(self.winproxy_function) except KeyError: - raise windows.winproxy.ExportNotFound(self.winproxy_function.__name__, "SysWow[ntdll64]") + raise windows.winproxy.ExportNotFound(self.winproxy_function.__name__, "SysWow[ntdll64]") def perform_call(*args): @@ -270,7 +271,7 @@ raise ValueError("I do not have all parameters: how is that possible ?") for param_name, param_value in zip(self.params_name, args): if param_value is NeededParameter: - raise TypeError("{0}: Missing Mandatory parameter <{1}>".format(self.winproxy_function.__name__, param_name)) + raise TypeError("{0}: Missing Mandatory parameter <{1}>".format(self.winproxy_function.__name__, param_name)) if self.raw_call is None: force_resolution() @@ -373,13 +374,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/utils/winutils.html b/docs/build/html/_modules/windows/utils/winutils.html index 051317d..1f053d8 100644 --- a/docs/build/html/_modules/windows/utils/winutils.html +++ b/docs/build/html/_modules/windows/utils/winutils.html @@ -6,7 +6,7 @@ - windows.utils.winutils — PythonForWindows 0.2 documentation + windows.utils.winutils — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -55,6 +56,7 @@ import datetime import windows +from windows.dbgprint import dbgprint from .. import winproxy from ..generated_def import windef from ..generated_def.winstructs import * @@ -133,6 +135,10 @@ if args: lpCommandLine = (" ".join([str(a) for a in args])) windows.winproxy.CreateProcessA(path, lpCommandLine=lpCommandLine, dwCreationFlags=dwCreationFlags, lpProcessInformation=ctypes.byref(proc_info), lpStartupInfo=lpStartupInfo) + dbgprint("CreateProcessA new process handle {:#x}".format(proc_info.hProcess), "HANDLE") + dbgprint("CreateProcessA new thread handle {:#x}".format(proc_info.hThread), "HANDLE") + dbgprint("Automatic close of thread handle {:#x}".format(proc_info.hThread), "HANDLE") + windows.winproxy.CloseHandle(proc_info.hThread) # Give access to a WinThread in addition of the WinProcess ? return windows.winobject.process.WinProcess(pid=proc_info.dwProcessId, handle=proc_info.hProcess) @@ -267,6 +273,14 @@ # addr = windows.winproxy.MapViewOfFile(h, dwDesiredAccess=FILE_MAP_READ, dwNumberOfBytesToMap=1) # return addr +def decompress_buffer(comptype, buffer, uncompress_size=None): + if uncompress_size is None: + uncompress_size = len(buffer) * 10 + result_size = DWORD() + uncompressed = ctypes.c_buffer(uncompress_size) + windows.winproxy.RtlDecompressBuffer(comptype, uncompressed, uncompress_size, buffer, len(buffer), result_size) + return uncompressed[:result_size.value] +
    [docs]class VirtualProtected(object): """ A context manager usable like `VirtualProtect` that will restore the old protection at exit :: @@ -342,13 +356,13 @@
  • modules |
  • - - + +
    \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/exception.html b/docs/build/html/_modules/windows/winobject/exception.html index 697d2c9..c9fe6a4 100644 --- a/docs/build/html/_modules/windows/winobject/exception.html +++ b/docs/build/html/_modules/windows/winobject/exception.html @@ -6,7 +6,7 @@ - windows.winobject.exception — PythonForWindows 0.2 documentation + windows.winobject.exception — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -190,8 +191,8 @@ def __hex__(self): if self.raw == 0: - return "{0}({1})".format(type(self).__name__, hex(self.raw)) - return "{0}({1}:{2})".format(type(self).__name__, hex(self.raw), self.dump()) + return "{0}({1})".format(type(self).__name__, hex(self.raw)) + return "{0}({1}:{2})".format(type(self).__name__, hex(self.raw), self.dump()) raw = property(get_raw, set_raw) """Raw value of the eflags @@ -329,12 +330,12 @@ """The fields of the structure""" @classmethod -
    [docs] def new_aligned(cls): +
    [docs] def new_aligned(cls): """Return a new :class:`ECONTEXT64` aligned on 16 bits temporary workaround or horrible hack ? choose your side """ - size = ctypes.sizeof(cls) + size = ctypes.sizeof(cls) nb_qword = (size + 8) / ctypes.sizeof(ULONGLONG) buffer = (nb_qword * ULONGLONG)() struct_address = ctypes.addressof(buffer) @@ -342,7 +343,7 @@ raise ValueError("ULONGLONG array not aligned on 8") if (struct_address & 0xf) == 8: struct_address += 8 - self = cls.from_address(struct_address) + self = cls.from_address(struct_address) # Keep the raw buffer alive self._buffer = buffer return self
    @@ -379,8 +380,8 @@ """A decorator that create a callable which can be passed to :func:`AddVectoredExceptionHandler`""" func_type = ctypes.WINFUNCTYPE(ctypes.c_uint, ctypes.POINTER(EEXCEPTION_POINTERS)) - def __new__(cls, func): - self = object.__new__(cls) + def __new__(cls, func): + self = object.__new__(cls) self.func = func v = self.func_type(self.decorator) v.self = self @@ -412,7 +413,7 @@ class DumpContextOnException(VectoredExceptionHandler): def __init__(self, exit=False): self.exit = exit - super(DumpContextOnException, self).__init__(self.print_context_result) + super(DumpContextOnException, self).__init__(self.print_context_result) def print_context_result(self, exception_pointers): except_record = exception_pointers[0].ExceptionRecord[0] @@ -452,13 +453,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/handle.html b/docs/build/html/_modules/windows/winobject/handle.html index cecf5b9..466b683 100644 --- a/docs/build/html/_modules/windows/winobject/handle.html +++ b/docs/build/html/_modules/windows/winobject/handle.html @@ -6,7 +6,7 @@ - windows.winobject.handle — PythonForWindows 0.2 documentation + windows.winobject.handle — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -83,11 +84,15 @@ :type: :class:`str`""" return self._get_object_type() + @property + def infos(self): + """TODO: DOC""" + return self._get_object_basic_infos() + def _get_object_name(self): lh = self.local_handle size_needed = DWORD() yyy = ctypes.c_buffer(0x1000) - size_needed = DWORD() winproxy.NtQueryObject(lh, ObjectNameInformation, ctypes.byref(yyy), ctypes.sizeof(yyy), ctypes.byref(size_needed)) return WinUnicodeString.from_buffer_copy(yyy[:size_needed.value]).str @@ -97,13 +102,25 @@ size_needed = DWORD() try: winproxy.NtQueryObject(lh, ObjectTypeInformation, ctypes.byref(xxx), ctypes.sizeof(xxx), ctypes.byref(size_needed)) - except Exception as e: + except WindowsError as e: + if e.code != STATUS_INFO_LENGTH_MISMATCH: + print("ERROR WITH {0:x}".format(lh)) + raise size = size_needed.value buffer = ctypes.c_buffer(size) winproxy.NtQueryObject(lh, ObjectTypeInformation, buffer, size, ctypes.byref(size_needed)) xxx = EPUBLIC_OBJECT_TYPE_INFORMATION.from_buffer_copy(buffer) return xxx.TypeName.str + def _get_object_basic_infos(self): + pass + lh = self.local_handle + size_needed = DWORD() + basic_infos = PUBLIC_OBJECT_BASIC_INFORMATION() + winproxy.NtQueryObject(lh, ObjectBasicInformation, ctypes.byref(basic_infos), ctypes.sizeof(basic_infos), ctypes.byref(size_needed)) + return basic_infos + #PUBLIC_OBJECT_BASIC_INFORMATION + @windows.utils.fixedpropety def local_handle(self): """A local copy of the handle, acquired with ``DuplicateHandle`` @@ -116,7 +133,7 @@ return res.value def __repr__(self): - return "<{0} value=<0x{1:x}> in process pid={2}>".format(type(self).__name__, self.wValue, self.dwProcessId) + return "<{0} value=<0x{1:x}> in process pid={2}>".format(type(self).__name__, self.wValue, self.dwProcessId) def __del__(self): if self.dwProcessId == windows.current_process.pid: @@ -176,13 +193,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/network.html b/docs/build/html/_modules/windows/winobject/network.html index a35c60b..86d0944 100644 --- a/docs/build/html/_modules/windows/winobject/network.html +++ b/docs/build/html/_modules/windows/winobject/network.html @@ -6,7 +6,7 @@ - windows.winobject.network — PythonForWindows 0.2 documentation + windows.winobject.network — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -443,7 +444,7 @@ return icmp_type_and_code.value def __repr__(self): - return '<{0} "{1}">'.format(type(self).__name__, self.name) + return '<{0} "{1}">'.format(type(self).__name__, self.name)
    [docs]class Network(object): NetFwPolicy2 = windows.com.IID.from_string("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD") @@ -524,13 +525,13 @@
  • modules |
  • - - + +
    \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/process.html b/docs/build/html/_modules/windows/winobject/process.html index 9c4c7f3..9eaf5dc 100644 --- a/docs/build/html/_modules/windows/winobject/process.html +++ b/docs/build/html/_modules/windows/winobject/process.html @@ -6,7 +6,7 @@ - windows.winobject.process — PythonForWindows 0.2 documentation + windows.winobject.process — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -82,7 +83,7 @@ # Big bypass to prevent missing reference at programm close.. _close_function = ctypes.WinDLL("kernel32").CloseHandle def _get_handle(self): - raise NotImplementedError("{0} is abstract".format(type(self).__name__)) + raise NotImplementedError("{0} is abstract".format(type(self).__name__)) @property def handle(self): @@ -97,6 +98,9 @@ return self._handle self._handle = self._get_handle() dbgprint("Open handle {0} for {1}".format(hex(self._handle), self), "HANDLE") + #if "DEAD" in str(self): + # print("OPEN FOR THE DEADS") + # import pdb;pdb.set_trace() return self._handle def wait(self, timeout=INFINITE): @@ -105,7 +109,8 @@ def __del__(self): if hasattr(self, "_handle") and self._handle: - #dbgprint("Closing Handle {0} for {1}".format(hex(self._handle), self), "HANDLE") + # Prevent some bug where dbgprint might be None when __del__ is called in a closing process + dbgprint("Closing Handle {0} for {1}".format(hex(self._handle), self), "HANDLE") if dbgprint is not None else None self._close_function(self._handle) @@ -273,7 +278,7 @@ owner_name = "<Dead process with pid {0}>".format(hex(self.th32OwnerProcessID)) else: owner_name = owner.name - return '<{0} {1} owner "{2}" at {3}>'.format(self.__class__.__name__, self.tid, owner_name, hex(id(self))) + return '<{0} {1} owner "{2}" at {3}>'.format(self.__class__.__name__, self.tid, owner_name, hex(id(self))) @staticmethod def _from_handle(handle): @@ -308,6 +313,17 @@ _get_thread_id = _get_thread_id_manual + + # def token(self): + # """The token of the process + # + # :type: :class:`Token` + # """ + # token_handle = HANDLE() + # winproxy.OpenThreadToken(self.handle, TOKEN_QUERY, False, byref(token_handle)) + # return Token(token_handle.value) + +
    [docs]class DeadThread(AutoHandle): """An already dead thread (returned only by API returning a new thread if thread die before being returned)""" def __init__(self, handle, tid=None): @@ -587,8 +603,20 @@ def read_string(self, addr): """Read an ascii string at ``addr``""" res = [] + read_size = 0x100 + readden = 0 for i in itertools.count(): - x = self.read_memory(addr + (i * 0x100), 0x100) + try: + x = self.read_memory(addr + readden, read_size) + except winproxy.Kernel32Error as e: + if read_size == 2: + raise + # handle read_wstring at end of page + # Of read failed: read only the half of size + # read_size must remain a multiple of 2 + read_size = read_size / 2 + continue + readden += read_size if "\x00" in x: res.append(x.split("\x00", 1)[0]) break @@ -598,8 +626,21 @@ def read_wstring(self, addr): """Read a windows UTF16 string at ``addr``""" res = [] - for i in itertools.count(): - x = self.read_memory(addr + (i * 0x100), 0x100) + read_size = 0x100 + readden = 0 + # I am trying to do something smart here.. + while True: + try: + x = self.read_memory(addr + readden, read_size) + except winproxy.Kernel32Error as e: + if read_size == 2: + raise + # handle read_wstring at end of page + # Of read failed: read only the half of size + # read_size must remain a multiple of 2 + read_size = read_size / 2 + continue + readden += read_size utf16_chars = ["".join(c) for c in zip(*[iter(x)] * 2)] if "\x00\x00" in utf16_chars: res.extend(utf16_chars[:utf16_chars.index("\x00\x00")]) @@ -641,16 +682,25 @@ return TimeInfo(creation, exit, kernel, user) - @utils.fixedpropety - def token(self): - """The token of the process - :type: :class:`Token` - """ + def open_token(self, flags=TOKEN_QUERY): token_handle = HANDLE() - winproxy.OpenProcessToken(self.handle, TOKEN_QUERY, byref(token_handle)) + winproxy.OpenProcessToken(self.handle, flags, byref(token_handle)) return Token(token_handle.value) + + token = property(open_token) + + # @utils.fixedpropety + # def token(self): + # """The token of the process + # + # :type: :class:`Token` + # """ + # token_handle = HANDLE() + # winproxy.OpenProcessToken(self.handle, TOKEN_QUERY, byref(token_handle)) + # return Token(token_handle.value) +
    [docs]class CurrentThread(AutoHandle): """The current thread""" @property #It's not a fixedpropety because executing thread might change @@ -683,6 +733,10 @@ """Raise :class:`ValueError` to prevent deadlock :D""" raise ValueError("wait() on current thread")
    + #def token(self): + + # GetCurrentThreadToken() +
    [docs]class CurrentProcess(Process): """The current process""" @@ -834,7 +888,7 @@ return WinProcess(handle=handle) @classmethod - def _from_PROCESSENTRY32(cls, entry): + def _from_PROCESSENTRY32(cls, entry): #print("_from_PROCESSENTRY32") name = entry.szExeFile.decode() pid = entry.th32ProcessID @@ -877,10 +931,10 @@ def __repr__(self): try: if self.is_exit: - return '<{0} "{1}" pid {2} (DEAD) at {3}>'.format(self.__class__.__name__, self.name, self.pid, hex(id(self))) + return '<{0} "{1}" pid {2} (DEAD) at {3}>'.format(self.__class__.__name__, self.name, self.pid, hex(id(self))) except WindowsError: # Cannot open process pass - return '<{0} "{1}" pid {2} at {3}>'.format(self.__class__.__name__, self.name, self.pid, hex(id(self))) + return '<{0} "{1}" pid {2} at {3}>'.format(self.__class__.__name__, self.name, self.pid, hex(id(self)))
    [docs] def virtual_alloc(self, size, prot=PAGE_EXECUTE_READWRITE): """Allocate memory in the process @@ -1063,17 +1117,16 @@ @property def integrity(self): - """Return the integrity level of a process + """Return the integrity level of a token :type: :class:`int` """ buffer_size = self.get_required_information_size(TokenIntegrityLevel) buffer = ctypes.c_buffer(buffer_size) self.get_informations(TokenIntegrityLevel, buffer) - sid = ctypes.cast(buffer, POINTER(TOKEN_MANDATORY_LABEL))[0].Label.Sid count = winproxy.GetSidSubAuthorityCount(sid) - integrity = winproxy.GetSidSubAuthority(sid, ord(count[0]) - 1)[0] + integrity = winproxy.GetSidSubAuthority(sid, count[0] - 1)[0] return know_integrity_level_mapper.get(integrity, integrity) @property @@ -1120,9 +1173,14 @@ cbsize = DWORD() try: winproxy.GetTokenInformation(self.handle, info_type, None, 0, ctypes.byref(cbsize)) - except WindowsError: - pass - return cbsize.value
    + except WindowsError as e: + if not e.winerror == ERROR_INSUFFICIENT_BUFFER: + raise + return cbsize.value + + #TODO: TEST + DOC + def set_informations(self, info_type, infos): + return winproxy.SetTokenInformation(self.handle, info_type, ctypes.byref(infos), ctypes.sizeof(infos))
    def transform_ctypes_fields(struct, replacement): @@ -1150,7 +1208,7 @@ return (ctypes.c_wchar * size).from_address(self.Buffer)[:] def __repr__(self): - return """<{0} "{1}" at {2}>""".format(type(self).__name__, self.str, hex(id(self))) + return """<{0} "{1}" at {2}>""".format(type(self).__name__, self.str, hex(id(self)))
    [docs]class LoadedModule(Structure): @@ -1181,7 +1239,7 @@ return self.FullDllName.str.lower() def __repr__(self): - return '<{0} "{1}" at {2}>'.format(self.__class__.__name__, self.name, hex(id(self))) + return '<{0} "{1}" at {2}>'.format(self.__class__.__name__, self.name, hex(id(self))) @property def pe(self): @@ -1433,13 +1491,13 @@
  • modules |
  • - - + +
    \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/registry.html b/docs/build/html/_modules/windows/winobject/registry.html index 865fd07..4680ce2 100644 --- a/docs/build/html/_modules/windows/winobject/registry.html +++ b/docs/build/html/_modules/windows/winobject/registry.html @@ -6,7 +6,7 @@ - windows.winobject.registry — PythonForWindows 0.2 documentation + windows.winobject.registry — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -92,7 +93,7 @@ try: self._phkey = _winreg.OpenKeyEx(self.surkey.phkey, self.name, 0, self.sam) except WindowsError as e: - raise WindowsError("Could not open registry key <{0}>".format(self.fullname)) + raise WindowsError(e.winerror, "Could not open registry key <{0}> ({1})".format(self.fullname, e.strerror)) return self._phkey @@ -180,9 +181,9 @@ value, rtype = value return self.set(name, value, rtype) - __getitem__ = get + __getitem__ = get - __call__ = open_subkey + __call__ = open_subkey class DummyPHKEY(object): @@ -214,8 +215,8 @@ def __call__(self, name, sam=KEY_READ): """Get a registry key:: - registry[r"HKEY_LOCAL_MACHINE\\Software"] - registry["HKEY_LOCAL_MACHINE"]["Software"] + registry(r"HKEY_LOCAL_MACHINE\\Software") + registry("HKEY_LOCAL_MACHINE")("Software") :rtype: :class:`PyHKey` """ @@ -261,13 +262,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/service.html b/docs/build/html/_modules/windows/winobject/service.html index b22f8cc..6ad9ff8 100644 --- a/docs/build/html/_modules/windows/winobject/service.html +++ b/docs/build/html/_modules/windows/winobject/service.html @@ -6,7 +6,7 @@ - windows.winobject.service — PythonForWindows 0.2 documentation + windows.winobject.service — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -91,7 +92,7 @@ class Service(object): def __repr__(self): - return '<{0} "{1}">'.format(type(self).__name__, self.name) + return '<{0} "{1}">'.format(type(self).__name__, self.name) @utils.fixedpropety def name(self): @@ -154,7 +155,7 @@ while True: size = size_needed.value - buffer = (ctypes.c_byte * size)() + buffer = (BYTE * size)() try: windows.winproxy.EnumServicesStatusExA(scmanager, SC_ENUM_PROCESS_INFO, SERVICE_TYPE_ALL, SERVICE_ACTIVE, buffer, size, ctypes.byref(size_needed), ctypes.byref(nb_services), byref(counter), None) @@ -193,13 +194,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/system.html b/docs/build/html/_modules/windows/winobject/system.html index eaa4e93..8147793 100644 --- a/docs/build/html/_modules/windows/winobject/system.html +++ b/docs/build/html/_modules/windows/winobject/system.html @@ -6,7 +6,7 @@ - windows.winobject.system — PythonForWindows 0.2 documentation + windows.winobject.system — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -129,7 +130,7 @@ @utils.fixedpropety def wmi(self): - r"""An object to perform wmi request to "root\\cimv2" + r"""An object to perform wmi request to "root\\cimv2" :type: :class:`windows.winobject.wmi.WmiRequester`""" return wmi.WmiRequester() @@ -302,13 +303,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/volume.html b/docs/build/html/_modules/windows/winobject/volume.html index 61dc34e..d477af5 100644 --- a/docs/build/html/_modules/windows/winobject/volume.html +++ b/docs/build/html/_modules/windows/winobject/volume.html @@ -6,7 +6,7 @@ - windows.winobject.volume — PythonForWindows 0.2 documentation + windows.winobject.volume — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -92,7 +93,7 @@ def __repr__(self): - return """<{0} "{1}" ({2})>""".format(type(self).__name__, self.name, self.type.name) + return """<{0} "{1}" ({2})>""".format(type(self).__name__, self.name, self.type.name) @@ -148,13 +149,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_modules/windows/winobject/wmi.html b/docs/build/html/_modules/windows/winobject/wmi.html index dadf691..5e57f6a 100644 --- a/docs/build/html/_modules/windows/winobject/wmi.html +++ b/docs/build/html/_modules/windows/winobject/wmi.html @@ -6,7 +6,7 @@ - windows.winobject.wmi — PythonForWindows 0.2 documentation + windows.winobject.wmi — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -60,14 +61,14 @@
    [docs]class WmiRequester(object): - r"""An object to perform wmi request to ``root\cimv2``""" + r"""An object to perform wmi request to ``root\cimv2``""" INSTANCE = None - def __new__(cls, *args, **kwargs): - if cls.INSTANCE is not None: - return cls.INSTANCE - cls.INSTANCE = super(cls, cls).__new__(cls, *args, **kwargs) - return cls.INSTANCE + def __new__(cls, *args, **kwargs): + if cls.INSTANCE is not None: + return cls.INSTANCE + cls.INSTANCE = super(cls, cls).__new__(cls, *args, **kwargs) + return cls.INSTANCE def __init__(self, target="root\\cimv2", user=None, password=None): locator = IWbemLocator() @@ -166,13 +167,13 @@
  • modules |
  • - - + +
    \ No newline at end of file diff --git a/docs/build/html/_modules/windows/wintrust.html b/docs/build/html/_modules/windows/wintrust.html index d9d0636..22e0ff5 100644 --- a/docs/build/html/_modules/windows/wintrust.html +++ b/docs/build/html/_modules/windows/wintrust.html @@ -6,7 +6,7 @@ - windows.wintrust — PythonForWindows 0.2 documentation + windows.wintrust — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -174,6 +175,7 @@ while t is not None: t = winproxy.CryptCATAdminEnumCatalogFromHash(ctx, hash, len(hash), 0, ctypes.byref(HCATINFO(t))) + # Todo: how to handle multiple catalog ? winproxy.CryptCATAdminReleaseCatalogContext(ctx, t, 0) winproxy.CryptCATAdminReleaseContext(ctx, 0) return tname @@ -194,6 +196,7 @@ # The volume for a file has been externally altered so that the opened file is no longer valid. # (returned for empty file) return None + raise return buffer @@ -273,13 +276,13 @@
  • modules |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/_sources/com.rst.txt b/docs/build/html/_sources/com.rst.txt new file mode 100644 index 0000000..d8d6288 --- /dev/null +++ b/docs/build/html/_sources/com.rst.txt @@ -0,0 +1,44 @@ +:mod:`windows.com` - Component Object Model +"""""""""""""""""""""""""""""""""""""""""""" + +.. module:: windows.com + +A module to call `COM` interfaces from `Python` or +`COM` vtable in python. + +This code is only used in :mod:`windows.winobject.wmi` and :mod:`windows.winobject.network` for the firewall. +The ability to create `COM` vtable is used in the `LKD project `_ . + + +Using a COM interface +''''''''''''''''''''' + +It's possible to directly call `COM` interface from python. All you need is the definition of the `COM` interface. + +There are three ways to get the definition of the code interface: + + * By using it from :mod:`windows.generated_def.interfaces` + * By writing it yourself : `_ + * By generating it. + +To generate a `COM` interface you need its definition from the ".c" file. +Then add thisit to ``PythonForWindows\ctypes_generation\com\MyInterface.txt``. +Finally re-generate the interface using ``generate.py``. + +When you have the `COM` interface defintion you can create an instance of it. +Then you need to retrieve the interface by using an API returning an object or :func:`window.com.create_instance`. +You can then use the instance to call whatever method you need. + +.. note:: + + see sample :ref:`sample_com_firewall` + +Implementing a COM interface +'''''''''''''''''''''''''''' + +To create `COM` object you need to: + + 1. Create your ``COMImplementation`` with an ``IMPLEMENT`` attribute that should be a cominterface `CODE 1 `_ + 2. Implements the methods of the interface `CODE 2 `_ + 3. Create an instance `CODE3 `_ + 4. Pass it to whatever native function expects it `CODE4 `_ \ No newline at end of file diff --git a/docs/build/html/_sources/crypto.rst.txt b/docs/build/html/_sources/crypto.rst.txt new file mode 100644 index 0000000..cbd2640 --- /dev/null +++ b/docs/build/html/_sources/crypto.rst.txt @@ -0,0 +1,101 @@ +``windows.crypto`` -- CryptoAPI +******************************* + +.. module:: windows.crypto + +The :mod:`windows.crypto` module offers some wrappers arround the CryptoAPI_. + +The main goal of this module (for now) is providing simple encryption/decryption methods. + +Encryption +"""""""""" + +.. note:: + + See sample :ref:`sample_crypto_encryption` + +encrypt +''''''' + +.. autofunction:: encrypt + +decrypt +''''''' + +.. autofunction:: decrypt + +import_pfx +'''''''''' + +.. autofunction:: import_pfx + + +Certificate +""""""""""" + +.. note:: + + See sample :ref:`sample_crypto_certificate` + +CertificateContext +'''''''''''''''''' + +.. autoclass:: CertificateContext + + +EHCERTSTORE +''''''''''' + +.. autoclass:: EHCERTSTORE + + +CryptObject +''''''''''' + +.. autoclass:: CryptObject + + .. warning:: + + The methods and property of this class will problably change as I haven't yet had the time + to try it out in real cases. + + +CryptContext +'''''''''''' + +.. autoclass:: CryptContext + + +Generating componants +""""""""""""""""""""" + +.. module:: windows.crypto.generation + +This module is used to generate selfsigned-certificates / keypair and pfx file. + +.. note:: + + See ``genkeys()`` in the sample :ref:`sample_crypto_encryption` + + +generate_selfsigned_certificate +''''''''''''''''''''''''''''''' + +.. autofunction:: generate_selfsigned_certificate + + +generate_key +'''''''''''' + +.. autofunction:: generate_key + + +generate_pfx +'''''''''''' + +.. autofunction:: generate_pfx + + + + +.. _CryptoAPI: https://msdn.microsoft.com/en-us/library/windows/desktop/aa380252(v=vs.85).aspx \ No newline at end of file diff --git a/docs/build/html/_sources/debug.rst.txt b/docs/build/html/_sources/debug.rst.txt new file mode 100644 index 0000000..4c5c05a --- /dev/null +++ b/docs/build/html/_sources/debug.rst.txt @@ -0,0 +1,88 @@ +:mod:`windows.debug` -- Debugging +================================= + +.. module:: windows.debug + +.. note:: + + See sample :ref:`sample_debugger` + +:class:`Debugger` +""""""""""""""""" + +The :class:`Debugger` is the base class to perform the debugging of a remote process. +The :class:`Debugger` have some functions called on given event that can be implemented by subclasses. + +All Memory-breakpoint are disabled when callind a public callback or a breakpoint ``trigger()`` function. + +This means that those methods see the original ``current_process`` memory access rights. + +.. autoclass:: Debugger + :members: + :member-order: bysource + + .. automethod:: __init__ + + + +:class:`LocalDebugger` +"""""""""""""""""""""" + +.. note:: + + See sample :ref:`sample_local_debugger` + +The :class:`Debugger` is the base class to perform the debugging the current process. +It is based on :func:`VectoredException` (see :ref:`sample_vectoredexception`) + +There is not much documentation for now as the code might change soon. + + + +.. autoclass:: LocalDebugger + :members: + + + +:class:`Breakpoint` +""""""""""""""""""" + +Standard breakpoints types expect an address as argument. + +An address can be: + + * An :class:`int` + * A :class:`str` of form (breakpoint will be put when ``DLL`` is loaded): + + * ``"DLL!ApiName"`` + * ``"DLL!Offset"`` where offset is a int ("16", "0x10", ..) + + +When a breakpoint is hit, its ``trigger`` function is called with the debugger and a +``DEBUG_EXECEPTION_EVENT`` structure as argument. + + +.. autoclass:: Breakpoint + :members: + +.. autoclass:: HXBreakpoint + :members: + :inherited-members: + +.. autoclass:: MemoryBreakpoint + :members: + :inherited-members: + :special-members: __init__ + + + +.. note:: + + MemoryBreakpoint are triggered based on the fault address only (as I don't know a way to get the size of the read/write causing the fault without embedding a disassembler). + + This means that a MEMBP at address ``X`` won't be triggered by a write of size 4 at address ``X - 1``. it's sad I know. + +.. autoclass:: FunctionBP + :members: + :inherited-members: + :special-members: __init__ \ No newline at end of file diff --git a/docs/build/html/_sources/exception.rst.txt b/docs/build/html/_sources/exception.rst.txt new file mode 100644 index 0000000..d0e9ac9 --- /dev/null +++ b/docs/build/html/_sources/exception.rst.txt @@ -0,0 +1,99 @@ +Exception and Context related structures +======================================== + +.. module:: windows.winobject.exception + + +This module regroups all the Exception/Context related structures and functions. +Most of the structures are the Windows structure with a prefix ``E`` (For enhanced) + +Those structure have the same fields that the normal windows ones but their types might vary for a simpler use. + + +This module also define the decorator :func:`VectoredException` which allows to play with ``Vectored Exception Handler`` in Python + +.. note:: + + See sample :ref:`sample_vectoredexception` samples + +Exception Records +''''''''''''''''' + +.. autoclass:: EEXCEPTION_RECORD + :members: + :inherited-members: + +.. autoclass:: EEXCEPTION_RECORD32 + :inherited-members: + +.. autoclass:: EEXCEPTION_RECORD64 + :members: + :inherited-members: + +EXCEPTION DEBUG INFO +'''''''''''''''''''' + +.. autoclass:: EEXCEPTION_DEBUG_INFO32 + :members: + :inherited-members: + + .. data:: ExceptionRecord + + :type: :class:`EEXCEPTION_RECORD32` + + +.. autoclass:: EEXCEPTION_DEBUG_INFO64 + :members: + :inherited-members: + + .. data:: ExceptionRecord + + :type: :class:`EEXCEPTION_RECORD64` + +Context +''''''' + +.. autoclass:: ECONTEXT32 + :members: + :inherited-members: + +.. autoclass:: ECONTEXTWOW64 + :members: + :inherited-members: + +.. autoclass:: ECONTEXT64 + :members: + :inherited-members: + +.. autoclass:: EEflags + :members: + +.. autoclass:: EDr7 + :members: + +EXCEPTION POINTERS +'''''''''''''''''' + +.. autoclass:: EEXCEPTION_POINTERS + :members: + + .. data:: ExceptionRecord + + :type: POINTER to :class:`EEXCEPTION_RECORD` + + .. data:: ContextRecord + + :type: POINTER to :class:`ECONTEXT32` or :class:`ECONTEXT64` + + +.. _vectoredexception: + +Vectored Exception +'''''''''''''''''' + +.. note:: + + See sample :ref:`sample_vectoredexception` + +.. autoclass:: VectoredException + :members: \ No newline at end of file diff --git a/docs/build/html/_sources/handle.rst.txt b/docs/build/html/_sources/handle.rst.txt new file mode 100644 index 0000000..1497638 --- /dev/null +++ b/docs/build/html/_sources/handle.rst.txt @@ -0,0 +1,10 @@ +Handle -- Processes handles +============================ + +.. note:: + + See sample :ref:`sample_system` + +.. module:: windows.winobject.handle + +.. autoclass:: Handle \ No newline at end of file diff --git a/docs/build/html/_sources/iat_hook.rst.txt b/docs/build/html/_sources/iat_hook.rst.txt new file mode 100644 index 0000000..2f98d42 --- /dev/null +++ b/docs/build/html/_sources/iat_hook.rst.txt @@ -0,0 +1,113 @@ +IAT hooking +""""""""""" + +.. note:: + + See sample :ref:`sample_iat_hook` + +Putting an IAT hook +''''''''''''''''''' + +To setup your IAT hook you just need: + + * A callback that respect the :ref:`hook_protocol` + * The :class:`windows.pe_parse.IATEntry` to hook + + +You just need to use the function :func:`windows.pe_parse.IATEntry.set_hook` + +Putting a hook:: + + import windows + from windows.hooks import * + + @CreateFileACallback + def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function): + print("Trying to open {0}".format(lpFileName)) + if "secret" in lpFileName: + return 0xffffffff + return real_function() + + my_exe = windows.current_process.peb.modules[0] + imp = my_exe.pe.imports + + iat_create_file = [entry for entry in imp['kernel32.dll'] if entry.name == "CreateFileA"] + iat_create_file.set_hook(createfile_callback) + + +.. _hook_protocol: + +Hook protocol +''''''''''''' + +Callback arguments +------------------ + +A hook callback must have the same number of argument as the hooked API, PLUS a last argument ``real_function``. + + + +The ``real_function`` argument is a callable that represent the hooked API, it can be called in two ways: + + * Without argument, the call will be done with the argument originaly passed to your callback. This allows simple redirection to the real API. + + * With arguments it will simply call the API with these. + +Example:: + + def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function): + print("Trying to open {0}".format(lpFileName)) + if "secret" in lpFileName: + return 0xffffffff + # Perform the real call + return real_function() + + +A hook callback must also embed some :ref:`Type Information ` + + +.. _type_information: + +Callback type information +-------------------------- + +In order make the magic behind hook callback, :mod:`ctypes` needs to have type information about the API parameters. + +There is (again) two ways to give those informations to your hook callback. Both techniques use a decorator to setup type information to the callback. + + * Giving the type manualy using the decorator :class:`windows.hooks.Callback`:: + + from windows.hooks import * + # First type is return type, others are parameters types + @Callback(ctypes.c_void_p, ctypes.c_ulong) + def exit_callback(x, real_function): + print("Try to quit with {0} | {1}".format(x, type(x))) + if x == 3: + print("TRYING TO REAL EXIT") + return real_function(1234) + return 0x4242424243444546 + + * Using the `Callback` decorator generated from known functions:: + + from windows.hooks import * + # Decorator name is always API_NAME + "CallBack" + @CreateFileACallback + def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function): + print("Trying to open {0}".format(lpFileName)) + if "secret" in lpFileName: + return 0xffffffff + return real_function() + + .. note:: + + See the list of known functions + + +:mod:`windows.hooks` +'''''''''''''''''''' + +.. module:: windows.hooks + +.. autoclass:: windows.hooks.Callback + +.. autoclass:: windows.hooks.IATHook \ No newline at end of file diff --git a/docs/build/html/_sources/index.rst.txt b/docs/build/html/_sources/index.rst.txt new file mode 100644 index 0000000..a6af62e --- /dev/null +++ b/docs/build/html/_sources/index.rst.txt @@ -0,0 +1,36 @@ +.. PyWindows documentation master file, created by + sphinx-quickstart on Tue Apr 07 11:39:41 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to PythonForWindows's documentation! +============================================ + +Contents: + +.. toctree:: + :maxdepth: 2 + :numbered: + + windows.rst + various.rst + native_exec.rst + winproxy.rst + utils.rst + wintrust.rst + debug.rst + com.rst + crypto.rst + iat_hook.rst + wip.rst + internals.rst + sample.rst + + +Indices and tables +================== + +* :ref:`modindex` +* :ref:`search` +* :ref:`genindex` + diff --git a/docs/build/html/_sources/internals.rst.txt b/docs/build/html/_sources/internals.rst.txt new file mode 100644 index 0000000..7163570 --- /dev/null +++ b/docs/build/html/_sources/internals.rst.txt @@ -0,0 +1,125 @@ +Internals +========= + +Because some horrible hacks of ``PythonForWindows`` are hidden and I wanted to talk about it. + +remotectypes.py +''''''''''''''' + +.. module:: windows.remotectypes + +Performing parsing of PEB / PE in remote process may be painful and i didn't want +to have two versions of all my parsing code. + +So I made a wrapper around :mod:`ctypes` that is able to do two things: + + - Transform a 32bits ctypes structure into a 64bits one and reverse + + This is done by replacing the ``c_void_p``/``c_char_p`` by ``DWORD`` or + ``QWORD`` and rewriting a wrapper around the :mod:`ctypes` ``POINTER`` and other stuff. + It might not works for every structure by i didn't have any problem for now. + + - Read the memory in another process + + For this one I rewrote a class that use the standard :mod:`ctypes` structure + offset-size calculation, extracts those information when asked for a field and read it from the target process. + We just need to take care of special cases: ``POINTER`` / ``ARRAY`` / ``STRING`` / .. + +We also need to be carreful about the inheritance, we need to inherit from "hidden" +:class:`ctypes` classes to keep the magic working. + + +This module exports the following API: + +.. autofunction:: transform_type_to_remote32bits + +.. autofunction:: transform_type_to_remote64bits + +Both functions return a class that represent the structure in a remote process. +The class.__init__ accept two arguments: + + * ``base_addr``: the address of the object in the remote process + * ``target``: an object with a method ``read_memory`` (so a :class:`windows.winobject.WinProcess` in our case) + +Example ``WinProcess.peb``:: + + def peb(self): + if windows.current_process.bitness == 32 and self.bitness == 64: + return RemotePEB64(self.peb_addr, self) + if windows.current_process.bitness == 64 and self.bitness == 32: + return RemotePEB32(self.peb_addr, self) + return RemotePEB(self.peb_addr, self) + +I am pretty sure that this code does NOT handle all the cases, so it might break some day. + +syswow64.py -- Crossing the heaven gate +''''''''''''''''''''''''''''''''''''''' + +.. module:: windows.syswow64 + +One of my goal with ``PythonForWindows`` is to have some abstraction of the bitness of the processes. +It means being able to work on a ``32bits Python`` or a ``64bits Python``. + +In the case of a 32bits python on a ``64bits`` system (``SysWow64``) it's not trivial to perform operation on +other ``64bits`` processes. For example directly calling :func:`CreateRemoteThread` will not work. + +To be able to perform those operation we must be able to execute code in the ``64bits`` part of our +``SysWow64`` process. + +.. note:: + + See `Knockin’ on Heaven’s Gate – Dynamic Processor Mode Switching `_ + + +For that we need to jump to the 64bits segment of our process, execute some code then return. +To do so, we need to use some ``far jump`` / ``far ret`` with the segments selector ``0x23`` (CS_32bits) and ``0x33`` (CS_64bits). + +The generation of this is quite ugly in my case. +This code is in: + +.. function:: execute_64bits_code_from_syswow + +Once we are able to execute some code in the ``64bits`` part we need to create the code that will call our API (in NTDLL). +To do that, I rely on the type information already present in the function of :mod:`windows.winproxy`. +With these information we are able to know + + * The name of the API + * The number of arguments + +Then I generate the correct x64 stub (using :mod:`windows.native_exec.simple_x64`) with the function: + +.. function:: generate_syswow64_call + +One problem I encountered is that our function must be able to pass values of 64bits, so passing arguments by register is not possible. + +For now I allocate a buffer where a python wrapper copy the parameters and the x64 stub retrieves them from here. + +(It might be possible to do something by creating a WINCFUNC with only ULONG64 parameters). + +.. function:: try_generate_stub_target + +The final result is a ``Python`` function like the one in :mod:`windows.winproxy` + + * It copies the arguments in the buffer + * Jumps on the 32->64 stub + * X64 bits code retrieves the arguments in the buffer and setup the registers and the stack for the call + * Calls the API + * Returns to 32bits mode. + +.. class:: Syswow64ApiProxy + +Existing function are: + +.. function:: NtCreateThreadEx_32_to_64 + +.. function:: NtQueryInformationProcess_32_to_64 + +.. function:: NtQueryInformationThread_32_to_64 + +.. function:: NtQueryVirtualMemory_32_to_64 + +.. function:: NtGetContextThread_32_to_64 + +.. function:: NtSetContextThread_32_to_64 + +.. function:: LdrLoadDll_32_to_64 \ No newline at end of file diff --git a/docs/build/html/_sources/native_exec.rst.txt b/docs/build/html/_sources/native_exec.rst.txt new file mode 100644 index 0000000..f46e723 --- /dev/null +++ b/docs/build/html/_sources/native_exec.rst.txt @@ -0,0 +1,236 @@ +.. module:: windows.native_exec + +``windows.native_exec`` -- Native Code Execution +************************************************ + + +:mod:`windows.native_exec` allows to create `Python` functions calling native code. +it also provides a simple assembler for x86 and x64. + +:mod:`windows.native_exec` provides those functions: + +.. autofunction:: windows.native_exec.create_function + +The :mod:`windows.native_exec` also contains some submodules: + * :mod:`windows.native_exec.cpuid` + * :mod:`windows.native_exec.simple_x86` + * :mod:`windows.native_exec.simple_x64` + +:mod:`windows.native_exec.cpuid` -- Interface to native CPUID +""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" + +.. automodule:: windows.native_exec.cpuid + :no-show-inheritance: + :no-members: bitness + +Demo:: + + >>> import windows.native_exec.cpuid + >>> windows.native_exec.cpuid.do_cpuid(0) + + >>> x = windows.native_exec.cpuid.do_cpuid(0) + >>> x.EAX + 13L + >>> x.EBX + 1970169159L + >>> windows.native_exec.cpuid.get_vendor_id() + 'GenuineIntel' + >>> windows.native_exec.cpuid.get_proc_family_model() + (6L, 58L) + + +:mod:`windows.native_exec.simple_x86` -- X86 Assembler +"""""""""""""""""""""""""""""""""""""""""""""""""""""" + +.. module:: windows.native_exec.simple_x86 + +The :mod:`windows.native_exec.simple_x86` module allows to create simple x86 code. + +Its features are: + * Forward - Backward jump (using labels) + * Non-string interface for conditional/context dependent generation + + +.. note:: + The assembler DOES NOT handle every instruction at all. + + +The assembler instructions are `Python` object that may accept arguments representing +the mnemonic operands. + +These parameters can be of type: + * :class:`str` (register) + * :class:`int` (int) + * :class:`mem_access` (memory access) + +.. autoclass:: windows.native_exec.simple_x86.mem_access + :members: prefix, base, index, scale, disp + :exclude-members: count + +The :class:`mem_access` object can be created: + * By hand + * Using :func:`create_displacement` + * Using :func:`mem` + +.. autofunction:: windows.native_exec.simple_x86.create_displacement +.. autofunction:: windows.native_exec.simple_x86.deref +.. autofunction:: windows.native_exec.simple_x86.mem + +Instruction assembling:: + + >>> import windows.native_exec.simple_x86 as x86 + >>> import random + >>> x86.Mov + + >>> instr = x86.Mov("EAX", "EBX") + >>> instr + + >>> instr.get_code() + '\x89\xd8' + >>> x86.Mov("EAX", 0x42424242).get_code() + '\xc7\xc0BBBB' + >>> x86.Mov("EAX", x86.create_displacement(base="EAX", disp=random.randint(0, 0xffffffff))).get_code() + '\x8b\x80\x977\n&' + >>> x86.Mov(x86.mem("[EBX + EDI * 2 + 0x11111111]"), "EAX").get_code() + '\x89\x84{\x11\x11\x11\x11' + >>> x86.Mov(x86.mem("gs:[EBX + EDI * 2 + 0x11111111]"), "EAX").get_code() + 'e\x89\x84{\x11\x11\x11\x11' + +:mod:`windows.native_exec.simple_x86` also provides an interface to complex shellcode assembling +including jump and label via the :class:`MultipleInstr` class. + +Shellcode assembling:: + + import windows.native_exec.simple_x86 as x86 + + code = x86.MultipleInstr() + code += x86.Label(":BEGIN") + code += x86.Jmp(":BEGIN") + print(repr(code.get_code())) + # '\xeb\xfe' + +Another example from a project:: + + IO_STACK_INPUT_BUFFER_LEN = x86.mem('[ESI + 8]') + IO_STACK_INPUT_BUFFER = x86.mem('[ESI + 0x10]') + + INPUT_BUFFER_SIZE = x86.mem('[ECX]') + INPUT_BUFFER_PORT = x86.mem('[ECX + 4]') + INPUT_BUFFER_VALUE = x86.mem('[ECX + 8]') + + out_ioctl = x86.MultipleInstr() + out_ioctl += x86.Cmp(IO_STACK_INPUT_BUFFER_LEN, 0xc) # size indicator / port / value + out_ioctl += x86.Jnz(":FAIL") + out_ioctl += x86.Mov('ECX', IO_STACK_INPUT_BUFFER) + out_ioctl += x86.Mov('EDX', INPUT_BUFFER_PORT) + out_ioctl += x86.Mov('EAX', INPUT_BUFFER_VALUE) + out_ioctl += x86.Mov('ECX', INPUT_BUFFER_SIZE) + out_ioctl += x86.Cmp('ECX', 0x1) + out_ioctl += x86.Jnz(":OUT_2_OR_4") + out_ioctl += x86.Out('DX', 'AL') + out_ioctl += x86.Jmp(':SUCCESS') + out_ioctl += x86.Label(":OUT_2_OR_4") + out_ioctl += x86.Cmp('ECX', 0x2) + out_ioctl += x86.Jnz(":OUT_4") + out_ioctl += x86.Out('DX', 'AX') + out_ioctl += x86.Jmp(':SUCCESS') + out_ioctl += x86.Label(":OUT_4") + out_ioctl += x86.Out('DX', 'EAX') + out_ioctl += x86.Label(":SUCCESS") + out_ioctl += x86.Xor('EAX', 'EAX') + out_ioctl += x86.Ret() + out_ioctl += x86.Label(":FAIL") + out_ioctl += x86.Mov('EAX', 0x0C000000D) + out_ioctl += x86.Ret() + + out_ioctl.get_code() + '\x81~\x08\x0c\x00\x00\x00u&\x8bN\x10\x8bQ\x04\x8bA\x08\x8b\t\x81\xf9\x01\x00\x00\x00u\x03\xee\xeb\r\x81\xf9\x02\x00\x00\x00u\x04f\xef\xeb\x01\xef1\xc0\xc3\xc7\xc0\r\x00\x00\xc0\xc3' + + +:mod:`windows.native_exec.simple_x64` -- X64 Assembler +"""""""""""""""""""""""""""""""""""""""""""""""""""""" + +.. module:: windows.native_exec.simple_x64 + +Same things as :mod:`windows.native_exec.simple_x86` + +The only things that change are: + * The registers name + +:mod:`windows.native_exec.simple_x64` handles 32 and 64 bits operations. + +Demo:: + + >>> import windows.native_exec.simple_x64 as x64 + >>> x64.Mov("RAX", "R13").get_code() + 'L\x89\xe8' + >>> x64.Mov("EAX", "EDI").get_code() + '\x89\xf8' + >>> x64.Mov("RAX", "EDI").get_code() + """ + ValueError: Size mismatch + """ + >>> x64.Mov("RAX", x64.mem("[EAX]")).get_code() + 'gH\x8b\x00' + >>> x64.Mov("RAX", x64.mem("[RAX]")).get_code() + 'H\x8b\x00' + >>> x64.Mov("EAX", x64.mem("[RAX]")).get_code() + '\x8b\x00' + >>> x64.Mov("EAX", x64.mem("[EAX]")).get_code() + 'g\x8b\x00' + + + +:mod:`windows.native_exec.nativeutils` -- Native utility functions +"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" + +.. module:: windows.native_exec.nativeutils + +This module contains some native-code functions that can be used for various purposes. +Each function export a label that allow another :class:`MultipleInstr` to call the code of the function. + +The current functions are: + + * ``StrlenW64`` A 64bits wide-string STRLEN (``Label(":FUNC_STRLENW64")``) + * ``StrlenA64`` A 64bits ASCII STRLEN (``Label(":FUNC_STRLENA64")``) + * ``GetProcAddress64`` A 64bits export resolver (``Label(":FUNC_GETPROCADDRESS64")``) + + * Arg1: The DLL (wstring) + * Arg2: The API (string) + * Return value: + + * 0xfffffffffffffffe if the DLL is not found + * 0xffffffffffffffff if the API is not found + * The address of the function + + * ``StrlenW32`` A 32bits wide-string STRLEN (``Label(":FUNC_STRLENW32")``) + * ``StrlenA32`` A 32bits ASCII STRLEN (``Label(":FUNC_STRLENA32")``) + * ``GetProcAddress32`` A 32bits export resolver (``Label(":FUNC_GETPROCADDRESS32")``) + + * Arg1: The DLL (wstring) + * Arg2: The API (string) + * Return value: + + * 0xfffffffe if the DLL is not found + * 0xffffffff if the API is not found + * The address of the function + +To use those functions in a :class:`MultipleInstr` just call the label in your code and append the function at +the end of your :class:`MultipleInstr` + + +Example:: + + RemoteManualLoadLibray = x86.MultipleInstr() + + RemoteManualLoadLibray += x86.Mov("ECX", x86.mem("[ESP + 4]")) + RemoteManualLoadLibray += x86.Push(x86.mem("[ECX + 4]")) + RemoteManualLoadLibray += x86.Push(x86.mem("[ECX]")) + RemoteManualLoadLibray += x86.Call(":FUNC_GETPROCADDRESS32") + RemoteManualLoadLibray += x86.Push(x86.mem("[ECX + 8]")) + RemoteManualLoadLibray += x86.Call("EAX") # LoadLibrary + RemoteManualLoadLibray += x86.Pop("ECX") + RemoteManualLoadLibray += x86.Pop("ECX") + RemoteManualLoadLibray += x86.Ret() + + RemoteManualLoadLibray += GetProcAddress32 \ No newline at end of file diff --git a/docs/build/html/_sources/network.rst.txt b/docs/build/html/_sources/network.rst.txt new file mode 100644 index 0000000..2e64fd3 --- /dev/null +++ b/docs/build/html/_sources/network.rst.txt @@ -0,0 +1,27 @@ +Network +======= + +.. module:: windows.winobject.network + +.. note:: + + See sample :ref:`sample_network_exploration` + + +.. autoclass:: Network + +Connections +""""""""""" + +.. autoclass:: TCP4Connection + + +.. autoclass:: TCP6Connection + +Firewall +"""""""" + +.. autoclass:: Firewall + + +.. autoclass:: FirewallRule \ No newline at end of file diff --git a/docs/build/html/_sources/process.rst.txt b/docs/build/html/_sources/process.rst.txt new file mode 100644 index 0000000..fd0f77b --- /dev/null +++ b/docs/build/html/_sources/process.rst.txt @@ -0,0 +1,128 @@ +Processes and Threads +""""""""""""""""""""" + +.. module:: windows.winobject.process + +CurrentProcess +'''''''''''''' + +.. note:: + + See sample :ref:`sample_current_process` + +.. autoclass:: CurrentProcess + :members: + :show-inheritance: + :inherited-members: + +CurrentThread +''''''''''''' + +.. autoclass:: CurrentThread + :members: + :show-inheritance: + :inherited-members: + +WinProcess +'''''''''' + +.. note:: + + See sample :ref:`sample_remote_process` + +.. autoclass:: WinProcess + :members: + :show-inheritance: + :inherited-members: + + +WinThread +''''''''' + +.. autoclass:: WinThread + :members: + :show-inheritance: + :inherited-members: + + +.. autoclass:: DeadThread + :members: + :show-inheritance: + :inherited-members: + +Token +''''' + +.. autoclass:: Token + :members: + :inherited-members: + + +PEB Exploration +""""""""""""""" + +The :mod:`windows` module is able to parse the PEB of the current process or remote process. +The :class:`PEB` is accessible via ``process.peb`` and is of type :class:`PEB`. + +.. note:: + + See sample :ref:`sample_peb_exploration` + +PEB +''' + +.. autoclass:: PEB + :members: + :inherited-members: + +.. autoclass:: WinUnicodeString + +LoadedModule +'''''''''''' + +.. autoclass:: LoadedModule + + +PEFile - Parsing loaded PE +"""""""""""""""""""""""""" + +:mod:`windows.pe_parse` +''''''''''''''''''''''' + +.. module:: windows.pe_parse + +.. autofunction:: windows.pe_parse.GetPEFile + +PEFile +^^^^^^ + +.. autoclass:: PEFile + +IATEntry +^^^^^^^^ + +.. autoclass:: IATEntry + + .. data:: addr + + :class:`int` : Address of the IAT Entry + + .. data:: ord + + :class:`int` : Ordinal of the imported function + + .. data:: name + + :class:`int` : Name of the imported function + + .. data:: value + + :class:`int` : The content (destination) of the IAT entry + + .. warning:: + + `value` is a descriptor. Setting its value will actually CHANGE THE IAT ENTRY, resulting in a segfault if no VirtualProtect have been done. + + .. note:: + + See: :class:`windows.utils.VirtualProtected` \ No newline at end of file diff --git a/docs/build/html/_sources/registry.rst.txt b/docs/build/html/_sources/registry.rst.txt new file mode 100644 index 0000000..cf1f0ba --- /dev/null +++ b/docs/build/html/_sources/registry.rst.txt @@ -0,0 +1,38 @@ +Registry +======== + +.. module:: windows.winobject.registry + +.. note:: + + See sample :ref:`sample_registry` + +Registry +"""""""" + +.. autoclass:: Registry + :special-members: __getitem__ + + +PyHKey +"""""" + +.. autoclass:: PyHKey + + .. function:: __call__(name) + + Alias for :func:`open_subkey` + + .. function:: __getitem__(name) + + Alias for :func:`get` + + .. function:: __setitem__(name) + + Wrapper for :func:`set`, accept ``value`` or ``(value, type)`` + +KeyValue +"""""""" + +.. autoclass:: KeyValue + :exclude-members: count, index \ No newline at end of file diff --git a/docs/build/html/_sources/sample.rst.txt b/docs/build/html/_sources/sample.rst.txt new file mode 100644 index 0000000..c86df28 --- /dev/null +++ b/docs/build/html/_sources/sample.rst.txt @@ -0,0 +1,705 @@ +Samples of code +=============== + +Processes +""""""""" + +.. _sample_current_process: + +``windows.current_process`` +''''''''''''''''''''''''''' + +.. literalinclude:: ..\..\samples\current_process.py + +Output:: + + (cmd λ) python32.exe current_process.py + current process is + current process is a <32> bits process + current process is a SysWow64 process ? + current process pid <8264> and ppid <4100> + Here are the current process threads: <[]> + Let's execute some native code ! (0x41 + 1) + Native code returned <0x42> + Allocating memory in current process + Allocated memory is at <0xd60000> + Writing 'SOME STUFF' in allocation memory + Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'> + +.. _sample_remote_process: + +Remote process : :class:`WinProcess` +'''''''''''''''''''''''''''''''''''' + +.. literalinclude:: ..\..\samples\remote_process.py + +Output:: + + (cmd λ) python.exe remote_process.py + Creating a notepad + Looking for notepads in the processes + They are currently <1> notepads running on the system + Let's play with our notepad: <> + Our notepad pid is 2044 + Our notepad is a <32> bits process + Our notepad is a SysWow64 process ? + Our notepad have threads ! <[, , ...]> + Exploring our notepad PEB ! + Command line is + Here are 3 loaded modules: [, , ] + Allocating memory in our notepad + Allocated memory is at <0x6f80000> + Writing 'SOME STUFF' in allocated memory + Reading allocated memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'> + Execution some native code in our notepad (write 0x424242 at allocated address + return 0x1337) + Executing native code ! + Return code = 0x1337L + Reading allocated memory : <'BBBB STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'> + Executing python code ! + Reading allocated memory : <'HELLO FROM notepad\x00\x00'> + Trying to import in remote module 'FAKE_MODULE' + Remote ERROR ! + Traceback (most recent call last): + File "", line 3, in + File "", line 2, in func + ImportError: No module named FAKE_MODULE + + That's all ! killing the notepad + + +.. _sample_peb_exploration: + +:class:`PEB` exploration +'''''''''''''''''''''''' + +.. literalinclude:: ..\..\samples\peb.py + +Output:: + + (cmd λ) python.exe peb.py + Exploring the current process PEB + PEB is <> + Commandline object is + Commandline string is u'python.exe peb.py ' + Imagepath + Printing some modules: + + + + + + === K32 === + Looking for kernel32.dll + Kernel32 module: + Module name = | Fullname = + Kernel32 is loaded at address 0x774c0000 + === K32 PE === + PE Representation of k32: + Here are some exports {0: 2001566688L, u'CreateFileA': 2001635616L, 42: 2001647872L, u'VirtualAlloc': 2001570704L} + Import DLL dependancies are (without api-*): [u'ntdll.dll', u'kernelbase.dll'] + IAT Entry for ntdll!NtCreateFile = | addr = 0x77541128L + Sections: [, , , , ] + +.. _sample_iat_hook: + +IAT hooking +''''''''''' + +.. literalinclude:: ..\..\samples\iat_hook.py + +Output:: + + (cmd λ) python iat_hook.py + Asking for + Hook called | hKey = 0x12d687 | lpSubKey = + Secret key asked, returning magic handle 0x12345678 + Result = 0x12345678 + + Asking for + Hook called | hKey = 0x12d687 | lpSubKey = + Asked for a failing key: returning 0x2a + WindowsError(42, 'Windows Error 0x2A') + + Asking for + Hook called | hKey = 0x80000001L | lpSubKey = + Non-secret key : calling normal function + Result = 0x108 + +.. _sample_system: + + +``windows.system`` +"""""""""""""""""" + +.. literalinclude:: ..\..\samples\system.py + +Output:: + + (cmd λ) python system.py + Basic system infos: + version = (6, 3) + bitness = 64 + computer_name = HAKRIL-PC + product_type = VER_NT_WORKSTATION(0x1L) + version_name = Windows 8.1 + + There is 117 processes + There is 1246 threads + + Dumping first logical drive: + + name = C:\ + type = DRIVE_FIXED(0x3L) + path = \Device\HarddiskVolume2 + + Dumping first service: + + name = ACPI + description = Microsoft ACPI Driver + status = ServiceStatus(type=SERVICE_KERNEL_DRIVER(0x1L), state=SERVICE_RUNNING(0x4L), control_accepted=1L, flags=0L) + process = None + + Finding a service in a user process: + + name = Appinfo + description = Application Information + status = ServiceStatus(type=SERVICE_WIN32_SHARE_PROCESS(0x20L), state=SERVICE_RUNNING(0x4L), control_accepted=129L, flags=0L) + process = + + Enumerating handles: + There are 40664 handles: + First handle is: in process pid=4> + Enumerating handles of the current process: + There are 255 handles for this process + Looking for a File handle: + Handle is in process pid=14340> + Name is <\Device\ConDrv> + + + +.. _sample_network_exploration: + +:class:`Network` - socket exploration +""""""""""""""""""""""""""""""""""""" + +.. literalinclude:: ..\..\samples\network.py + +Output:: + + (cmd λ) python.exe network.py + Working on ipv4 + == Listening == + Some listening connections: [, , ] + Listening ports are : [80, 135, 443, 445, 902, 912, 5357, 49152, 49153, 49154, 49155, 49157, 49159, 8307, 25340, 139, 139] + == Established == + Some established connections: [ 127.0.0.1:49472>, 127.0.0.1:49174>, 127.0.0.1:49173>] + == connection to localhost:80 == + Our connection is [ 127.0.0.1:80>] + Sending YOP + Closing socket + Sending LAIT + Traceback (most recent call last): + File ".\network.py", line 45, in + s.send("LAIT") + socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host + + +.. _sample_registry: + +:class:`Registry` +""""""""""""""""" + +.. literalinclude:: ..\..\samples\registry.py + +Output:: + + (cmd λ) python.exe registry.py + Registry is <> + HKEY_CURRENT_USER is <> + HKEY_CURRENT_USER subkeys names are: + ['AppEvents', + 'AppXBackupContentType', + 'Console', + 'Control Panel', + 'Environment', + 'EUDC', + 'Identities', + 'Keyboard Layout', + 'Network', + 'Printers', + 'Software', + 'System', + 'Volatile Environment'] + Opening 'Software' in HKEY_CURRENT_USER: + We can also open it in one access: + Looking at CurrentVersion + Key is + values are: + [KeyValue(name='SoftwareType', value=u'System', type=1), + KeyValue(name='RegisteredOwner', value=u'hakril', type=1), + KeyValue(name='InstallDate', value=0, type=4), + ... + KeyValue(name='PathName', value=u'C:\\Windows', type=1)] + registered owner = + + +.. _sample_wintrust: + +``windows.wintrust`` +"""""""""""""""""""" + +.. literalinclude:: ..\..\samples\wintrust.py + +Output:: + + (cmd λ) python .\wintrust.py + Checking signature of + is_signed: + check_signature: <0> + full_signature_information: + * signed + * catalog + * catalogsigned + * additionalinfo <0> + Checking signature of some loaded DLL + : False (TRUST_E_NOSIGNATURE(0x800b0100L)) + : True + : True + : True + : False (TRUST_E_NOSIGNATURE(0x800b0100L)) + +.. _sample_vectoredexception: + +:func:`VectoredException` +""""""""""""""""""""""""" + +In local process +'''''''''''''''' + +.. literalinclude:: ..\..\samples\veh_segv.py + +Output:: + + (cmd λ) python.exe veh_segv.py + Protected page is at <0x1db0000> + Setting page protection to + + ==Entry of VEH handler== + Instr at 0x1d1ab574 accessed to addr 0x1db0000 + Resetting page protection to + ==Entry of VEH handler== + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + Value 1 read + + ==Entry of VEH handler== + Instr at 0x1d1ab574 accessed to addr 0x1db0010 + Resetting page protection to + ==Entry of VEH handler== + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + Value 2 read + + +In remote process +''''''''''''''''' + +.. literalinclude:: ..\..\samples\remote_veh_segv.py + +Output:: + + (cmd λ) python .exe.\samples\remote_veh_segv.py + (In another console) + + Tracing execution in module: + Protected page is at 0x7ffa3c700000L + + Instr at 0x7ffa3c70f0f0L accessed to addr 0x7ffa3c70f0f0L (gdi32.dll) + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + + Instr at 0x7ffa3c70f0f5L accessed to addr 0x7ffa3c70f0f5L (gdi32.dll) + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + + Instr at 0x7ffa3c70f0faL accessed to addr 0x7ffa3c70f0faL (gdi32.dll) + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + + Instr at 0x7ffa3c70f0ffL accessed to addr 0x7ffa3c70f0ffL (gdi32.dll) + Exception of type EXCEPTION_SINGLE_STEP(0x80000004L) + Resetting page protection to + + Instr at 0x7ffa3c70f100L accessed to addr 0x7ffa3c70f100L (gdi32.dll) + No more tracing ! + + +.. _sample_debugger: + +Debugging +""""""""" + +:class:`Debugger` +''''''''''''''''' + +.. literalinclude:: ..\..\samples\debugger_print_LdrLoaddll.py + +Ouput:: + + (cmd λ) python.exe .\samples\debugger_print_LdrLoaddll.py + Loading + Got exception EXCEPTION_BREAKPOINT(0x80000003L) at 0x77a73bad + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Loading + Ask to load : exiting process + + +Single stepping +~~~~~~~~~~~~~~~ + +.. literalinclude:: ..\..\samples\debugger_membp_singlestep.py + +Ouput:: + + (cmd λ) python.exe .\samples\debugger_membp_singlestep.py + Got exception EXCEPTION_BREAKPOINT(0x80000003L) at 0x77ae3c7d + Instruction at <0x8d0006> wrote at <0x8e0000> + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d000c + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d0011 + Instruction at <0x8d0011> wrote at <0x8e0004> + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d0017 + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d001c + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d0022 + Got single_step EXCEPTION_SINGLE_STEP(0x80000004L) at 0x8d0023 + No more single step: exiting + + +:class:`windows.debug.FunctionBP` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: ..\..\samples\debug_functionbp.py + +Ouput:: + + (cmd λ) python.exe .\samples\debug_functionbp.py + NtCreateFile of <\??\C:\Windows\syswow64\en-US\calc.exe.mui>: handle = 0xac + Handle manually found! typename=, name=<\Device\HarddiskVolume2\Windows\SysWOW64\en-US\calc.exe.mui> + + NtCreateFile of <\Device\DeviceApi\CMApi>: handle = 0x108 + Handle manually found! typename=, name=<\Device\DeviceApi> + + NtCreateFile of <\??\C:\Windows\Fonts\staticcache.dat>: handle = 0x154 + Handle manually found! typename=, name=<\Device\HarddiskVolume2\Windows\Fonts\StaticCache.dat> + + Exiting process + + +Native code tester +~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: ..\..\samples\test_code.py + + +Ouput:: + + (cmd λ) python.exe .\samples\test_code.py "mov eax, 0x42424242" "eax=0x11223344" + Testing x86 code + Startup context is: + Eip -> 0x3f0000L + Esp -> 0x3bfae4L + Eax -> 0x11223344L + Ebx -> 0x5a6000L + Ecx -> 0x0L + Edx -> 0x0L + Ebp -> 0x0L + Edi -> 0x0L + Esi -> 0x0L + EFlags -> 0x202L + EEflags(0x202L:IF) + ==Post-exec context== + Eip -> 0x3f0007L + Esp -> 0x3bfae4L + Eax -> 0x42424242L + Ebx -> 0x5a6000L + Ecx -> 0x0L + Edx -> 0x0L + Ebp -> 0x0L + Edi -> 0x0L + Esi -> 0x0L + EFlags -> 0x202L + EEflags(0x202L:IF) + + ==DIFF== + Eip: 0x3f0000 -> 0x3f0007 (+0x7) + Eax: 0x11223344 -> 0x42424242 (+0x31200efe) + + + (cmd λ) python64 .\samples\test_code.py --x64 "mov r15, 0x11223344; push r14; call r15" "rcx=1; r14=0x4242424243434343" + Testing x64 code + Startup context is: + Rip -> 0x205a1d60000L + Rsp -> 0xe24a88fa88L + Rax -> 0x0L + Rbx -> 0x0L + Rcx -> 0x1L + Rdx -> 0xe24aaf9000L + Rbp -> 0x0L + Rdi -> 0x0L + Rsi -> 0x0L + R8 -> 0x0L + R9 -> 0x0L + R10 -> 0x0L + R11 -> 0x0L + R12 -> 0x0L + R13 -> 0x0L + R14 -> 0x4242424243434343L + R15 -> 0x0L + EFlags -> 0x200L + EEflags(0x200L:IF) + ==Post-exec context== + Rip -> 0x11223344L + Rsp -> 0xe24a88fa78L + Rax -> 0x0L + Rbx -> 0x0L + Rcx -> 0x1L + Rdx -> 0xe24aaf9000L + Rbp -> 0x0L + Rdi -> 0x0L + Rsi -> 0x0L + R8 -> 0x0L + R9 -> 0x0L + R10 -> 0x0L + R11 -> 0x0L + R12 -> 0x0L + R13 -> 0x0L + R14 -> 0x4242424243434343L + R15 -> 0x11223344L + EFlags -> 0x10202L + EEflags(0x10202L:IF|RF) + at <0x11223344> + ==DIFF== + Rip: 0x205a1d60000 -> 0x11223344 (-0x20590b3ccbc) + Rsp: 0xe24a88fa88 -> 0xe24a88fa78 (-0x10) + R15: 0x0 -> 0x11223344 (+0x11223344) + EFlags: 0x200 -> 0x10202 (+0x10002) + Negative Stack: dumping: + E24A88FA88 0C 00 D6 A1 05 02 00 00 43 43 43 43 42 42 42 42 ........CCCCBBBB + + +.. _sample_local_debugger: + + +:class:`LocalDebugger` +'''''''''''''''''''''' + +In current process +~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: ..\..\samples\local_debugger.py + +Ouput:: + + (cmd λ) python.exe .\samples\local_debugger.py + Code addr = 0xcf0002 + GOT AN HXBP at 0xcf0002 + EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004L) at 0xcf0003 + EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004L) at 0xcf0004 + EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004L) at 0xcf0005 + EXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004L) at 0x770d7c04 + Done! + + +In remote process +~~~~~~~~~~~~~~~~~ + +.. literalinclude:: ..\..\samples\local_debugger_remote_process.py + +Ouput:: + + (cmd λ) python.exe .\samples\local_debugger_remote_process.py + (In another console) + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + I AM LOADING + + +.. _wmi_request: + +Make WMI requests +""""""""""""""""" + + +.. literalinclude:: ..\..\samples\wmi_request.py + + +Ouput:: + + (cmd λ) python .\samples\wmi_request.py + WMI requester is + Selecting * from 'Win32_Process' + They are <92> processes + Looking for ourself via pid + Some info about our process: + * Name -> python.exe + * ProcessId -> 7968 + * OSName -> Microsoft Windows 8.1 Pro|C:\Windows|\Device\Harddisk0\Partition2 + * UserModeTime -> 2812500 + * WindowsVersion -> 6.3.9600 + * CommandLine -> python.exe .\samples\wmi_request.py + " + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll(":enabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll(":disabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( el ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return (sel + "").replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( (oldCache = uniqueCache[ key ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context === document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( el ) { + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( el ) { + return el.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; + } ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnotwhite = ( /\S+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + resolve.call( undefined, value ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.call( undefined, value ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( jQuery.isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[ 0 ], key ) : emptyGet; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ jQuery.camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ jQuery.camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( jQuery.camelCase ); + } else { + key = jQuery.camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnotwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? JSON.parse( data ) : + data; + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + jQuery.contains( elem.ownerDocument, elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + +var swap = function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + do { + + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ), + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); + +var rscriptType = ( /^$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE <=9 only + option: [ 1, "" ], + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
    " ], + col: [ 2, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + + _default: [ 0, "", "" ] +}; + +// Support: IE <=9 only +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? + context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); +var documentElement = document.documentElement; + + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 only +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + // Make a writable jQuery.Event from the native event object + var event = jQuery.event.fix( nativeEvent ); + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Support: IE <=9 + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // + // Support: Firefox <=42 + // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) + if ( delegateCount && cur.nodeType && + ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push( { elem: cur, handlers: matches } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: jQuery.isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event.which; + } +}, jQuery.event.addProp ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + /* eslint-disable max-len */ + + // See https://github.com/eslint/eslint/issues/3229 + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, + + /* eslint-enable */ + + // Support: IE <=10 - 11, Edge 12 - 13 + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +function manipulationTarget( elem, content ) { + if ( jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return elem.getElementsByTagName( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rmargin = ( /^margin/ ); + +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + div.style.cssText = + "box-sizing:border-box;" + + "position:relative;display:block;" + + "margin:auto;border:1px;padding:1px;" + + "top:1%;width:50%"; + div.innerHTML = ""; + documentElement.appendChild( container ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = divStyle.marginLeft === "2px"; + boxSizingReliableVal = divStyle.width === "4px"; + + // Support: Android 4.0 - 4.3 only + // Some styles come back with percentage values, even though they shouldn't + div.style.marginRight = "50%"; + pixelMarginRightVal = divStyle.marginRight === "4px"; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + + "padding:0;margin-top:1px;position:absolute"; + container.appendChild( div ); + + jQuery.extend( support, { + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelMarginRight: function() { + computeStyleTests(); + return pixelMarginRightVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + style = elem.style; + + computed = computed || getStyles( elem ); + + // Support: IE <=9 only + // getPropertyValue is only needed for .css('filter') (#12537) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }, + + cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style; + +// Return a css property mapped to a potentially vendor prefixed property +function vendorPropName( name ) { + + // Shortcut for names that are not vendor prefixed + if ( name in emptyStyle ) { + return name; + } + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +function setPositiveNumber( elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + + // If we already have the right measurement, avoid augmentation + 4 : + + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // At this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + + // At this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // At this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var val, + valueIsBorderBox = true, + styles = getStyles( elem ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + if ( elem.getClientRects().length ) { + val = elem.getBoundingClientRect()[ name ]; + } + + // Some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test( val ) ) { + return val; + } + + // Check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && + ( support.boxSizingReliable() || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // Use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + "float": "cssFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || + ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + if ( type === "number" ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + style[ name ] = value; + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || + ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + } ) : + getWidthOrHeight( elem, name, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = extra && getStyles( elem ), + subtract = extra && augmentWidthOrHeight( + elem, + name, + extra, + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + styles + ); + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ name ] = value; + value = jQuery.css( elem, name ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( !rmargin.test( prefix ) ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && + ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || + jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function raf() { + if ( timerId ) { + window.requestAnimationFrame( raf ); + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = jQuery.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 13 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( jQuery.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + if ( percent < 1 && length ) { + return remaining; + } else { + deferred.resolveWith( elem, [ animation ] ); + return false; + } + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( jQuery.isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + jQuery.proxy( result.stop, result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + // attach callbacks from options + return animation.progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( jQuery.isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnotwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + // Go to the end state if fx are off or if document is hidden + if ( jQuery.fx.off || document.hidden ) { + opt.duration = 0; + + } else { + opt.duration = typeof opt.duration === "number" ? + opt.duration : opt.duration in jQuery.fx.speeds ? + jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Checks the timer has not already been removed + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + if ( timer() ) { + jQuery.fx.start(); + } else { + jQuery.timers.pop(); + } +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( !timerId ) { + timerId = window.requestAnimationFrame ? + window.requestAnimationFrame( raf ) : + window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.stop = function() { + if ( window.cancelAnimationFrame ) { + window.cancelAnimationFrame( timerId ); + } else { + window.clearInterval( timerId ); + } + + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + jQuery.nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + attrNames = value && value.match( rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + return tabindex ? + parseInt( tabindex, 10 ) : + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && elem.href ? + 0 : + -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + +var rclass = /[\t\r\n\f]/g; + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnotwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && + ( " " + curValue + " " ).replace( rclass, " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = jQuery.trim( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnotwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && + ( " " + curValue + " " ).replace( rclass, " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = jQuery.trim( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( type === "string" ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = value.match( rnotwhite ) || []; + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + getClass( elem ) + " " ).replace( rclass, " " ) + .indexOf( className ) > -1 + ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g, + rspaces = /[\x20\t\r\n\f]+/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, isFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + + // Handle most common string cases + ret.replace( rreturn, "" ) : + + // Handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup contextmenu" ).split( " " ), + function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; +} ); + +jQuery.fn.extend( { + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +} ); + + + + +support.focusin = "onfocusin" in window; + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = jQuery.now(); + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( jQuery.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && jQuery.type( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = jQuery.isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( i, elem ) { + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rts = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; + + if ( jQuery.isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match == null ? null : match; + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 13 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available, append data to url + if ( s.data ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add anti-cache in uncached url if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rts, "" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + + +jQuery._evalUrl = function( url ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + "throws": true + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( jQuery.isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -118,7 +120,7 @@ You can then use the instance to call whatever method you need.

    This Page

    @@ -151,12 +153,12 @@ You can then use the instance to call whatever method you need.

  • previous |
  • - + \ No newline at end of file diff --git a/docs/build/html/crypto.html b/docs/build/html/crypto.html new file mode 100644 index 0000000..379995a --- /dev/null +++ b/docs/build/html/crypto.html @@ -0,0 +1,627 @@ + + + + + + + + 9. windows.crypto – CryptoAPI — PythonForWindows 0.2 documentation + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +
    +

    9. windows.crypto – CryptoAPI

    +

    The windows.crypto module offers some wrappers arround the CryptoAPI.

    +

    The main goal of this module (for now) is providing simple encryption/decryption methods.

    +
    +

    9.1. Encryption

    +
    +

    Note

    +

    See sample Encryption demo

    +
    +
    +

    9.1.1. encrypt

    +
    +
    +windows.crypto.encrypt(cert_or_certlist, msg, algo=szOID_RSA_DES_EDE3_CBC('1.2.840.113549.3.7'), initvector=GenerateInitVector())[source]
    +

    Encrypt msg with the certificate(s) in cert_or_certlist using algo with the initial +vector initvector.

    +

    If geninitvector is left as it is, it will generate a random one.

    +

    Algorithms supported by GenerateInitVector are:

    +
    +
      +
    • szOID_OIWSEC_desCBC
    • +
    • szOID_RSA_DES_EDE3_CBC
    • +
    • szOID_NIST_AES128_CBC
    • +
    • szOID_NIST_AES192_CBC
    • +
    • szOID_NIST_AES256_CBC
    • +
    +
    + +++ + + + +
    Returns:bytearray: The encrypted message
    +
    + +
    +
    +

    9.1.2. decrypt

    +
    +
    +windows.crypto.decrypt(cert_store, encrypted)[source]
    +

    Try to decrypt the encrypted msg with any certificate in cert_store.

    +

    If there is no certificate able to decrypt the message Kernel32Error(winerror=0x8009200c) is raised.

    + +++ + + + +
    Returns:str: The decrypted message
    +
    + +
    +
    +

    9.1.3. import_pfx

    +
    +
    +windows.crypto.import_pfx(pfx, password=None, flags=36864L)[source]
    +

    Import the file pfx with the password.

    +

    default flags = PKCS12_NO_PERSIST_KEY | CRYPT_USER_KEYSET.

    +

    PKCS12_NO_PERSIST_KEY tells CryptoAPI to NOT save the keys in a on-disk container.

    + +++ + + + +
    Returns:EHCERTSTORE
    +
    + +
    +
    +
    +

    9.2. Certificate

    +
    +

    Note

    +

    See sample Certificate demo

    +
    +
    +

    9.2.1. CertificateContext

    +
    +
    +class windows.crypto.CertificateContext[source]
    +

    Represent a Certificate.

    +

    note: It is a pointer ctypes structure (PCCERT_CONTEXT)

    +
    +
    +chains
    +

    The list of chain context available for this certificate. Each elements of this list is a list of CertificateContext that should +go from the self certificate to a trusted certificate.

    + +++ + + + +
    Type:[[CertificateContext]] – A list of chain (list) of CertificateContext
    +
    + +
    +
    +contents
    +

    the object this pointer points to (read-write)

    +
    + +
    +
    +duplicate()[source]
    +

    Duplicate the certificate by incrementing the internal refcount. (see CertDuplicateCertificateContext)

    +

    note: The object returned is self

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +encoded
    +

    The encoded certificate.

    + +++ + + + +
    Type:bytearray
    +
    + +
    +
    +classmethod from_buffer(data)[source]
    +

    Create a CertificateContext from the buffer data

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +classmethod from_file(filename)[source]
    +

    Create a CertificateContext from the file filename

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +get_name(nametype=CERT_NAME_SIMPLE_DISPLAY_TYPE(0x4L), flags=0)[source]
    +

    Retrieve the subject or issuer name of the certificate. See CertGetNameStringA

    + +++ + + + +
    Returns:str
    +
    + +
    +
    +issuer
    +

    The name of the certificate’s issuer.

    + +++ + + + +
    Type:str
    +
    + +
    +
    +name
    +

    The name of the certificate.

    + +++ + + + +
    Type:str
    +
    + +
    +
    +raw_serial
    +

    The raw serial number of the certificate.

    + +++ + + + +
    Type:[int]: A list of int 0 <= x <= 255
    +
    + +
    +
    +serial
    +

    The string representation of the certificate’s serial.

    + +++ + + + +
    Type:str
    +
    + +
    +
    +store
    +

    The certificate store that contains the certificate

    + +++ + + + +
    Type:EHCERTSTORE
    +
    + +
    + +
    +
    +

    9.2.2. EHCERTSTORE

    +
    +
    +class windows.crypto.EHCERTSTORE[source]
    +

    A certificate store

    +
    +
    +add_certificate(certificate)[source]
    +

    Add a certificate to the store

    +
    + +
    +
    +certs
    +

    The certificates in the store

    + +++ + + + +
    Type:[CertificateContext] – A list of Certificate
    +
    + +
    +
    +classmethod from_file(filename)[source]
    +

    Create a new EHCERTSTORE from filename

    +
    + +
    +
    +classmethod from_system_store(store_name)[source]
    +

    Create a new EHCERTSTORE from system store``store_name`` +(see https://msdn.microsoft.com/en-us/library/windows/desktop/aa388136(v=vs.85).aspx)

    +
    + +
    +
    +classmethod new_in_memory()[source]
    +

    Create a new temporary EHCERTSTORE in memory

    +
    + +
    +
    +value
    +

    current value

    +
    + +
    + +
    +
    +

    9.2.3. CryptObject

    +
    +
    +class windows.crypto.CryptObject(filename, content_type=CERT_QUERY_CONTENT_FLAG_ALL(0x3ffeL))[source]
    +

    Extract information from an CryptoAPI object.

    +

    Current main use is extracting the signers certificates from a PE file.

    +
    +

    Warning

    +

    The methods and property of this class will problably change as I haven’t yet had the time +to try it out in real cases.

    +
    +
    +
    +cert
    +

    Return embded certificate number index.

    +

    note: not all embded certificate are directly used to sign the CryptObject.

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +get_cert(index=0)[source]
    +

    Return embded certificate number index.

    +

    note: not all embded certificate are directly used to sign the CryptObject.

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +get_signer_certificate(index=0)[source]
    +

    Return the certificate used for signer nb index

    + +++ + + + +
    Returns:CertificateContext
    +
    + +
    +
    +get_signer_data(index=0)[source]
    +

    Returns the signer informations for signer nb index

    + +++ + + + +
    Returns:CMSG_SIGNER_INFO
    +
    + +
    +
    +nb_cert
    +

    The number of certificate embded in the CryptObject

    + +++ + + + +
    Type:int
    +
    + +
    +
    +nb_signer
    +

    The number of signers for the CryptObject

    + +++ + + + +
    Type:int
    +
    + +
    + +
    +
    +

    9.2.4. CryptContext

    +
    +
    +class windows.crypto.CryptContext(pszContainer=None, pszProvider=None, dwProvType=0, dwFlags=0, retrycreate=False)[source]
    +

    A context manager arround CryptAcquireContextW & CryptReleaseContext

    +
    +
    +contents
    +

    the object this pointer points to (read-write)

    +
    + +
    + +
    +
    +
    +

    9.3. Generating componants

    +

    This module is used to generate selfsigned-certificates / keypair and pfx file.

    +
    +

    Note

    +

    See genkeys() in the sample Encryption demo

    +
    +
    +

    9.3.1. generate_selfsigned_certificate

    +
    +
    +windows.crypto.generation.generate_selfsigned_certificate(name='CN=DEFAULT', prov=None, key_info=None, flags=0, signature_algo=None)[source]
    +

    Generate a selfsigned certificate.

    +

    See https://msdn.microsoft.com/en-us/library/windows/desktop/aa376039(v=vs.85).aspx

    + +++ + + + +
    Returns:windows.crypto.CertificateContext
    +
    + +
    +
    +

    9.3.2. generate_key

    +
    +
    +windows.crypto.generation.generate_key(prov, keytype=AT_KEYEXCHANGE(0x1L), flags=CRYPT_EXPORTABLE(0x1L))[source]
    +

    Generate a keypair if type keytype.

    + +++ + + + +
    Returns:HCRYPTKEY
    +
    + +
    +
    +

    9.3.3. generate_pfx

    +
    +
    +windows.crypto.generation.generate_pfx(hstore, password=None)[source]
    +

    Generate a pfx protected by password contaning the certificates in hstore

    + +++ + + + +
    Returns:bytearray – The raw PFX
    +
    + +
    +
    +
    + + +
    +
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/docs/build/html/debug.html b/docs/build/html/debug.html index 78fcd29..8264542 100644 --- a/docs/build/html/debug.html +++ b/docs/build/html/debug.html @@ -6,7 +6,7 @@ - 7. windows.debug – Debugging — PythonForWindows 0.2 documentation + 7. windows.debug – Debugging — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -470,7 +472,7 @@ It is based on

    This Page

    @@ -503,12 +505,12 @@ It is based on
  • previous |
  • - + \ No newline at end of file diff --git a/docs/build/html/exception.html b/docs/build/html/exception.html index f405fd7..f925cc1 100644 --- a/docs/build/html/exception.html +++ b/docs/build/html/exception.html @@ -6,7 +6,7 @@ - 2.4. Exception and Context related structures — PythonForWindows 0.2 documentation + 2.4. Exception and Context related structures — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + + @@ -601,7 +602,7 @@ Most of the structures are the Windows structure with a prefix

    This Page

    @@ -634,13 +635,13 @@ Most of the structures are the Windows structure with a prefix previous | - - + + \ No newline at end of file diff --git a/docs/build/html/genindex.html b/docs/build/html/genindex.html index ffc0af2..56fbdb4 100644 --- a/docs/build/html/genindex.html +++ b/docs/build/html/genindex.html @@ -7,7 +7,7 @@ - Index — PythonForWindows 0.2 documentation + Index — PythonForWindows 0.2 documentation @@ -18,13 +18,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -77,1946 +79,1208 @@

    _

    - + +
    - -
    __init__() (windows.debug.Debugger method) -
    +

    A

    - + - + +
  • application_name (windows.winobject.network.FirewallRule attribute) +
  • +
  • attach() (windows.debug.Debugger class method) +
  • +
    - -
    action (windows.winobject.network.FirewallRule attribute) -
    +
    - -
    allocated_memory() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    application_name (windows.winobject.network.FirewallRule attribute) -
    - - -
    attach() (windows.debug.Debugger class method) -
    - -

    B

    - - + + +
    - -
    base (windows.native_exec.simple_x86.mem_access attribute) -
    +
    - -
    break_on_ret() (windows.debug.FunctionBP method) -
    - - -
    Breakpoint (class in windows.debug) -
    - -

    C

    - + - + +
  • CryptContext (class in windows.crypto) +
  • +
  • CryptObject (class in windows.crypto) +
  • +
  • current_profile_types (windows.winobject.network.Firewall attribute) +
  • +
  • CurrentProcess (class in windows.winobject.process) +
  • +
  • CurrentThread (class in windows.winobject.process) +
  • +
    - -
    Callback (class in windows.hooks) -
    +
    - -
    context_syswow (windows.winobject.process.WinThread attribute) -
    - - -
    control_accepted (windows.winobject.service.ServiceStatus attribute) -
    - - -
    create_console() (in module windows.utils) -
    - - -
    create_displacement() (in module windows.native_exec.simple_x86) -
    - - -
    create_file_from_handle() (in module windows.utils) -
    - - -
    create_function() (in module windows.native_exec) -
    - - -
    create_process() (in module windows.utils) -
    - - -
    create_thread() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    current_profile_types (windows.winobject.network.Firewall attribute) -
    - - -
    CurrentProcess (class in windows.winobject.process) -
    - - -
    CurrentThread (class in windows.winobject.process) -
    - -

    D

    - + - + +
  • duplicate() (windows.crypto.CertificateContext method) +
  • +
    - -
    DeadThread (class in windows.winobject.process) -
    +
    - -
    disable() (windows.hooks.IATHook method) -
    - - -
    disable_all_memory_breakpoints() (windows.debug.Debugger method) -
    - - -
    DisabledMemoryBreakpoint() (windows.debug.Debugger method) -
    - - -
    DisableWow64FsRedirection (class in windows.utils) -
    - - -
    disp (windows.native_exec.simple_x86.mem_access attribute) -
    - - -
    do_cpuid() (in module windows.native_exec.cpuid) -
    - - -
    dump() (windows.winobject.exception.ECONTEXT32 method) -
    - -
    - -
    (windows.winobject.exception.ECONTEXT64 method) -
    - - -
    (windows.winobject.exception.ECONTEXTWOW64 method) -
    - - -
    (windows.winobject.exception.EEXCEPTION_POINTERS method) -
    - -
    -

    E

    - + - + +
  • export_name (windows.pe_parse.PEFile attribute) +
  • +
  • exports (windows.pe_parse.PEFile attribute) +
  • +
  • extract_arguments() (windows.debug.FunctionBP method) +
  • +
    - -
    ECONTEXT32 (class in windows.winobject.exception) -
    +
    - -
    enable() (windows.hooks.IATHook method) -
    - - -
    enable_privilege() (in module windows.utils) -
    - - -
    enabled (windows.winobject.network.Firewall attribute) -
    - -
    - -
    (windows.winobject.network.FirewallRule attribute) -
    - -
    - -
    established (windows.winobject.network.TCP4Connection attribute) -
    - -
    - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    ExceptionAddress (windows.winobject.exception.EEXCEPTION_RECORD attribute) -
    - -
    - -
    (windows.winobject.exception.EEXCEPTION_RECORD32 attribute) -
    - - -
    (windows.winobject.exception.EEXCEPTION_RECORD64 attribute) -
    - -
    - -
    ExceptionCode (windows.winobject.exception.EEXCEPTION_RECORD attribute) -
    - -
    - -
    (windows.winobject.exception.EEXCEPTION_RECORD32 attribute) -
    - - -
    (windows.winobject.exception.EEXCEPTION_RECORD64 attribute) -
    - -
    - -
    execute() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    execute_64bits_code_from_syswow() (in module windows.syswow64) -
    - - -
    execute_python() (windows.winobject.process.WinProcess method) -
    - - -
    execute_python_unsafe() (windows.winobject.process.WinProcess method) -
    - - -
    exit() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.CurrentThread method) -
    - - -
    (windows.winobject.process.WinProcess method) -
    - - -
    (windows.winobject.process.WinThread method) -
    - -
    - -
    exit_code (windows.winobject.process.CurrentProcess attribute) -
    - -
    - -
    (windows.winobject.process.DeadThread attribute) -
    - - -
    (windows.winobject.process.WinProcess attribute) -
    - - -
    (windows.winobject.process.WinThread attribute) -
    - -
    - -
    export_name (windows.pe_parse.PEFile attribute) -
    - - -
    exports (windows.pe_parse.PEFile attribute) -
    - - -
    extract_arguments() (windows.debug.FunctionBP method) -
    - -

    F

    - + - + +
  • FunctionBP (class in windows.debug) +
  • +
    - -
    fields (windows.native_exec.cpuid.X86CpuidResult attribute) -
    +
    - -
    full_signature_information() (in module windows.wintrust) -
    - - -
    fullname (windows.winobject.process.LoadedModule attribute) -
    - - -
    func_result (windows.winobject.exception.ECONTEXT32 attribute) -
    - -
    - -
    (windows.winobject.exception.ECONTEXT64 attribute) -
    - - -
    (windows.winobject.exception.ECONTEXTWOW64 attribute) -
    - -
    - -
    FunctionBP (class in windows.debug) -
    - -

    G

    - + - + +
  • get_memory_breakpoint_at() (windows.debug.Debugger method) +
  • +
  • get_name() (windows.crypto.CertificateContext method) +
  • +
  • get_proc_family_model() (in module windows.native_exec.cpuid) +
  • +
  • get_signer_certificate() (windows.crypto.CryptObject method) +
  • +
  • get_signer_data() (windows.crypto.CryptObject method) +
  • +
  • get_vendor_id() (in module windows.native_exec.cpuid) +
  • +
  • GetPEFile() (in module windows.pe_parse) +
  • +
  • grouping (windows.winobject.network.FirewallRule attribute) +
  • +
    - -
    generate_syswow64_call() (in module windows.syswow64) -
    +
    - -
    get_mapped_filename() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    get_memory_breakpoint_at() (windows.debug.Debugger method) -
    - - -
    get_proc_family_model() (in module windows.native_exec.cpuid) -
    - - -
    get_vendor_id() (in module windows.native_exec.cpuid) -
    - - -
    GetPEFile() (in module windows.pe_parse) -
    - - -
    grouping (windows.winobject.network.FirewallRule attribute) -
    - -

    H

    - - + + +
    - -
    Handle (class in windows.winobject.handle) -
    +
    - -
    handles (windows.winobject.system.System attribute) -
    - - -
    HXBreakpoint (class in windows.debug) -
    - -

    I

    - + - + +
  • issuer (windows.crypto.CertificateContext attribute) +
  • +
    - -
    IATEntry (class in windows.pe_parse) -
    +
    - -
    interface_types (windows.winobject.network.FirewallRule attribute) -
    - - -
    ipv4 (windows.winobject.network.Network attribute) -
    - - -
    ipv6 (windows.winobject.network.Network attribute) -
    - - -
    is_amd_proc() (in module windows.native_exec.cpuid) -
    - - -
    is_elevated (windows.winobject.process.Token attribute) -
    - - -
    is_exit (windows.winobject.process.CurrentProcess attribute) -
    - -
    - -
    (windows.winobject.process.DeadThread attribute) -
    - - -
    (windows.winobject.process.WinProcess attribute) -
    - - -
    (windows.winobject.process.WinThread attribute) -
    - -
    - -
    is_intel_proc() (in module windows.native_exec.cpuid) -
    - - -
    is_signed() (in module windows.wintrust) -
    - - -
    is_wow_64 (windows.winobject.process.CurrentProcess attribute) -
    - -
    - -
    (windows.winobject.process.WinProcess attribute) -
    - -
    -

    K

    - +
    - -
    KeyValue (class in windows.winobject.registry) -
    - -

    L

    - + - + +
  • LocalDebugger (class in windows.debug) +
  • +
  • LogicalDrive (class in windows.winobject.volume) +
  • +
  • LogicalDrive.name (in module windows.winobject.volume) +
  • +
  • logicaldrives (windows.winobject.system.System attribute) +
  • +
  • loop() (windows.debug.Debugger method) +
  • +
    - -
    LdrLoadDll_32_to_64() (in module windows.syswow64) -
    +
    - -
    local_port (windows.winobject.network.FirewallRule attribute) -
    - -
    - -
    (windows.winobject.network.TCP4Connection attribute) -
    - - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    LocalDebugger (class in windows.debug) -
    - - -
    LogicalDrive (class in windows.winobject.volume) -
    - - -
    LogicalDrive.name (in module windows.winobject.volume) -
    - - -
    logicaldrives (windows.winobject.system.System attribute) -
    - - -
    loop() (windows.debug.Debugger method) -
    - -

    M

    - - + + +
    - -
    mem() (in module windows.native_exec.simple_x86) -
    +
    - -
    MemoryBreakpoint (class in windows.debug) -
    - - -
    modules (windows.winobject.process.PEB attribute) -
    - -

    N

    - - + +
  • nb_cert (windows.crypto.CryptObject attribute) +
  • +
  • nb_signer (windows.crypto.CryptObject attribute) +
  • + +
    - -
    name (windows.winobject.handle.Handle attribute) -
    +
    - -
    NtGetContextThread_32_to_64() (in module windows.syswow64) -
    - - -
    NtQueryInformationProcess_32_to_64() (in module windows.syswow64) -
    - - -
    NtQueryInformationThread_32_to_64() (in module windows.syswow64) -
    - - -
    NtQueryVirtualMemory_32_to_64() (in module windows.syswow64) -
    - - -
    NtSetContextThread_32_to_64() (in module windows.syswow64) -
    - -

    O

    - + - + +
    - -
    on_create_process() (windows.debug.Debugger method) -
    +
    - -
    on_output_debug_string() (windows.debug.Debugger method) -
    - - -
    on_rip() (windows.debug.Debugger method) -
    - - -
    on_single_step() (windows.debug.Debugger method) -
    - - -
    on_unload_dll() (windows.debug.Debugger method) -
    - - -
    open_subkey() (windows.winobject.registry.PyHKey method) -
    - - -
    owner (windows.winobject.process.CurrentThread attribute) -
    - -
    - -
    (windows.winobject.process.WinThread attribute) -
    - -
    -

    P

    - + - + +
  • processes (windows.winobject.system.System attribute) +
  • +
  • product_type (windows.winobject.system.System attribute) +
  • +
  • protocol (windows.winobject.network.FirewallRule attribute) +
  • +
  • PyHKey (class in windows.winobject.registry) +
  • +
  • PyHKey.__call__() (in module windows.winobject.registry) +
  • +
  • PyHKey.__getitem__() (in module windows.winobject.registry) +
  • +
  • PyHKey.__setitem__() (in module windows.winobject.registry) +
  • +
    - -
    path (windows.winobject.volume.LogicalDrive attribute) -
    +
    - -
    ppid (windows.winobject.process.CurrentProcess attribute) -
    - -
    - -
    (windows.winobject.process.WinProcess attribute) -
    - -
    - -
    prefix (windows.native_exec.simple_x86.mem_access attribute) -
    - - -
    process (windows.winobject.handle.Handle attribute) -
    - -
    - -
    (windows.winobject.service.ServiceA attribute) -
    - -
    - -
    processes (windows.winobject.system.System attribute) -
    - - -
    product_type (windows.winobject.system.System attribute) -
    - - -
    protocol (windows.winobject.network.FirewallRule attribute) -
    - - -
    PyHKey (class in windows.winobject.registry) -
    - - -
    PyHKey.__call__() (in module windows.winobject.registry) -
    - - -
    PyHKey.__getitem__() (in module windows.winobject.registry) -
    - - -
    PyHKey.__setitem__() (in module windows.winobject.registry) -
    - -

    Q

    - + +
    - -
    query_memory() (windows.winobject.process.CurrentProcess method) -
    +

    R

    - + - + +
  • remove_hook() (windows.pe_parse.IATEntry method) +
  • +
  • restore_all_memory_breakpoints() (windows.debug.Debugger method) +
  • +
  • resume() (windows.winobject.process.WinThread method) +
  • +
  • ret_trigger() (windows.debug.FunctionBP method) +
  • +
  • rules (windows.winobject.network.Firewall attribute) +
  • +
    - -
    raw (windows.winobject.exception.EEflags attribute) -
    +
    - -
    regs() (windows.winobject.exception.ECONTEXT32 method) -
    - -
    - -
    (windows.winobject.exception.ECONTEXT64 method) -
    - - -
    (windows.winobject.exception.ECONTEXTWOW64 method) -
    - -
    - -
    remote_addr (windows.winobject.network.TCP4Connection attribute) -
    - -
    - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    remote_address (windows.winobject.network.FirewallRule attribute) -
    - - -
    remote_host (windows.winobject.network.TCP4Connection attribute) -
    - -
    - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    remote_port (windows.winobject.network.FirewallRule attribute) -
    - -
    - -
    (windows.winobject.network.TCP4Connection attribute) -
    - - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    remote_proto (windows.winobject.network.TCP4Connection attribute) -
    - -
    - -
    (windows.winobject.network.TCP6Connection attribute) -
    - -
    - -
    remove_hook() (windows.pe_parse.IATEntry method) -
    - - -
    restore_all_memory_breakpoints() (windows.debug.Debugger method) -
    - - -
    resume() (windows.winobject.process.WinThread method) -
    - - -
    ret_trigger() (windows.debug.FunctionBP method) -
    - - -
    rules (windows.winobject.network.Firewall attribute) -
    - -

    S

    - + - + +
  • start_address (windows.winobject.process.WinThread attribute) +
  • +
  • state (windows.winobject.service.ServiceStatus attribute) +
  • +
  • status (windows.winobject.service.ServiceA attribute) +
  • +
  • store (windows.crypto.CertificateContext attribute) +
  • +
  • str (windows.winobject.process.WinUnicodeString attribute) +
  • +
  • subkeys (windows.winobject.registry.PyHKey attribute) +
  • +
  • suspend() (windows.winobject.process.WinThread method) +
  • +
  • System (class in windows.winobject.system) +
  • +
  • Syswow64ApiProxy (class in windows.syswow64) +
  • +
    - -
    scale (windows.native_exec.simple_x86.mem_access attribute) -
    +
    - -
    signed (windows.wintrust.SignatureData attribute) -
    - - -
    single_step() (windows.debug.Debugger method) -
    - -
    - -
    (windows.debug.LocalDebugger method) -
    - -
    - -
    sp (windows.winobject.exception.ECONTEXT32 attribute) -
    - -
    - -
    (windows.winobject.exception.ECONTEXT64 attribute) -
    - - -
    (windows.winobject.exception.ECONTEXTWOW64 attribute) -
    - -
    - -
    start_address (windows.winobject.process.WinThread attribute) -
    - - -
    state (windows.winobject.service.ServiceStatus attribute) -
    - - -
    status (windows.winobject.service.ServiceA attribute) -
    - - -
    str (windows.winobject.process.WinUnicodeString attribute) -
    - - -
    subkeys (windows.winobject.registry.PyHKey attribute) -
    - - -
    suspend() (windows.winobject.process.WinThread method) -
    - - -
    System (class in windows.winobject.system) -
    - - -
    Syswow64ApiProxy (class in windows.syswow64) -
    - -

    T

    - + - + +
    - -
    TCP4Connection (class in windows.winobject.network) -
    +
    - -
    token (windows.winobject.process.CurrentProcess attribute) -
    - -
    - -
    (windows.winobject.process.WinProcess attribute) -
    - -
    - -
    transform_type_to_remote32bits() (in module windows.remotectypes) -
    - - -
    transform_type_to_remote64bits() (in module windows.remotectypes) -
    - - -
    trigger() (windows.debug.Breakpoint method) -
    - -
    - -
    (windows.debug.FunctionBP method) -
    - - -
    (windows.debug.HXBreakpoint method) -
    - - -
    (windows.debug.MemoryBreakpoint method) -
    - -
    - -
    try_generate_stub_target() (in module windows.syswow64) -
    - - -
    type (windows.winobject.handle.Handle attribute) -
    - -
    - -
    (windows.winobject.registry.KeyValue attribute) -
    - - -
    (windows.winobject.service.ServiceStatus attribute) -
    - - -
    (windows.winobject.volume.LogicalDrive attribute) -
    - -
    -

    U

    - +
    - -
    username (windows.winobject.process.Token attribute) -
    - -

    V

    - + - + +
  • VirtualProtected (class in windows.utils) +
  • +
    - -
    value (windows.winobject.network.Firewall attribute) -
    +
    - -
    virtual_alloc() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    virtual_free() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    virtual_protect() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    virtual_protected() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    VirtualProtected (class in windows.utils) -
    - -

    W

    - + - + +
    - -
    wait() (windows.winobject.process.CurrentProcess method) -
    +
    - -
    windows.winobject.registry (module) -
    - - -
    windows.winobject.service (module) -
    - - -
    windows.winobject.volume (module) -
    - - -
    windows.winobject.wmi (module) -
    - - -
    windows.winproxy (module) -
    - - -
    windows.wintrust (module) -
    - - -
    WinProcess (class in windows.winobject.process) -
    - - -
    WinThread (class in windows.winobject.process) -
    - - -
    WinUnicodeString (class in windows.winobject.process) -
    - - -
    wmi (windows.winobject.system.System attribute) -
    - - -
    WmiRequester (class in windows.winobject.wmi) -
    - - -
    write_byte() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    write_dword() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    write_memory() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    write_qword() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    - -
    write_short() (windows.winobject.process.CurrentProcess method) -
    - -
    - -
    (windows.winobject.process.WinProcess method) -
    - -
    -

    X

    - - + +
    - -
    x64_cpuid() (in module windows.native_exec.cpuid) -
    - - -
    x86_cpuid() (in module windows.native_exec.cpuid) -
    - -
    - -
    X86CpuidResult (class in windows.native_exec.cpuid) -
    - -
    @@ -2052,12 +1316,12 @@
  • modules |
  • - + \ No newline at end of file diff --git a/docs/build/html/handle.html b/docs/build/html/handle.html index 1a8f421..b471728 100644 --- a/docs/build/html/handle.html +++ b/docs/build/html/handle.html @@ -6,7 +6,7 @@ - 2.10. Handle – Processes handles — PythonForWindows 0.2 documentation + 2.10. Handle – Processes handles — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + + @@ -64,6 +65,12 @@
    class windows.winobject.handle.Handle[source]

    A handle of the system

    +
    +
    +infos
    +

    TODO: DOC

    +
    +
    local_handle
    @@ -139,7 +146,7 @@

    This Page

    @@ -172,13 +179,13 @@
  • previous |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/iat_hook.html b/docs/build/html/iat_hook.html index c6cfe65..f4a5903 100644 --- a/docs/build/html/iat_hook.html +++ b/docs/build/html/iat_hook.html @@ -6,7 +6,7 @@ - 9. IAT hooking — PythonForWindows 0.2 documentation + 10. IAT hooking — PythonForWindows 0.2 documentation @@ -17,15 +17,17 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - - + + + + @@ -53,13 +55,13 @@
    -

    9. IAT hooking

    +

    10. IAT hooking

    Note

    See sample IAT hooking

    -

    9.1. Putting an IAT hook

    +

    10.1. Putting an IAT hook

    To setup your IAT hook you just need:

      @@ -88,9 +90,9 @@
    -

    9.2. Hook protocol

    +

    10.2. Hook protocol

    -

    9.2.1. Callback arguments

    +

    10.2.1. Callback arguments

    A hook callback must have the same number of argument as the hooked API, PLUS a last argument real_function.

    The real_function argument is a callable that represent the hooked API, it can be called in two ways:

    @@ -111,7 +113,7 @@

    A hook callback must also embed some Type Information

    -

    9.2.2. Callback type information

    +

    10.2.2. Callback type information

    In order make the magic behind hook callback, ctypes needs to have type information about the API parameters.

    There is (again) two ways to give those informations to your hook callback. Both techniques use a decorator to setup type information to the callback.

    @@ -150,7 +152,7 @@
    -

    9.3. windows.hooks

    +

    10.3. windows.hooks

    class windows.hooks.Callback(*types)[source]
    @@ -186,28 +188,28 @@ \ No newline at end of file diff --git a/docs/build/html/index.html b/docs/build/html/index.html index fc44e46..e566aa3 100644 --- a/docs/build/html/index.html +++ b/docs/build/html/index.html @@ -6,7 +6,7 @@ - Welcome to PythonForWindows’s documentation! — PythonForWindows 0.2 documentation + Welcome to PythonForWindows’s documentation! — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -39,7 +41,7 @@
  • next |
  • - +
    @@ -102,29 +104,35 @@
  • 8.2. Implementing a COM interface
  • -
  • 9. IAT hooking
  • \ No newline at end of file diff --git a/docs/build/html/internals.html b/docs/build/html/internals.html index 2138f9e..475479c 100644 --- a/docs/build/html/internals.html +++ b/docs/build/html/internals.html @@ -6,7 +6,7 @@ - 11. Internals — PythonForWindows 0.2 documentation + 12. Internals — PythonForWindows 0.2 documentation @@ -17,15 +17,17 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - - + + + + @@ -53,10 +55,10 @@
    -

    11. Internals

    +

    12. Internals

    Because some horrible hacks of PythonForWindows are hidden and I wanted to talk about it.

    -

    11.1. remotectypes.py

    +

    12.1. remotectypes.py

    Performing parsing of PEB / PE in remote process may be painful and i didn’t want to have two versions of all my parsing code.

    So I made a wrapper around ctypes that is able to do two things:

    @@ -107,7 +109,7 @@ The class.__init__ accept two arguments:

    I am pretty sure that this code does NOT handle all the cases, so it might break some day.

    -

    11.2. syswow64.py – Crossing the heaven gate

    +

    12.2. syswow64.py – Crossing the heaven gate

    One of my goal with PythonForWindows is to have some abstraction of the bitness of the processes. It means being able to work on a 32bits Python or a 64bits Python.

    In the case of a 32bits python on a 64bits system (SysWow64) it’s not trivial to perform operation on @@ -212,23 +214,23 @@ With these information we are able to know

    Table Of Contents

    \ No newline at end of file diff --git a/docs/build/html/native_exec.html b/docs/build/html/native_exec.html index 7ce3a04..d61b3e4 100644 --- a/docs/build/html/native_exec.html +++ b/docs/build/html/native_exec.html @@ -6,7 +6,7 @@ - 3. windows.native_exec – Native Code Execution — PythonForWindows 0.2 documentation + 3. windows.native_exec – Native Code Execution — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - +
    @@ -495,7 +497,7 @@ the end of your

    This Page

    @@ -528,12 +530,12 @@ the end of your previous | - +
    \ No newline at end of file diff --git a/docs/build/html/network.html b/docs/build/html/network.html index 3a8817e..99ab0c1 100644 --- a/docs/build/html/network.html +++ b/docs/build/html/network.html @@ -6,7 +6,7 @@ - 2.6. Network — PythonForWindows 0.2 documentation + 2.6. Network — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + +
    @@ -576,7 +577,7 @@ Equals remote_port

    This Page

    @@ -609,13 +610,13 @@ Equals remote_port previous | - - + + \ No newline at end of file diff --git a/docs/build/html/process.html b/docs/build/html/process.html index 7ac2288..0a88d46 100644 --- a/docs/build/html/process.html +++ b/docs/build/html/process.html @@ -6,7 +6,7 @@ - 2.1. Processes and Threads — PythonForWindows 0.2 documentation + 2.1. Processes and Threads — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + + @@ -374,20 +375,6 @@
    -
    -
    -token
    -

    The token of the process

    - --- - - - -
    Type:Token
    -
    -
    virtual_alloc(size, prot=PAGE_EXECUTE_READWRITE(0x40L))[source]
    @@ -928,20 +915,6 @@ raises an exception if the remote thread raised one

    -
    -
    -token
    -

    The token of the process

    - --- - - - -
    Type:Token
    -
    -
    virtual_alloc(size, prot=PAGE_EXECUTE_READWRITE(0x40L))[source]
    @@ -1286,7 +1259,7 @@ raises an exception if the remote thread raised one

    integrity
    -

    Return the integrity level of a process

    +

    Return the integrity level of a token

    @@ -1495,7 +1468,7 @@ The
    -class windows.pe_parse.PEFile
    +class windows.pe_parse.PEFile(target, baseaddr, targetedbitness, transformers)[source]

    Represent a PE loaded in a process (current or remote)

    @@ -1545,7 +1518,7 @@ of
    -class windows.pe_parse.IATEntry
    +class windows.pe_parse.IATEntry[source]

    Represent an entry in the IAT of a module Can be used to get resolved value and setup hook

    @@ -1582,13 +1555,13 @@ Can be used to get resolved value and setup hook

    -remove_hook()
    +remove_hook()[source]

    Remove the hook on the entry

    -set_hook(callback, types=None)
    +set_hook(callback, types=None)[source]

    Setup a hook on the entry and return it. You MUST keep a reference to the hook while the hook is enabled.

    @@ -1658,7 +1631,7 @@ You MUST keep a reference to the hook while the hook is enabled.

    This Page

    @@ -1691,13 +1664,13 @@ You MUST keep a reference to the hook while the hook is enabled.

  • previous |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/py-modindex.html b/docs/build/html/py-modindex.html index 27c6c45..c9a034c 100644 --- a/docs/build/html/py-modindex.html +++ b/docs/build/html/py-modindex.html @@ -6,7 +6,7 @@ - Python Module Index — PythonForWindows 0.2 documentation + Python Module Index — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -38,7 +40,7 @@
  • modules |
  • - + @@ -54,8 +56,8 @@ w -
    - +
     
    + @@ -66,112 +68,122 @@ - - + + + + + + - - - - - - - - - - - - - - - - - - - -
     
    w
        +     windows.com
        +     + windows.crypto +
        + windows.crypto.generation +
        windows.debug
        +     windows.hooks
        +     windows.native_exec
        +     windows.native_exec.cpuid
        +     windows.native_exec.nativeutils
        +     windows.native_exec.simple_x64
        +     windows.native_exec.simple_x86
        +     windows.pe_parse
        +     windows.remotectypes
        +     windows.syswow64
        +     windows.utils
        +     windows.winobject.exception
        +     windows.winobject.handle
        +     windows.winobject.network
        +     windows.winobject.process
        +     windows.winobject.registry
        +     windows.winobject.service
        +     windows.winobject.volume
        +     windows.winobject.wmi
        +     windows.winproxy
        +     windows.wintrust
    @@ -205,12 +217,12 @@
  • modules |
  • - + \ No newline at end of file diff --git a/docs/build/html/registry.html b/docs/build/html/registry.html index 6c3c4c2..9601b83 100644 --- a/docs/build/html/registry.html +++ b/docs/build/html/registry.html @@ -6,7 +6,7 @@ - 2.5. Registry — PythonForWindows 0.2 documentation + 2.5. Registry — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + + @@ -212,7 +213,7 @@

    This Page

    @@ -245,13 +246,13 @@
  • previous |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/sample.html b/docs/build/html/sample.html index 8e6f38a..742f9b7 100644 --- a/docs/build/html/sample.html +++ b/docs/build/html/sample.html @@ -6,7 +6,7 @@ - 12. Samples of code — PythonForWindows 0.2 documentation + 13. Samples of code — PythonForWindows 0.2 documentation @@ -17,14 +17,16 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + + @@ -49,12 +51,14 @@
    -

    12. Samples of code

    +

    13. Samples of code

    +
    +

    13.1. Processes

    -

    12.1. windows.current_process

    +

    13.1.1. windows.current_process

    import sys
     import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.native_exec.simple_x86 as x86
    @@ -115,31 +119,31 @@ Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
     
    -

    12.2. Remote process : WinProcess

    +

    13.1.2. Remote process : WinProcess

    import sys
     import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.native_exec.simple_x86 as x86
     import windows.native_exec.simple_x64 as x64
     
    -print("Creating a calc")
    -calc = windows.utils.create_process(r"C:\windows\system32\calc.exe")
    +print("Creating a notepad") ## Replaced calc.exe by notepad.exe cause of windows 10.
    +notepad = windows.utils.create_process(r"C:\windows\system32\notepad.exe")
     # You don't need to do that in our case, but it's useful to now
    -print("Looking for calcs in the processes")
    -all_calcs = [proc for proc in windows.system.processes if proc.name == "calc.exe"]
    -print("They are currently <{0}> calcs running on the system".format(len(all_calcs)))
    +print("Looking for notepads in the processes")
    +all_notepads = [proc for proc in windows.system.processes if proc.name == "notepad.exe"]
    +print("They are currently <{0}> notepads running on the system".format(len(all_notepads)))
     
    -print("Let's play with our calc: <{calc}>".format(calc=calc))
    -print("Our calc pid is {calc.pid}".format(calc=calc))
    -print("Our calc is a <{calc.bitness}> bits process".format(calc=calc))
    -print("Our calc is a SysWow64 process ? <{calc.is_wow_64}>".format(calc=calc))
    -print("Our calc have threads ! <{calc.threads}>".format(calc=calc))
    +print("Let's play with our notepad: <{notepad}>".format(notepad=notepad))
    +print("Our notepad pid is {notepad.pid}".format(notepad=notepad))
    +print("Our notepad is a <{notepad.bitness}> bits process".format(notepad=notepad))
    +print("Our notepad is a SysWow64 process ? <{notepad.is_wow_64}>".format(notepad=notepad))
    +print("Our notepad have threads ! <{notepad.threads}>".format(notepad=notepad))
     
     # PEB STUFF
    -peb = calc.peb
    -print("Exploring our calc PEB ! {peb}".format(peb=peb))
    +peb = notepad.peb
    +print("Exploring our notepad PEB ! {peb}".format(peb=peb))
     print("Command line is {peb.commandline}".format(peb=peb))
     modules = peb.modules
     print("Here are 3 loaded modules: {0}".format(modules[:3]))
    @@ -148,19 +152,19 @@ Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
     
     # Remote alloc / read / write
     
    -print("Allocating memory in our calc")
    -addr = calc.virtual_alloc(0x1000)
    +print("Allocating memory in our notepad")
    +addr = notepad.virtual_alloc(0x1000)
     print("Allocated memory is at <{0}>".format(hex(addr)))
     print("Writing 'SOME STUFF' in allocated memory")
    -calc.write_memory(addr, "SOME STUFF")
    -print("Reading allocated memory : <{0}>".format(repr(calc.read_memory(addr, 20))))
    +notepad.write_memory(addr, "SOME STUFF")
    +print("Reading allocated memory : <{0}>".format(repr(notepad.read_memory(addr, 20))))
     
     
     # Remote Execution
     
    -print("Execution some native code in our calc (write 0x424242 at allocated address + return 0x1337)")
    +print("Execution some native code in our notepad (write 0x424242 at allocated address + return 0x1337)")
     
    -if calc.bitness == 32:
    +if notepad.bitness == 32:
         # Let's generate some native code
         code =  x86.MultipleInstr()
         code += x86.Mov(x86.deref(addr), 0x42424242)
    @@ -174,19 +178,19 @@ Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         code += x64.Ret()
     
     print("Executing native code !")
    -t = calc.execute(code.get_code())
    +t = notepad.execute(code.get_code())
     t.wait()
     print("Return code = {0}".format(hex(t.exit_code)))
    -print("Reading allocated memory : <{0}>".format(repr(calc.read_memory(addr, 20))))
    +print("Reading allocated memory : <{0}>".format(repr(notepad.read_memory(addr, 20))))
     
     print("Executing python code !")
     # Make 'windows' importable in remote python
    -calc.execute_python("import sys; sys.path.append(r'{0}')".format(sys.path[-1]))
    +notepad.execute_python("import sys; sys.path.append(r'{0}')".format(sys.path[-1]))
     
    -calc.execute_python("import windows")
    -# Let's write in the calc 'current_process' memory :)
    -calc.execute_python("addr = {addr}; windows.current_process.write_memory(addr, 'HELLO FROM CALC')".format(addr=addr))
    -print("Reading allocated memory : <{0}>".format(repr(calc.read_memory(addr, 20))))
    +notepad.execute_python("import windows")
    +# Let's write in the notepad 'current_process' memory :)
    +notepad.execute_python("addr = {addr}; windows.current_process.write_memory(addr, 'HELLO FROM notepad')".format(addr=addr))
    +print("Reading allocated memory : <{0}>".format(repr(notepad.read_memory(addr, 20))))
     
     # python_execute is 'safe':
     # - it waits for the thread completion
    @@ -194,13 +198,13 @@ Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
     
     try:
         print("Trying to import in remote module 'FAKE_MODULE'")
    -    calc.execute_python("def func():\n   import FAKE_MODULE\nfunc()")
    +    notepad.execute_python("def func():\n   import FAKE_MODULE\nfunc()")
     except windows.injection.RemotePythonError as e:
         print("Remote ERROR !")
         print(e)
     
    -print("That's all ! killing the calc")
    -calc.exit()
    +print("That's all ! killing the notepad")
    +notepad.exit()
     
     
     
    @@ -211,28 +215,28 @@ Reading memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
     

    Output:

    -
    (cmd λ) python.exe remote_calc.py
    -Creating a calc
    -Looking for calcs in the processes
    -They are currently <1> calcs running on the system
    -Let's play with our calc: <<WinProcess "calc.exe" pid 8052 at 0x27bd5d0>>
    -Our calc pid is 8052
    -Our calc is a <32> bits process
    -Our calc is a SysWow64 process ? <True>
    -Our calc have threads ! <[<WinThread 8552 owner "calc.exe" at 0x27f7f30>, <WinThread 3464 owner "calc.exe" at 0x27f7f80>, <WinThread 3840 owner "calc.exe" at 0x27fa030>]>
    -Exploring our calc PEB ! <windows.winobject.RemotePEB object at 0x026DDD00>
    -Command line is <RemoteWinUnicodeString ""C:\windows\system32\calc.exe"" at 0x26ddee0>
    -Here are 3 loaded modules: [<RemoteLoadedModule "calc.exe" at 0x26dde40>, <RemoteLoadedModule "ntdll.dll" at 0x26ddf30>, <RemoteLoadedModule "kernel32.dll" at 0x26ddc60>]
    -Allocating memory in our calc
    -Allocated memory is at <0x5c90000>
    +
    (cmd λ) python.exe remote_process.py
    +Creating a notepad
    +Looking for notepads in the processes
    +They are currently <1> notepads running on the system
    +Let's play with our notepad: <<WinProcess "notepad.exe" pid 2044 at 0x40ce850>>
    +Our notepad pid is 2044
    +Our notepad is a <32> bits process
    +Our notepad is a SysWow64 process ? <True>
    +Our notepad have threads ! <[<WinThread 7700 owner "notepad.exe" at 0x41faee0>, <WinThread 7264 owner "notepad.exe" at 0x41faf30>, ...]>
    +Exploring our notepad PEB ! <windows.winobject.process.RemotePEB object at 0x03F6CDA0>
    +Command line is <RemoteWinUnicodeString ""C:\windows\system32\notepad.exe"" at 0x3f6cf80>
    +Here are 3 loaded modules: [<RemoteLoadedModule "notepad.exe" at 0x3f6cf30>, <RemoteLoadedModule "ntdll.dll" at 0x3f6ce40>, <RemoteLoadedModule "kernel32.dll" at 0x3f6cee0>]
    +Allocating memory in our notepad
    +Allocated memory is at <0x6f80000>
     Writing 'SOME STUFF' in allocated memory
     Reading allocated memory : <'SOME STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'>
    -Execution some native code in our calc (write 0x424242 at allocated address + return 0x1337
    +Execution some native code in our notepad (write 0x424242 at allocated address + return 0x1337)
     Executing native code !
     Return code = 0x1337L
     Reading allocated memory : <'BBBB STUFF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'>
     Executing python code !
    -Reading allocated memory : <'HELLO FROM CALC\x00\x00\x00\x00\x00'>
    +Reading allocated memory : <'HELLO FROM notepad\x00\x00'>
     Trying to import in remote module 'FAKE_MODULE'
     Remote ERROR !
     Traceback (most recent call last):
    @@ -240,15 +244,15 @@ File "<string>", line 3, in <module>
     File "<string>", line 2, in func
     ImportError: No module named FAKE_MODULE
     
    -That's all ! killing the calc
    +That's all ! killing the notepad
     
    -

    12.3. PEB exploration

    +

    13.1.3. PEB exploration

    import sys
     import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     
    @@ -315,11 +319,98 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     
    -
    -

    12.4. windows.system

    +
    +

    13.1.4. IAT hooking

    import sys
     import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +
    +import _winreg
    +import windows
    +
    +# Here is a demo of IAT hooking in python
    +# We will hook the 'RegOpenKeyExA' entry of Python27.dll because it is easy to trigger !
    +
    +# First: let's create our hook
    +# windows.hooks.RegOpenKeyExACallback is generated based on windows.generated_def.winfuncs
    +@windows.hooks.RegOpenKeyExACallback
    +def open_reg_hook(hKey, lpSubKey, ulOptions, samDesired, phkResult, real_function):
    +    print("<in hook> Hook called | hKey = {0} | lpSubKey = <{1}>".format(hex(hKey), lpSubKey.value))
    +    # Our hook can choose to call the real_function or not
    +    if "SECRET" in lpSubKey.value:
    +        print("<in hook> Secret key asked, returning magic handle 0x12345678")
    +        # We must respect the hooked method return-value interface
    +        phkResult[0] = 0x12345678
    +        return 0
    +    if "FAIL" in lpSubKey.value:
    +        print("<in hook> Asked for a failing key: returning 0x2a")
    +        return 42
    +    print("<in hook> Non-secret key : calling normal function")
    +    return real_function()
    +
    +
    +# Get the peb of our process
    +peb = windows.current_process.peb
    +
    +# Get the pythonxx.dll module
    +pythondll_module = [m for m in peb.modules if m.name.startswith("python") and m.name.endswith(".dll")][0]
    +
    +# Get the iat entries for DLL advapi32.dll
    +adv_imports = pythondll_module.pe.imports['advapi32.dll']
    +
    +# Get RegOpenKeyExA iat entry
    +RegOpenKeyExA_iat = [n for n in adv_imports if n.name == "RegOpenKeyExA"][0]
    +
    +# Setup our hook
    +RegOpenKeyExA_iat.set_hook(open_reg_hook)
    +
    +# Use python native module _winreg that call 'RegOpenKeyExA'
    +print("Asking for <MY_SECRET_KEY>")
    +v = _winreg.OpenKey(1234567, "MY_SECRET_KEY")
    +print("Result = " + hex(v.handle))
    +
    +print("")
    +print("Asking for <MY_FAIL_KEY>")
    +try:
    +    v = _winreg.OpenKey(1234567, "MY_FAIL_KEY")
    +    print("Result = " + hex(v.handle))
    +except WindowsError as e:
    +    print(repr(e))
    +
    +print("")
    +print("Asking for <HKEY_CURRENT_USER/Software>")
    +try:
    +    v = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software")
    +    print("Result = " + hex(v.handle))
    +except WindowsError as e:
    +    print(repr(e))
    +
    +
    +

    Output:

    +
    (cmd λ) python iat_hook.py
    +Asking for <MY_SECRET_KEY>
    +<in hook> Hook called | hKey = 0x12d687 | lpSubKey = <MY_SECRET_KEY>
    +<in hook> Secret key asked, returning magic handle 0x12345678
    +Result = 0x12345678
    +
    +Asking for <MY_FAIL_KEY>
    +<in hook> Hook called | hKey = 0x12d687 | lpSubKey = <MY_FAIL_KEY>
    +<in hook> Asked for a failing key: returning 0x2a
    +WindowsError(42, 'Windows Error 0x2A')
    +
    +Asking for <HKEY_CURRENT_USER/Software>
    +<in hook> Hook called | hKey = 0x80000001L | lpSubKey = <Software>
    +<in hook> Non-secret key : calling normal function
    +Result = 0x108
    +
    +
    +
    +
    +
    +

    13.2. windows.system

    +
    import sys
    +import os.path
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     system = windows.system
    @@ -418,98 +509,12 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     
    -
    -

    12.5. IAT hooking

    -
    import sys
    -import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    -
    -import _winreg
    -import windows
    -
    -# Here is a demo of IAT hooking in python
    -# We will hook the 'RegOpenKeyExA' entry of Python27.dll because it is easy to trigger !
    -
    -# First: let's create our hook
    -# windows.hooks.RegOpenKeyExACallback is generated based on windows.generated_def.winfuncs
    -@windows.hooks.RegOpenKeyExACallback
    -def open_reg_hook(hKey, lpSubKey, ulOptions, samDesired, phkResult, real_function):
    -    print("<in hook> Hook called | hKey = {0} | lpSubKey = <{1}>".format(hex(hKey), lpSubKey.value))
    -    # Our hook can choose to call the real_function or not
    -    if "SECRET" in lpSubKey.value:
    -        print("<in hook> Secret key asked, returning magic handle 0x12345678")
    -        # We must respect the hooked method return-value interface
    -        phkResult[0] = 0x12345678
    -        return 0
    -    if "FAIL" in lpSubKey.value:
    -        print("<in hook> Asked for a failing key: returning 0x2a")
    -        return 42
    -    print("<in hook> Non-secret key : calling normal function")
    -    return real_function()
    -
    -
    -# Get the peb of our process
    -peb = windows.current_process.peb
    -
    -# Get the pythonxx.dll module
    -pythondll_module = [m for m in peb.modules if m.name.startswith("python") and m.name.endswith(".dll")][0]
    -
    -# Get the iat entries for DLL advapi32.dll
    -adv_imports = pythondll_module.pe.imports['advapi32.dll']
    -
    -# Get RegOpenKeyExA iat entry
    -RegOpenKeyExA_iat = [n for n in adv_imports if n.name == "RegOpenKeyExA"][0]
    -
    -# Setup our hook
    -RegOpenKeyExA_iat.set_hook(open_reg_hook)
    -
    -# Use python native module _winreg that call 'RegOpenKeyExA'
    -print("Asking for <MY_SECRET_KEY>")
    -v = _winreg.OpenKey(1234567, "MY_SECRET_KEY")
    -print("Result = " + hex(v.handle))
    -
    -print("")
    -print("Asking for <MY_FAIL_KEY>")
    -try:
    -    v = _winreg.OpenKey(1234567, "MY_FAIL_KEY")
    -    print("Result = " + hex(v.handle))
    -except WindowsError as e:
    -    print(repr(e))
    -
    -print("")
    -print("Asking for <HKEY_CURRENT_USER/Software>")
    -try:
    -    v = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software")
    -    print("Result = " + hex(v.handle))
    -except WindowsError as e:
    -    print(repr(e))
    -
    -
    -

    Output:

    -
    (cmd λ) python iat_hook.py
    -Asking for <MY_SECRET_KEY>
    -<in hook> Hook called | hKey = 0x12d687 | lpSubKey = <MY_SECRET_KEY>
    -<in hook> Secret key asked, returning magic handle 0x12345678
    -Result = 0x12345678
    -
    -Asking for <MY_FAIL_KEY>
    -<in hook> Hook called | hKey = 0x12d687 | lpSubKey = <MY_FAIL_KEY>
    -<in hook> Asked for a failing key: returning 0x2a
    -WindowsError(42, 'Windows Error 0x2A')
    -
    -Asking for <HKEY_CURRENT_USER/Software>
    -<in hook> Hook called | hKey = 0x80000001L | lpSubKey = <Software>
    -<in hook> Non-secret key : calling normal function
    -Result = 0x108
    -
    -
    -
    -

    12.6. Network - socket exploration

    +

    13.3. Network - socket exploration

    import sys
     import os.path
     import socket
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     
    @@ -563,11 +568,11 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     
    -

    12.7. Registry

    +

    13.4. Registry

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     
    @@ -581,7 +586,7 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     pprint.pprint(subkeys_name)
     
     print("Opening 'Software' in HKEY_CURRENT_USER: {0}".format(current_user("Software")))
    -print("We can also open it in one access: {0}".format(registry(r"HKEY_CURRENT_USER\Sofware")))
    +print("We can also open it in one access: {0}".format(registry(r"HKEY_CURRENT_USER\Sofware")))
     print("Looking at CurrentVersion")
     
     windows_info = registry("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion")
    @@ -617,24 +622,24 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     Looking at CurrentVersion
     Key is <PyHKey "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion">
     values are:
    -[KeyValue(name='SoftwareType', value=u'System', type=1),
    -KeyValue(name='RegisteredOwner', value=u'hakril', type=1),
    +[KeyValue(name='SoftwareType', value=u'System', type=1),
    +KeyValue(name='RegisteredOwner', value=u'hakril', type=1),
     KeyValue(name='InstallDate', value=0, type=4),
     ...
    -KeyValue(name='PathName', value=u'C:\\Windows', type=1)]
    -registered owner = <KeyValue(name='RegisteredOwner', value=u'hakril', type=1)>
    +KeyValue(name='PathName', value=u'C:\\Windows', type=1)]
    +registered owner = <KeyValue(name='RegisteredOwner', value=u'hakril', type=1)>
     
    -

    12.8. windows.wintrust

    +

    13.5. windows.wintrust

    import sys
     import os.path
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows.wintrust
     
    -TARGET_FILE = r"C:\windows\system32\ntdll.dll"
    +TARGET_FILE = r"C:\windows\system32\ntdll.dll"
     print("Checking signature of <{0}>".format(TARGET_FILE))
     print(" is_signed: <{0}>".format(windows.wintrust.is_signed(TARGET_FILE)))
     print(" check_signature: <{0}>".format(windows.wintrust.check_signature(TARGET_FILE)))
    @@ -666,7 +671,7 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     check_signature: <0>
     full_signature_information:
         * signed <True>
    -    * catalog <C:\Windows\system32\CatRoot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\Package_35_for_KB3128650~31bf3856ad364e35~amd64~~6.3.1.2.cat>
    +    * catalog <C:\Windows\system32\CatRoot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\Package_35_for_KB3128650~31bf3856ad364e35~amd64~~6.3.1.2.cat>
         * catalogsigned <True>
         * additionalinfo <0>
     Checking signature of some loaded DLL
    @@ -679,13 +684,13 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     
    -

    12.9. VectoredException()

    +

    13.6. VectoredException()

    -

    12.9.1. In local process

    +

    13.6.1. In local process

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import ctypes
     import windows
    @@ -751,11 +756,11 @@ Sections: [<PESection ".text">, <PESection ".rdata"
     
    -

    12.9.2. In remote process

    +

    13.6.2. In remote process

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.test
    @@ -853,13 +858,13 @@ No more tracing !
     
    -

    12.10. Debugging

    +

    13.7. Debugging

    -

    12.10.1. Debugger

    +

    13.7.1. Debugger

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.test
    @@ -878,7 +883,7 @@ No more tracing !
     
     class PrintUnicodeString(windows.debug.Breakpoint):
         def __init__(self, addr, argument_position):
    -        super(PrintUnicodeString, self).__init__(addr)
    +        super(PrintUnicodeString, self).__init__(addr)
             self.arg_pos = argument_position
     
     
    @@ -925,11 +930,11 @@ No more tracing !
     
    -

    12.10.1.1. Single stepping

    +

    13.7.1.1. Single stepping

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.test
    @@ -941,7 +946,7 @@ No more tracing !
     
     class MyDebugger(windows.debug.Debugger):
         def __init__(self, *args, **kwargs):
    -        super(MyDebugger, self).__init__(*args, **kwargs)
    +        super(MyDebugger, self).__init__(*args, **kwargs)
             self.single_step_counter = 0
     
         def on_exception(self, exception):
    @@ -1011,11 +1016,11 @@ No more tracing !
     
    -

    12.10.1.2. windows.debug.FunctionBP

    +

    13.7.1.2. windows.debug.FunctionBP

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.test
    @@ -1025,7 +1030,7 @@ No more tracing !
     
     class MyFunctionBP(windows.debug.FunctionBP):
         def __init__(self, target, addr=None):
    -        super(MyFunctionBP, self).__init__(target, addr)
    +        super(MyFunctionBP, self).__init__(target, addr)
             self.target_name = target.target_func
             self.counter = 3
     
    @@ -1078,15 +1083,278 @@ Exiting process
     
    +
    +

    13.7.1.3. Native code tester

    +
    import sys
    +import argparse
    +
    +import windows
    +import windows.test
    +import windows.debug as dbg
    +import windows.native_exec.simple_x86 as x86
    +import windows.native_exec.simple_x64 as x64
    +from windows.generated_def import *
    +
    +
    +def hexdump(string, start_addr=0):
    +    result = ""
    +    if len(string) == 0:
    +        return
    +    ascii = list("."*256)
    +    for i in range(1,0x7f):
    +        ascii[i] = chr(i)
    +    ascii[0x0] = "."
    +    ascii[0x7] = "."
    +    ascii[0x8] = "."
    +    ascii[0x9] = "."
    +    ascii[0xa] = "."
    +    ascii[0x1b] = "."
    +    ascii[0xd] = "."
    +    ascii[0xff] = "\x13"
    +    ascii = "".join(ascii)
    +    offset = 0
    +    while (offset+0x10) <= len(string):
    +        line = string[offset:(offset+0x10)]
    +        linebuf = " %08X " % (offset + start_addr)
    +        for i in range(0,16):
    +            if i == 8:
    +                linebuf += " "
    +            linebuf += "%02X " % ord(line[i])
    +        linebuf += " "
    +        for i in range(0,16):
    +            linebuf += ascii[ord(line[i])]
    +        result += linebuf+"\n"
    +        offset += 0x10
    +    if (len(string) % 0x10) > 0:
    +        linebuf = " %08X " % (offset + start_addr)
    +        for i in range((len(string)-(len(string) % 0x10)),(len(string))):
    +            if i == 8:
    +                linebuf += " "
    +            linebuf += "%02X " % ord(string[i])
    +        linebuf += "   "*(0x10-(len(string) % 0x10))
    +        linebuf += " "
    +        for i in range((len(string)-(len(string) % 0x10)),(len(string))):
    +            linebuf += ascii[ord(string[i])]
    +        result += linebuf+"\n"
    +    return result
    +
    +
    +class CodeTesteur(dbg.Debugger):
    +    def __init__(self, process, code, register_start={}):
    +        super(CodeTesteur, self).__init__(process)
    +
    +        self.initial_code = code
    +        code += "\xcc"
    +
    +        code_addr = self.write_code_in_target(process, code)
    +        register_start["pc"] = code_addr
    +        self.thread_exec = process.threads[0]
    +        self.context_exec = self.thread_exec.context
    +        self.setup_target_context(self.context_exec, register_start)
    +        print("Startup context is:")
    +        self.context_exec.dump()
    +        print(self.context_exec.EEFlags)
    +        self.thread_exec.suspend()
    +        self.thread_exec.set_context(self.context_exec)
    +        self.thread_exec.resume()
    +        self.init_breakpoint = False
    +
    +    def write_code_in_target(self, process, code):
    +        addr = process.virtual_alloc(len(code))
    +        process.write_memory(addr, code)
    +        return addr
    +
    +    def setup_target_context(self, ctx, register_start):
    +        for name, value in register_start.items():
    +            if not hasattr(ctx, name):
    +                raise ValueError("Unknown register to setup <{0}>".format(name))
    +            setattr(ctx, name, value)
    +
    +    def on_exception(self, x):
    +        exc_code = x.ExceptionRecord.ExceptionCode
    +        exc_addr = x.ExceptionRecord.ExceptionAddress
    +        if not self.init_breakpoint and exc_code == EXCEPTION_BREAKPOINT:
    +            self.init_breakpoint = True
    +            return
    +        ctx = self.current_thread.context
    +        print("==Post-exec context==")
    +        ctx.dump()
    +        print(ctx.EEFlags)
    +        if exc_code == EXCEPTION_BREAKPOINT and exc_addr == self.context_exec.pc + len(self.initial_code):
    +            print("<Normal terminaison>")
    +        else:
    +            print("<{0}> at <{1:#x}>".format(exc_code, exc_addr))
    +        self.report_ctx_diff(self.context_exec, ctx)
    +        self.current_process.exit()
    +        return
    +
    +    def report_ctx_diff(self, start, now):
    +        print("==DIFF==")
    +        for name, start_value in start.regs():
    +            now_value = getattr(now, name)
    +            if start_value != now_value:
    +                diff = now_value - start_value
    +                print("{0}: {1:#x} -> {2:#x} ({3:+#x})".format(name, start_value, now_value, diff))
    +        if start.sp > now.sp:
    +            print("Negative Stack: dumping:")
    +            data = self.current_process.read_memory(now.sp, start.sp - now.sp)
    +            print(hexdump(data, start.sp))
    +
    +
    +def test_code_x86(code, regs=None, raw=False, **kwargs):
    +    print("Testing x86 code")
    +    process = windows.test.pop_calc_32(dwCreationFlags=DEBUG_PROCESS)
    +    if raw:
    +        code = code.replace(" ", "").decode('hex')
    +    else:
    +        code = x86.assemble(code)
    +
    +    start_register = {}
    +    if regs:
    +        for name_value in regs.split(";"):
    +            name, value = name_value.split("=")
    +            name = name.strip().capitalize()
    +            if name == "Eflags":
    +                name = "EFlags"
    +            value = int(value.strip(), 0)
    +            start_register[name] = value
    +
    +
    +    x = CodeTesteur(process, code, start_register)
    +    x.loop()
    +
    +def test_code_x64(code, regs=None, raw=False, **kwargs):
    +    print("Testing x64 code")
    +    if windows.current_process.bitness == 32:
    +        raise ValueError("Cannot debug a 64b process from 32b python")
    +    process = windows.test.pop_calc_64(dwCreationFlags=DEBUG_PROCESS)
    +    if raw:
    +        code = code.replace(" ", "").decode('hex')
    +    else:
    +        code = x64.assemble(code)
    +
    +    start_register = {}
    +    if regs:
    +        for name_value in regs.split(";"):
    +            name, value = name_value.split("=")
    +            name = name.strip().capitalize()
    +            if name == "Eflags":
    +                name = "EFlags"
    +            value = int(value.strip(), 0)
    +            start_register[name] = value
    +
    +
    +    x = CodeTesteur(process, code, start_register)
    +    x.loop()
    +
    +
    +parser = argparse.ArgumentParser(prog=__file__)
    +
    +parser.add_argument('--x64', action='store_const', dest="func", const=test_code_x64, default=test_code_x86, help='Code is x64')
    +parser.add_argument('--raw', action='store_true', help='argument is raw assembled code (in hex)')
    +parser.add_argument('code', help='The code to execute')
    +parser.add_argument('regs', nargs="?", help='The default values of the registers')
    +
    +res = parser.parse_args()
    +
    +res.func(**res.__dict__)
    +
    +
    +

    Ouput:

    +
    (cmd λ) python.exe .\samples\test_code.py "mov eax, 0x42424242" "eax=0x11223344"
    +Testing x86 code
    +Startup context is:
    +Eip -> 0x3f0000L
    +Esp -> 0x3bfae4L
    +Eax -> 0x11223344L
    +Ebx -> 0x5a6000L
    +Ecx -> 0x0L
    +Edx -> 0x0L
    +Ebp -> 0x0L
    +Edi -> 0x0L
    +Esi -> 0x0L
    +EFlags -> 0x202L
    +EEflags(0x202L:IF)
    +==Post-exec context==
    +Eip -> 0x3f0007L
    +Esp -> 0x3bfae4L
    +Eax -> 0x42424242L
    +Ebx -> 0x5a6000L
    +Ecx -> 0x0L
    +Edx -> 0x0L
    +Ebp -> 0x0L
    +Edi -> 0x0L
    +Esi -> 0x0L
    +EFlags -> 0x202L
    +EEflags(0x202L:IF)
    +<Normal terminaison>
    +==DIFF==
    +Eip: 0x3f0000 -> 0x3f0007 (+0x7)
    +Eax: 0x11223344 -> 0x42424242 (+0x31200efe)
    +
    +
    +(cmd λ) python64 .\samples\test_code.py --x64 "mov r15, 0x11223344; push r14; call r15" "rcx=1; r14=0x4242424243434343"
    +Testing x64 code
    +Startup context is:
    +Rip -> 0x205a1d60000L
    +Rsp -> 0xe24a88fa88L
    +Rax -> 0x0L
    +Rbx -> 0x0L
    +Rcx -> 0x1L
    +Rdx -> 0xe24aaf9000L
    +Rbp -> 0x0L
    +Rdi -> 0x0L
    +Rsi -> 0x0L
    +R8 -> 0x0L
    +R9 -> 0x0L
    +R10 -> 0x0L
    +R11 -> 0x0L
    +R12 -> 0x0L
    +R13 -> 0x0L
    +R14 -> 0x4242424243434343L
    +R15 -> 0x0L
    +EFlags -> 0x200L
    +EEflags(0x200L:IF)
    +==Post-exec context==
    +Rip -> 0x11223344L
    +Rsp -> 0xe24a88fa78L
    +Rax -> 0x0L
    +Rbx -> 0x0L
    +Rcx -> 0x1L
    +Rdx -> 0xe24aaf9000L
    +Rbp -> 0x0L
    +Rdi -> 0x0L
    +Rsi -> 0x0L
    +R8 -> 0x0L
    +R9 -> 0x0L
    +R10 -> 0x0L
    +R11 -> 0x0L
    +R12 -> 0x0L
    +R13 -> 0x0L
    +R14 -> 0x4242424243434343L
    +R15 -> 0x11223344L
    +EFlags -> 0x10202L
    +EEflags(0x10202L:IF|RF)
    +<EXCEPTION_ACCESS_VIOLATION(0xc0000005L)> at <0x11223344>
    +==DIFF==
    +Rip: 0x205a1d60000 -> 0x11223344 (-0x20590b3ccbc)
    +Rsp: 0xe24a88fa88 -> 0xe24a88fa78 (-0x10)
    +R15: 0x0 -> 0x11223344 (+0x11223344)
    +EFlags: 0x200 -> 0x10202 (+0x10002)
    +Negative Stack: dumping:
    +E24A88FA88 0C 00 D6 A1 05 02 00 00  43 43 43 43 42 42 42 42 ........CCCCBBBB
    +
    +
    +
    -

    12.10.2. LocalDebugger

    +

    13.7.2. LocalDebugger

    -

    12.10.2.1. In current process

    +

    13.7.2.1. In current process

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     from windows.generated_def.winstructs import *
    @@ -1141,11 +1409,11 @@ Done!
     
    -

    12.10.2.2. In remote process

    +

    13.7.2.2. In remote process

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import ctypes
     import windows
    @@ -1215,12 +1483,13 @@ Done!
     
    +
    -

    12.10.3. Make WMI requests

    +

    13.8. Make WMI requests

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     
    @@ -1264,19 +1533,19 @@ Done!
         * WindowsVersion -> 6.3.9600
         * CommandLine -> python.exe  .\samples\wmi_request.py
     <Select Caption,FileSystem,FreeSpace from Win32_LogicalDisk>:
    -    * {'Caption': u'C:', 'FreeSpace': u'43991547904', 'FileSystem': u'NTFS'}
    -    * {'Caption': u'E:', 'FreeSpace': u'82776027136', 'FileSystem': u'NTFS'}
    -    * {'Caption': u'F:', 'FreeSpace': u'5711265792', 'FileSystem': u'FAT32'}
    -    * {'Caption': u'G:', 'FreeSpace': None, 'FileSystem': None}
    +    * {'Caption': u'C:', 'FreeSpace': u'43991547904', 'FileSystem': u'NTFS'}
    +    * {'Caption': u'E:', 'FreeSpace': u'82776027136', 'FileSystem': u'NTFS'}
    +    * {'Caption': u'F:', 'FreeSpace': u'5711265792', 'FileSystem': u'FAT32'}
    +    * {'Caption': u'G:', 'FreeSpace': None, 'FileSystem': None}
     
    -

    12.10.4. using COM: INetFwPolicy2

    +

    13.9. using COM: INetFwPolicy2

    import sys
     import os.path
     import pprint
    -sys.path.append(os.path.abspath(__file__ + "\..\.."))
    +sys.path.append(os.path.abspath(__file__ + "\..\.."))
     
     import windows
     import windows.generated_def as gdef
    @@ -1326,6 +1595,289 @@ Done!
     
    +
    +

    13.10. windows.crypto

    +
    +

    13.10.1. Encryption demo

    +

    This sample is a working POC able to generate key-pair, encrypt and decrypt file.

    +
    import argparse
    +import windows.crypto as crypto
    +from windows import winproxy
    +from windows.generated_def import *
    +
    +import windows.crypto.generation as gencrypt
    +
    +# http://stackoverflow.com/questions/1461272/basic-questions-on-microsoft-cryptoapi
    +
    +def crypt(src, dst, certs, **kwargs):
    +    """Encrypt the content of 'src' file with the certifacts in 'certs' into 'dst'"""
    +    # Open every certificates in the certs list
    +    certlist = [crypto.CertificateContext.from_file(x) for x in certs]
    +    # Encrypt the content of 'src' with all the public keys(certs)
    +    res = crypto.encrypt(certlist, src.read())
    +    print("Encryption done. Result:")
    +    print(repr(res))
    +    # Write the result in 'dst'
    +    dst.write(res)
    +    dst.close()
    +    src.close()
    +
    +def decrypt(src, pfxfile, password, **kwargs):
    +    """Decrypt the content of 'src' with the private key in 'pfxfile'. the 'pfxfile' is open using the 'password'"""
    +    # Open the 'pfx' with the given password
    +    pfx = crypto.import_pfx(pfxfile.read(), password)
    +    # Decrypt the content of the file
    +    decrypted = crypto.decrypt(pfx, src.read())
    +    print(u"Result = <{0}>".format(decrypted))
    +    return decrypted
    +
    +PFW_TMP_KEY_CONTAINER = "PythonForWindowsTMPContainer"
    +
    +def genkeys(common_name, pfxpassword, outname, **kwargs):
    +    """Generate a SHA256/RSA key pair. A self-signed certificate with 'common_name' is stored as 'outname'.cer.
    +    The private key is stored in 'outname'.pfx protected with 'pfxpassword'"""
    +    cert_store = crypto.EHCERTSTORE.new_in_memory()
    +    # Create a TMP context that will hold our newly generated key-pair
    +    with crypto.CryptContext(PFW_TMP_KEY_CONTAINER, None, PROV_RSA_FULL, 0, retrycreate=True) as ctx:
    +        key = HCRYPTKEY()
    +        # Generate a key-pair that is exportable
    +        winproxy.CryptGenKey(ctx, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, key)
    +        # It does NOT destroy the key-pair from the container,
    +        # It only release the key handle
    +        # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379918(v=vs.85).aspx
    +        winproxy.CryptDestroyKey(key)
    +
    +    # Descrption of the key-container that will be used to generate the certificate
    +    KeyProvInfo = CRYPT_KEY_PROV_INFO()
    +    KeyProvInfo.pwszContainerName = PFW_TMP_KEY_CONTAINER
    +    KeyProvInfo.pwszProvName = None
    +    KeyProvInfo.dwProvType = PROV_RSA_FULL
    +    KeyProvInfo.dwFlags = 0
    +    KeyProvInfo.cProvParam = 0
    +    KeyProvInfo.rgProvParam = None
    +    #KeyProvInfo.dwKeySpec = AT_SIGNATURE
    +    KeyProvInfo.dwKeySpec = AT_KEYEXCHANGE
    +
    +    crypt_algo = CRYPT_ALGORITHM_IDENTIFIER()
    +    crypt_algo.pszObjId = szOID_RSA_SHA256RSA
    +
    +    certif_name = "CN={0}".format(common_name)
    +    # Generate a self-signed certificate based on the given key-container and signature algorithme
    +    certif = gencrypt.generate_selfsigned_certificate(certif_name, key_info=KeyProvInfo, signature_algo=crypt_algo)
    +    # Add the newly created certificate to our TMP cert-store
    +    cert_store.add_certificate(certif)
    +    # Generate a pfx from the TMP cert-store
    +    pfx = gencrypt.generate_pfx(cert_store, pfxpassword)
    +    if outname is None:
    +        outname = common_name.lower()
    +
    +    # Dump the certif (public key) and pfx (public + private keys)
    +    with open(outname + ".cer", "wb") as f:
    +        # The encoded certif only contains the public key
    +        f.write(certif.encoded)
    +    with open(outname + ".pfx", "wb") as f:
    +        f.write(pfx)
    +    print(certif)
    +    # Destroy the TMP key container
    +    prov = HCRYPTPROV()
    +    winproxy.CryptAcquireContextW(prov, PFW_TMP_KEY_CONTAINER, None, PROV_RSA_FULL, CRYPT_DELETEKEYSET)
    +
    +parser = argparse.ArgumentParser(prog=__file__)
    +subparsers = parser.add_subparsers(description='valid subcommands',)
    +
    +cryptparse = subparsers.add_parser('crypt')
    +cryptparse.set_defaults(func=crypt)
    +
    +cryptparse.add_argument('src', type=argparse.FileType('rb'), help='File to encrypt')
    +cryptparse.add_argument('dst', type=argparse.FileType('wb'), help='The encrypted file')
    +cryptparse.add_argument('certs', type=str, nargs='+',
    +                    help='List of certfile used to encrypt the src')
    +
    +decryptparse = subparsers.add_parser('decrypt')
    +decryptparse.set_defaults(func=decrypt)
    +decryptparse.add_argument('src', type=argparse.FileType('rb'), help='File to decrypt')
    +decryptparse.add_argument('pfxfile', type=argparse.FileType('rb'), help='PFX file to use')
    +decryptparse.add_argument('password', help='Password of the PFX')
    +
    +genkeysparse = subparsers.add_parser('genkey')
    +genkeysparse.set_defaults(func=genkeys)
    +genkeysparse.add_argument('common_name', nargs='?', metavar='CommonName', default='DEFAULT', help='the common name of the certificate')
    +genkeysparse.add_argument('outname', nargs='?',help='The filename base for the generated files')
    +genkeysparse.add_argument('--pfxpassword', nargs='?', help='Password to protect the PFX')
    +
    +res = parser.parse_args()
    +res.func(**res.__dict__)
    +
    +
    +

    Ouput:

    +
    (cmd λ) python ..\samples\encryption_demo.py genkey YOLOCERTIF mykey --pfxpassword MYPASSWORD
    +<CertificatContext "YOLOCERTIF" serial="1b a4 3e 17 f7 ed ec ab 4f f8 11 46 48 e9 29 25">
    +
    +(cmd λ) ls
    +mykey.cer  mykey.pfx
    +
    +(cmd λ) echo|set /p="my secret message" > message.txt
    +
    +(cmd λ) python ..\samples\encryption_demo.py crypt message.txt message.crypt mykey.cer
    +Encryption done. Result:
    +bytearray(b'0\x82\x01\x19\x06\t*\x86H\x86\xf7\r\x01\x07\x03\xa0\x82\x01\n0\x82\x01\x06\x02\x01\x001\x81\xc30\x81
    +\xc0\x02\x01\x000)0\x151\x130\x11\x06\x03U\x04\x03\x13\nYOLOCERTIF\x02\x10\x1b\xa4>\x17\xf7\xed\xec\xabO\xf8\x11
    +FH\xe9)%0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x04\x81\x80V\x89)\xf5\xaaM\x99cEA\x17^\xa2D~\x94\xe3\xf2\x1f
    +\x05Y\xc2\xbb\xb2\xbbYBpU6\x870\xce\xe7\xd2M{\xbb\xb9K\xa0\xf5\xe5\x93\xca\xedF\x80.x\xdc\xf2\x0c\xa6UO\x01\r\xaf
    +\xd0Z\xd9\xabnzR\xd4j=\xca\xc2RG\xcd\x11u\x82\x7f\x8c\xd8t\xb9\xf9\xe8%\xfal\xaaHPj;\xecKk]\t%\xfd\x91\xcc\xe0lWf
    +\xc6\x12x\x1am\xc8\x01t\xac\xa6\xf3#\x02\xd4J \x8eZ\xbb\x10W\xe1 0;\x06\t*\x86H\x86\xf7\r\x01\x07\x010\x14\x06\x08*
    +\x86H\x86\xf7\r\x03\x07\x04\x08\x14F\x04\xad\xed9\xed<\x80\x18\x80]6\xccTV\xbc\xb8*\x84QY!~\xb3\n\x1aV\xd4\rf\xd1n:')
    +
    +(cmd λ) python ..\samples\encryption_demo.py decrypt message.crypt mykey.pfx BADPASS
    +Traceback (most recent call last):
    +File "..\samples\encryption_demo.py", line 103, in <module>
    +    res.func(**res.__dict__)
    +File "..\samples\encryption_demo.py", line 26, in decrypt
    +    pfx = crypto.import_pfx(pfxfile.read(), password)
    +File "c:\users\hakril\documents\work\pythonforwindows\windows\crypto\certificate.py", line 153, in import_pfx
    +    cert_store = winproxy.PFXImportCertStore(pfx, password, flags)
    +File "c:\users\hakril\documents\work\pythonforwindows\windows\winproxy.py", line 1065, in PFXImportCertStore
    +    return PFXImportCertStore.ctypes_function(pPFX, szPassword, dwFlags)
    +File "c:\users\hakril\documents\work\pythonforwindows\windows\winproxy.py", line 148, in perform_call
    +    return self._cprototyped(*args)
    +File "c:\users\hakril\documents\work\pythonforwindows\windows\winproxy.py", line 69, in kernel32_error_check
    +    raise Kernel32Error(func_name)
    +windows.winproxy.Kernel32Error: PFXImportCertStore: [Error 86] The specified network password is not correct.
    +
    +(cmd λ) python samples\encryption_demo.py decrypt message.crypt mykey.pfx MYPASSWORD
    +Result = <my secret message>
    +
    +
    +
    +
    +

    13.10.2. Certificate demo

    +
    import hashlib
    +import windows.crypto
    +
    +windowscert = """-----BEGIN CERTIFICATE-----
    +MIIFBDCCA+ygAwIBAgITMwAAAQZuwyXEMckYDgAAAAABBjANBgkqhkiG9w0BAQsF
    +ADCBhDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT
    +B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEuMCwGA1UE
    +AxMlTWljcm9zb2Z0IFdpbmRvd3MgUHJvZHVjdGlvbiBQQ0EgMjAxMTAeFw0xNjEw
    +MTEyMDM5MzFaFw0xODAxMTEyMDM5MzFaMHAxCzAJBgNVBAYTAlVTMRMwEQYDVQQI
    +EwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3Nv
    +ZnQgQ29ycG9yYXRpb24xGjAYBgNVBAMTEU1pY3Jvc29mdCBXaW5kb3dzMIIBIjAN
    +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyWcaCYghNInk3ecpyu2uZ7LCV9QS
    +7GWYr41ufTkcL66ewHxlAoWjmkKG6W2Bp9BYYQok10iDeDGACE9Vjr6m4Jdh+YuN
    +RLxMnHC8JTGzk96CzmdBPAuUWdAcHNmTkIWQF6AXzsbBWsekQejvDBygAOCuIYh4
    +sBgNa5cjTxQc7Iyp9c7RxBmThV5BNFTOnSN6D9N8zU+ENgIZuyHxGvqzRdrhU4G4
    +Cg/h1CkI4TgeZQZCeUNPnWV6DMuvPCiqGEia5phOJZyENKND0Sx6eQZrYnuz1gMn
    +YaEnO+ggegtt4pWpqg8Ch0jNrkL1fb3Kzz7E34/K9dcTgaOymfF6qUKabQIDAQAB
    +o4IBgDCCAXwwHwYDVR0lBBgwFgYKKwYBBAGCNwoDBgYIKwYBBQUHAwMwHQYDVR0O
    +BBYEFBEciVg/vsVmKtr/hmHt7KM6g8lSMFIGA1UdEQRLMEmkRzBFMQ0wCwYDVQQL
    +EwRNT1BSMTQwMgYDVQQFEysyMjk4NzkrMTQ3NDQ5YmUtMTVhOC00ZWJhLTkzZjMt
    +ZDExMGE1YzQ1NTUyMB8GA1UdIwQYMBaAFKkpAjmOFsSXeM2Q+Z5PmuF8Va9TMFQG
    +A1UdHwRNMEswSaBHoEWGQ2h0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2lvcHMv
    +Y3JsL01pY1dpblByb1BDQTIwMTFfMjAxMS0xMC0xOS5jcmwwYQYIKwYBBQUHAQEE
    +VTBTMFEGCCsGAQUFBzAChkVodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpb3Bz
    +L2NlcnRzL01pY1dpblByb1BDQTIwMTFfMjAxMS0xMC0xOS5jcnQwDAYDVR0TAQH/
    +BAIwADANBgkqhkiG9w0BAQsFAAOCAQEAvYC1iawgKoxXAotQXaN0lj1J5VX01/un
    +7JybZF4sPMG4acoFT85Ao5U6TK5ATPB7yPUulAivp8908DwTGqN+Ju6iH+UkvAb+
    +a/WcHVEMxQXK5eOFNE6yekUArBGbMNWlTFrpwklmVTnL9R+4aApTEe6ITT1KLDio
    +5uFw98n5Sqgh+In073czyiTG7MVhBexbOfhgnciXoufeyhwy1pYgjouSqSQZs4bj
    +cUwQTwGlS2Gd5a+3nblhjn+QhSszIo1K5n1udLPFWtn29BuGlSrtTXPv5OCfNtLO
    +l2ec6CyjDQc6HcQBNCsbJVq6qGtQbYNE+ih+KhIU4tO5jf25xthf2g==
    +-----END CERTIFICATE-----"""
    +
    +
    +raw_cert = ("".join(windowscert.split("\n")[1:-1])).decode('base64')
    +cert = windows.crypto.CertificateContext.from_buffer(raw_cert)
    +
    +print("Analysing certificate: {0}".format(cert))
    +print("    * name: <{0}>".format(cert.name))
    +print("    * issuer: <{0}>".format(cert.issuer))
    +print("    * raw_serial: <{0}>".format(cert.raw_serial))
    +print("    * serial: <{0}>".format(cert.serial))
    +print("    * encoded start: <{0!r}>".format(cert.encoded[:20]))
    +
    +print ""
    +chains = cert.chains
    +print("This certificate has {0} certificate chain(s)".format(len(chains)))
    +for i, chain in enumerate(chains):
    +    print("Chain {0}:".format(i))
    +    for ccert in chain:
    +
    +        print("  {0}:".format(ccert))
    +        print("    * issuer: <{0}>".format(ccert.issuer))
    +
    +print ""
    +cert_to_verif = ccert
    +print("Looking for <{0}> in trusted certificates".format(cert_to_verif.name))
    +root_store = windows.crypto.EHCERTSTORE.from_system_store("Root")
    +# This is not the correct way verify the validity of a certificate chain.
    +# I would say that if the goal is to verify the signature of the certificate: use wintrust.
    +# (or maybe CertVerifyCertificateChainPolicy : https://msdn.microsoft.com/en-us/library/windows/desktop/aa377163(v=vs.85).aspx)
    +matchs = [c for c in root_store.certs if c == cert_to_verif]
    +print("matches = {0}".format(matchs))
    +if matchs:
    +    print("Found it !")
    +else:
    +    print("Not found :(")
    +
    +## Extract certificates of a PE file
    +
    +print ("")
    +print ("== PE Analysis ==")
    +TARGET_FILE = r"C:\windows\system32\ntdll.dll"
    +print("Target sha1 = <{0}>".format(hashlib.sha1(open(TARGET_FILE, "rb").read()).hexdigest()))
    +cryptobj = windows.crypto.CryptObject(TARGET_FILE)
    +print("Analysing {0}".format(cryptobj))
    +print("File has {0} signer(s):".format(cryptobj.nb_signer))
    +for i, signer in ((i, cryptobj.get_signer_data(i)) for i in range(cryptobj.nb_signer)):
    +    print("Signer {0}:".format(i))
    +    print("   * Issuer: {0!r}".format(windows.crypto.ECRYPT_DATA_BLOB(signer.Issuer.cbData, signer.Issuer.pbData).data))
    +    print("   * HashAlgorithme: {0}".format(signer.HashAlgorithm.pszObjId))
    +    cert = cryptobj.get_signer_certificate(i)
    +    print("   * Certificate: {0}".format(cert))
    +
    +print("")
    +print("File embdeds {0} certificate(s):".format(cryptobj.nb_cert))
    +for i, certificate in ((i, cryptobj.get_cert(i)) for i in range(cryptobj.nb_cert)):
    +    print("   * {0}) {1}".format(i, certificate))
    +
    +
    +

    Ouput:

    +
    (cmd λ) python .\samples\certificate.py
    +Analysing certificate: <CertificateContext "Microsoft Windows" serial="33 00 00 01 06 6e c3 25 c4 31 c9 18 0e 00 00 00 00 01 06">
    +    * name: <Microsoft Windows>
    +    * issuer: <Microsoft Windows Production PCA 2011>
    +    * raw_serial: <[51, 0, 0, 1, 6, 110, 195, 37, 196, 49, 201, 24, 14, 0, 0, 0, 0, 1, 6]>
    +    * serial: <33 00 00 01 06 6e c3 25 c4 31 c9 18 0e 00 00 00 00 01 06>
    +    * encoded start: <bytearray(b'0\x82\x05\x040\x82\x03\xec\xa0\x03\x02\x01\x02\x02\x133\x00\x00\x01\x06')>
    +
    +This certificate has 1 certificate chain(s)
    +Chain 0:
    +<CertificateContext "Microsoft Windows" serial="33 00 00 01 06 6e c3 25 c4 31 c9 18 0e 00 00 00 00 01 06">:
    +    * issuer: <Microsoft Windows Production PCA 2011>
    +<CertificateContext "Microsoft Windows Production PCA 2011" serial="61 07 76 56 00 00 00 00 00 08">:
    +    * issuer: <Microsoft Root Certificate Authority 2010>
    +<CertificateContext "Microsoft Root Certificate Authority 2010" serial="28 cc 3a 25 bf ba 44 ac 44 9a 9b 58 6b 43 39 aa">:
    +    * issuer: <Microsoft Root Certificate Authority 2010>
    +
    +Looking for <Microsoft Root Certificate Authority 2010> in trusted certificates
    +matches = [<CertificateContext "Microsoft Root Certificate Authority 2010" serial="28 cc 3a 25 bf ba 44 ac 44 9a 9b 58 6b 43 39 aa">]
    +Found it !
    +
    +== PE Analysis ==
    +Target sha1 = <059cb1ba1a41433a18dd8f87422c2ac3bf35b7b8>
    +Analysing <CryptObject "C:\windows\system32\ntdll.dll" content_type=CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED(0xaL)>
    +File has 1 signer(s):
    +Signer 0:
    +* Issuer: bytearray(b'0\x81\x841\x0b0\t\x06\x03U\x04\x06\x13\x02US1\x130\x11\x06\x03U\x04\x08\x13\nWashington1\x100\x0e\x06\x03U\x04\x07\x13\x07Redmond1\x1e0\x1c\x06\x03U\x04\n\x13\x15Microsoft Corporation1.0,\x06\x03U\x04\x03\x13%Microsoft Windows Production PCA 2011')
    +* HashAlgorithme: 2.16.840.1.101.3.4.2.1
    +* Certificate: <CertificateContext "Microsoft Windows" serial="33 00 00 01 06 6e c3 25 c4 31 c9 18 0e 00 00 00 00 01 06">
    +
    +File embdeds 2 certificate(s):
    +* 0) <CertificateContext "Microsoft Windows" serial="33 00 00 01 06 6e c3 25 c4 31 c9 18 0e 00 00 00 00 01 06">
    +* 1) <CertificateContext "Microsoft Windows Production PCA 2011" serial="61 07 76 56 00 00 00 00 00 08">
    +
    +
    +
    @@ -1337,33 +1889,42 @@ Done!

    Table Of Contents

    \ No newline at end of file diff --git a/docs/build/html/search.html b/docs/build/html/search.html index e0eefef..f346183 100644 --- a/docs/build/html/search.html +++ b/docs/build/html/search.html @@ -6,7 +6,7 @@ - Search — PythonForWindows 0.2 documentation + Search — PythonForWindows 0.2 documentation @@ -17,14 +17,16 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • modules |
  • - +
    @@ -94,12 +96,12 @@
  • modules |
  • - +
    \ No newline at end of file diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js index 7a8b610..00d3b69 100644 --- a/docs/build/html/searchindex.js +++ b/docs/build/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({envversion:49,filenames:["index","sample"],objects:{},objnames:{},objtypes:{},terms:{"00c04fc295ee":1,"0x02649b70":1,"0x026ddd00":1,"0x0272d350":1,"0x02941290":1,"0x02b37ef0":1,"0x02dc8210":1,"0x030a2590":1,"0x10":1,"0x1000":1,"0x108":1,"0x12345678":1,"0x12d687":1,"0x1337":1,"0x1337l":1,"0x154":1,"0x1d1ab574":1,"0x1db0000":1,"0x1db0010":1,"0x1l":1,"0x20l":1,"0x2649c60":1,"0x2649d50":1,"0x26ddc60":1,"0x26dde40":1,"0x26ddee0":1,"0x26ddf30":1,"0x272a030":1,"0x272a080":1,"0x272acb0":1,"0x272ad00":1,"0x272ad50":1,"0x272ada0":1,"0x27bd5d0":1,"0x27f7f30":1,"0x27f7f80":1,"0x27fa030":1,"0x2a":1,"0x2e64750":1,"0x2l":1,"0x32d3210":1,"0x3l":1,"0x4":1,"0x41":1,"0x42":1,"0x424242":1,"0x42424242":1,"0x4l":1,"0x5c90000":1,"0x770d7c04":1,"0x774c0000":1,"0x77541128l":1,"0x77a73bad":1,"0x77ae3c7d":1,"0x7ffa3c700000l":1,"0x7ffa3c70f0f0l":1,"0x7ffa3c70f0f5l":1,"0x7ffa3c70f0fal":1,"0x7ffa3c70f0ffl":1,"0x7ffa3c70f100l":1,"0x80000001l":1,"0x80000003l":1,"0x80000004l":1,"0x800b0100l":1,"0x8984848":1,"0x8d0006":1,"0x8d000c":1,"0x8d0011":1,"0x8d0017":1,"0x8d001c":1,"0x8d0022":1,"0x8d0023":1,"0x8e0000":1,"0x8e0004":1,"0xac":1,"0xcf0002":1,"0xcf0003":1,"0xcf0004":1,"0xcf0005":1,"0xd60000":1,"11d1":1,"129l":1,"17415_none_dad8722c5bcc2d8f":1,"2001566688l":1,"2001570704l":1,"2001635616l":1,"2001647872l":1,"31bf3856ad364e35":1,"38ee":1,"41ac":1,"6ae1":1,"817a":1,"85e5":1,"\u03bb":1,"case":1,"class":1,"default":1,"export":1,"function":[0,1],"import":1,"int":1,"return":1,"super":1,"true":1,"try":1,__file__:1,__init__:1,_winreg:1,about:1,abspath:1,access:1,acpi:1,add:1,add_bp:1,additionalinfo:1,addr:1,address:1,addvectoredexceptionhandl:1,adv_import:1,advapi32:1,all:1,all_calc:1,alloc:1,allocat:1,also:1,amd64:1,anoth:1,api:[0,1],append:1,appevent:1,appinfo:1,applicat:1,appxbackupcontenttyp:1,arg:1,arg_po:1,argument_posit:1,ask:1,asked:1,asking:1,assembl:1,assembler:0,base:1,baseaddr:1,basic:1,bbbb:1,becaus:1,begin:1,bit:1,break_on_ret:1,breakpoint:[0,1],buffer:1,c_uint:1,c_void_p:1,calc:1,call:1,can:1,caption:1,cast:1,cat:1,catalog:1,catalogsign:1,catroot:1,check:[0,1],check_is_elev:1,check_signatur:1,choos:1,close:1,clsid:1,cmapi:1,cmd:1,code:0,code_addr:1,code_s:1,com:0,com_inetfwpolicy2:1,comctl32:1,command:1,commandlin:1,complet:1,compon:0,computer_nam:1,condrv:1,conn:1,connect:1,consol:1,content:[0,1],context:[0,1],contextrecord:1,control:1,control_accept:1,counter:1,cp_handl:1,cpuid:0,creat:1,create_connect:1,create_consol:1,create_funct:1,create_inst:1,create_process:1,create_suspended:1,create_thread:1,createfilea:1,cross:0,ctype:1,current_process:0,current_thread:1,current_us:1,currentprocess:1,currentvers:1,dat:1,data:1,dbg:1,debug:0,debug_functionbp:1,debug_process:1,debugg:0,debugger_membp_singlestep:1,debugger_print_ldrloaddl:1,def:1,demo:1,depend:1,deref:1,descript:1,devic:1,deviceapi:1,dict:1,dll:1,dll_load:1,don:1,done:1,drive:[0,1],drive_fixed:1,driver:1,dump:1,dwcreationflag:1,dwprocessid:1,e2b3c97f:1,earli:0,easi:1,eax:1,eeflag:1,eip:1,elev:1,els:1,enabl:1,endswith:1,entri:1,entry:1,enumer:1,environ:1,errno:1,error:1,esp:1,establish:1,eudc:1,event:1,exampl:0,exc:1,except:1,exception:[0,1],exception_access_violation:1,exception_breakpoint:1,exception_continue_execution:1,exception_single_step:1,exceptionaddress:1,exceptioncod:1,exceptioninform:1,exceptionrecord:1,execut:[0,1],execute_python:1,exist:1,exit:1,exit_cod:1,exite:1,exp:1,explor:0,explorat:0,explore:1,extract_argu:1,f6f92166d7dd:1,f750e6c3:1,fail:1,failed:1,fake_module:1,fals:1,fat32:1,fault_addr:1,fhandl:1,file:1,file_h:1,filehandl:1,filenam:1,filesystem:1,find:1,firewal:1,first:1,fixedinteractiveconsol:1,flag:1,follow:1,font:1,forcibl:1,format:1,found:1,freespac:1,from:1,from_address:1,from_str:1,full_signature_inform:1,fullnam:1,func:1,func_result:1,gate:0,gdef:1,gdi32:1,gdiplu:1,gdiplus_6595b64144ccf1df_1:1,gener:1,generated_def:1,get:1,get_cod:1,get_exception_cod:1,get_exception_context:1,get_firewallen:1,get_optionalhead:1,getpeernam:1,got:1,hakril:1,handl:[0,1],handle_addr:1,handle_valu:1,handler:1,harddisk0:1,harddiskvolume2:1,have:1,heaven:0,hello:1,helper:0,here:1,hex:1,hkei:1,hkey_current_user:1,hkey_local_machine:1,hook:0,host:1,hxbp:1,hxbreakpoint:1,iat:0,iat_hook:1,iatentry:1,identiti:1,iid:1,imagepath:1,imm32:1,implement:0,importerror:1,inc:1,index:0,infinit:1,infitin:1,info:1,informat:1,init:1,initialis:1,inject:1,installdat:1,instanc:1,instr:1,instruct:1,instruction:1,interact:1,interfac:[0,1],internal:0,ipv4:1,is_sign:1,is_wow_64:1,item:1,jmp:1,join:1,k32:1,k32pe:1,kei:1,kernel32:1,kernelbas:1,keyboard:1,keyvalu:1,kill:1,kwarg:1,label:1,lait:1,last:1,layout:1,ldr:1,ldrloaddll:1,len:1,let:1,line:1,listen:1,load:[0,1],loadedmodul:1,loading:1,local_debugg:1,local_debugger_remote_process:1,local_port:1,localdebugg:0,localhost:1,logic:[0,1],logicaldr:1,look:1,loop:1,lpsubkei:1,magic:1,make:0,manag:0,manual:1,mem:1,memori:1,memorybreakpoint:1,method:1,microsoft:1,model:0,modul:[0,1],module_to_trac:1,more:1,most:1,mov:1,msctf:1,msvcr90:1,msxml6:1,mui:1,multipleinstr:1,must:1,my_fail_key:1,my_secret_key:1,mydebugg:1,myfunctionbp:1,name:1,nativ:[0,1],native_cod:1,native_exec:[0,1],nativeutil:0,nb_repeat:1,need:1,net_fw_profile2_domain:1,net_fw_profile2_private:1,net_fw_profile2_public:1,netfwpolicy2clsid:1,network:0,nfunc:1,non:1,none:1,nop:1,normal:1,now:1,ntcreatefil:1,ntcreatefile_iat:1,ntdll:1,ntfs:1,object:[0,1],objectattribut:1,objectnam:1,ole32:1,oleacc:1,oleaut32:1,on_except:1,on_single_step:1,open:1,open_reg_hook:1,opene:1,openkei:1,ordin:1,osname:1,ouput:1,our:1,our_connect:1,ourself:1,output:1,owner:1,package_35_for_kb3128650:1,page:[0,1],page_execute_readwrite:1,page_noaccess:1,page_readwrite:1,panel:1,param:1,pars:0,partition2:1,path:1,pathnam:1,pe_pars:1,peb:0,pefile:[0,1],pesection:1,phkresult:1,pid:1,plai:1,pop_calc_32:1,pop_calc_64:1,port:1,ppid:1,pprint:1,print:1,printer:1,printunicodestr:1,pro:1,proc:1,process:0,processid:1,product_typ:1,profil:1,progress:0,protect:1,protocol:0,put:0,pvoid:1,pyhkei:1,python27:1,python32:1,python:1,python_cod:1,python_execut:1,pythondll_modul:1,pythonxx:1,rais:1,rax:1,rdata:1,read:1,read_memori:1,read_ptr:1,read_wstr:1,real_funct:1,recent:1,regist:1,registered_own:1,registeredown:1,registri:0,regopenkeyexa:1,regopenkeyexa_iat:1,regopenkeyexacallback:1,relat:0,reloc:1,remot:0,remote_addr:1,remote_calc:1,remote_cod:1,remote_port:1,remote_veh_segv:1,remotectyp:0,remoteloadedmodul:1,remotepeb:1,remotepythonerror:1,remotewinunicodestr:1,repr:1,represent:1,request:0,requir:1,reset:1,respect:1,result:1,resum:1,ret:1,ret_trigg:1,ret_valu:1,rewrit:1,rewritebreakpoint:1,rsrc:1,run:1,rwx:1,safe:1,samdesir:1,sampl:0,search:0,secret:1,section:1,secur:1,see:1,select:1,self:1,send:1,serv:1,servic:[0,1],service_kernel_driver:1,service_running:1,service_win32_share_process:1,servicea:1,servicestatu:1,set:1,set_hook:1,setup:1,shell32:1,sign:1,sign_info:1,signatur:[0,1],simpl:1,simple_x64:[0,1],simple_x86:[0,1],single_step:1,single_step_count:1,singlesteponwrit:1,singlesteppingdebugg:1,size:1,sizeofcod:1,sleep:1,socket:0,softwar:1,software:1,softwaretyp:1,sofwar:1,some:1,some_export:1,startswith:1,state:1,staticcach:1,statu:1,str:1,string:1,structur:0,stuff:1,subkei:1,subkeys_nam:1,suspend:1,svchost:1,system32:1,system:0,syswow64:[0,1],target:1,target_addr:1,target_file:1,target_func:1,target_host:1,target_nam:1,target_pag:1,target_port:1,tcp:1,test:1,text:1,thei:1,thi:1,thread:[0,1],time:1,trace:1,traceback:1,trigger:1,trust_e_nosignature:1,type:1,typenam:1,uloption:1,unicode_string_addr:1,use:1,user:1,usermodetim:1,using:0,util:[0,1],utiliti:0,uxthem:1,valu:1,valueerror:1,variabl:1,variant_bool:1,vectoredexcept:0,veh:1,veh_segv:1,ver_nt_workstation:1,verif:1,version:1,version_nam:1,via:1,virtual_alloc:1,virtualalloc:[0,1],virtualprotect:1,vol:1,volatil:1,volum:0,wait:1,win32_logicaldisk:1,win32_process:1,windef:1,window:0,windows_info:1,windowserror:1,windowsvers:1,winfunc:1,winmm:1,winobject:1,winoject:1,winprocess:0,winproxi:[0,1],winstruct:1,winsxs:1,winthread:1,wintrust:0,winunicodestr:1,without:1,wmi:0,wmi_request:1,wmirequest:1,work:[0,1],write:1,write_memori:1,wrote:1,wstring_addr:1,wvalu:1,x00:1,x64:[0,1],x86:[0,1],x86_microsoft:1,x90:1,yolohxbp:1,yop:1,you:1},titles:["Welcome to PythonForWindows’s documentation!","12. Samples of code"],titleterms:{code:1,com:1,current:1,current_process:1,debug:1,debugg:1,document:0,explor:1,functionbp:1,hook:1,iat:1,indice:0,inetfwpolicy2:1,local:1,localdebugg:1,make:1,network:1,peb:1,process:1,pythonforwindow:0,registri:1,remot:1,request:1,sampl:1,singl:1,socket:1,step:1,system:1,tabl:0,vectoredexcept:1,welcom:0,window:1,winprocess:1,wintrust:1,wmi:1}}) \ No newline at end of file +Search.setIndex({docnames:["crypto","index","sample","winproxy"],envversion:50,filenames:["crypto.rst","index.rst","sample.rst","winproxy.rst"],objects:{"windows.crypto":{CertificateContext:[0,1,1,""],CryptContext:[0,1,1,""],CryptObject:[0,1,1,""],EHCERTSTORE:[0,1,1,""],decrypt:[0,5,1,""],encrypt:[0,5,1,""],generation:[0,0,0,"-"],import_pfx:[0,5,1,""]},"windows.crypto.CertificateContext":{chains:[0,2,1,""],contents:[0,2,1,""],duplicate:[0,3,1,""],encoded:[0,2,1,""],from_buffer:[0,4,1,""],from_file:[0,4,1,""],get_name:[0,3,1,""],issuer:[0,2,1,""],name:[0,2,1,""],raw_serial:[0,2,1,""],serial:[0,2,1,""],store:[0,2,1,""]},"windows.crypto.CryptContext":{contents:[0,2,1,""]},"windows.crypto.CryptObject":{cert:[0,2,1,""],get_cert:[0,3,1,""],get_signer_certificate:[0,3,1,""],get_signer_data:[0,3,1,""],nb_cert:[0,2,1,""],nb_signer:[0,2,1,""]},"windows.crypto.EHCERTSTORE":{add_certificate:[0,3,1,""],certs:[0,2,1,""],from_file:[0,4,1,""],from_system_store:[0,4,1,""],new_in_memory:[0,4,1,""],value:[0,2,1,""]},"windows.crypto.generation":{generate_key:[0,5,1,""],generate_pfx:[0,5,1,""],generate_selfsigned_certificate:[0,5,1,""]},windows:{crypto:[0,0,0,"-"],winproxy:[3,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","attribute","Python attribute"],"3":["py","method","Python method"],"4":["py","classmethod","Python class method"],"5":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:attribute","3":"py:method","4":"py:classmethod","5":"py:function"},terms:{"00c04fc295ee":2,"02x":2,"059cb1ba1a41433a18dd8f87422c2ac3bf35b7b8":2,"08x":2,"0x0":2,"0x02649b70":2,"0x026ddd00":[],"0x0272d350":2,"0x02941290":2,"0x02b37ef0":2,"0x02dc8210":2,"0x02ed63f0":3,"0x030a2590":2,"0x03243770":[],"0x0330d990":[],"0x03f6cda0":2,"0x04c87c90":[],"0x04c87cb0":[],"0x0c000000d":[],"0x0l":[2,3],"0x1":[],"0x10":2,"0x1000":[2,3],"0x10002":2,"0x1000l":3,"0x100l":[],"0x10202":2,"0x10202l":2,"0x108":2,"0x10l":[],"0x11111111":[],"0x11223344":2,"0x11223344l":2,"0x12345678":2,"0x12d687":2,"0x1337":2,"0x1337l":2,"0x154":2,"0x1b":2,"0x1d1ab574":2,"0x1db0000":2,"0x1db0010":2,"0x1f03ffl":3,"0x1f0fffl":3,"0x1l":[0,2,3],"0x2":[],"0x200":2,"0x20019l":[],"0x200l":2,"0x202l":2,"0x20590b3ccbc":2,"0x205a1d60000":2,"0x205a1d60000l":2,"0x20l":2,"0x23":[],"0x2649c60":2,"0x2649d50":2,"0x26ddc60":[],"0x26dde40":[],"0x26ddee0":[],"0x26ddf30":[],"0x272a030":2,"0x272a080":2,"0x272acb0":2,"0x272ad00":2,"0x272ad50":2,"0x272ada0":2,"0x27bd5d0":[],"0x27f7f30":[],"0x27f7f80":[],"0x27fa030":[],"0x2a":2,"0x2e64750":2,"0x2l":2,"0x31200efe":2,"0x32d3210":2,"0x33":[],"0x3bfae4l":2,"0x3f0000":2,"0x3f0000l":2,"0x3f0007":2,"0x3f0007l":2,"0x3f6ce40":2,"0x3f6cee0":2,"0x3f6cf30":2,"0x3f6cf80":2,"0x3ffel":0,"0x3l":[2,3],"0x4":2,"0x40ce850":2,"0x40l":3,"0x41":2,"0x41faee0":2,"0x41faf30":2,"0x42":2,"0x424242":2,"0x42424242":2,"0x4242424243434343":2,"0x4242424243434343l":2,"0x4242424243444546":[],"0x42424242l":2,"0x4l":[0,2,3],"0x5a6000l":2,"0x5c90000":[],"0x5l":3,"0x6f80000":2,"0x6l":[],"0x7":2,"0x770d7c04":2,"0x774c0000":2,"0x77541128l":2,"0x77a73bad":2,"0x77ae3c7d":2,"0x7f":2,"0x7ffa3c700000l":2,"0x7ffa3c70f0f0l":2,"0x7ffa3c70f0f5l":2,"0x7ffa3c70f0fal":2,"0x7ffa3c70f0ffl":2,"0x7ffa3c70f100l":2,"0x7l":[],"0x8":2,"0x80000000l":3,"0x80000001l":2,"0x80000003l":2,"0x80000004l":2,"0x8000l":3,"0x8009200c":0,"0x800b0100l":2,"0x80l":3,"0x8984848":2,"0x8d0006":2,"0x8d000c":2,"0x8d0011":2,"0x8d0017":2,"0x8d001c":2,"0x8d0022":2,"0x8d0023":2,"0x8e0000":2,"0x8e0004":2,"0x9":2,"0xa":2,"0xac":2,"0xal":2,"0xc":[],"0xc0000005l":2,"0xcf0002":2,"0xcf0003":2,"0xcf0004":2,"0xcf0005":2,"0xd":2,"0xd60000":2,"0xe24a88fa78":2,"0xe24a88fa78l":2,"0xe24a88fa88":2,"0xe24a88fa88l":2,"0xe24aaf9000l":2,"0xf001fl":3,"0xf003fl":3,"0xff":2,"0xfffffffe":[],"0xffffffff":3,"0xfffffffffffffffe":[],"0xffffffffffffffff":[],"0xffffffffl":3,"11d1":2,"129l":2,"13l":[],"17415_none_dad8722c5bcc2d8f":2,"1970169159l":[],"2001566688l":2,"2001570704l":2,"2001635616l":2,"2001647872l":2,"31bf3856ad364e35":2,"32b":2,"32bit":[],"36864l":0,"38ee":2,"3nblhjn":2,"41ac":2,"4aaptee6itt1kldio":2,"58l":[],"5ufw98n5sqgh":2,"64b":2,"64bit":[],"6ae1":2,"7gwyr41uftkcl66ewhxlaowjmkkg6w2bp9byyqok10idedgace9vjr6m4jdh":2,"7jybzf4spmg4acoft85ao5u6tk5atpb7ypuulaivp8908dwtgqn":2,"817a":2,"85e5":2,"\u03bb":2,"abstract":[],"break":[],"byte":[],"case":[0,2],"char":[],"class":[0,2],"const":2,"default":[0,2,3],"export":2,"final":[],"function":[1,2],"import":[0,2,3],"int":[0,2],"long":[],"new":0,"public":2,"return":[0,2,3],"short":[],"super":2,"switch":[],"true":[2,3],"try":[0,2],"while":2,For:[],Its:[],NOT:[0,2,3],Not:[2,3],One:[],THE:[],That:2,The:[0,1,2,3],Then:[],There:2,These:[],Use:2,Useful:[],Using:1,With:[],_______noumex______:[],__call__:[],__dict__:2,__file__:2,__getitem__:[],__init__:2,__repr__:[],__setitem__:[],__unusedalign:[],_cprototyp:[2,3],_enum_service_status_processa:[],_tcp_table_class:3,_winreg:2,a1udhwrnmeswsabhoewgq2h0dha6ly93d3cubwljcm9zb2z0lmnvbs9wa2lvchmv:2,aa376039:0,aa377163:2,aa379918:2,aa388136:0,abil:[],abl:[0,2],about:[2,3],abspath:2,accept:[],acceptconnect:3,access:2,acpi:2,acquir:[],action:2,activ:[],actual:[],adcbhdelmakga1uebhmcvvmxezarbgnvbagtcldhc2hpbmd0b24xedaobgnvbact:2,add:[0,2,3],add_argu:2,add_bp:2,add_certif:[0,2],add_pars:2,add_subpars:2,additionalinfo:2,addr:2,address:2,addvectoredcontinuehandl:3,addvectoredexceptionhandl:[2,3],adjusttokenprivileg:3,admin:[],adv_import:2,advapi32:2,affect:[],after:[],again:[],aim:[],algid:3,algo:0,algorithm:[0,2],alia:[],align:[],all:[0,2,3],all_calc:[],all_notepad:2,alloc:2,allocated_memori:[],allocations:3,allocconsol:3,allow:[],alpcgetmessageattribut:3,alpcinitializemessageattribut:3,alreadi:[],also:[2,3],alwai:[],amd64:2,analys:2,analysi:2,ani:0,anoth:[2,3],api:[1,2],api_nam:[],apinam:[],append:2,appev:2,appinfo:2,appli:[],applic:2,application_nam:[],appxbackupcontenttyp:2,arg1:[],arg2:[],arg:[2,3],arg_po:2,argpars:2,argument:[2,3],argument_posit:2,argumentpars:2,argv:[],around:3,arrai:[],arround:0,asauthsvc:3,ascii:2,ask:2,aspx:[0,2],assembl:[1,2],associ:[],at_keyexchang:[0,2],at_signatur:2,attach:[],attr:[],attribut:[],attributeflag:3,authenticamd:[],author:2,autohandl:[],automaticali:[],avail:[0,3],axmltwljcm9zb2z0ifdpbmrvd3mguhjvzhvjdglvbibqq0egmjaxmtaefw0xnjew:2,b1jlzg1vbmqxhjacbgnvbaotfu1py3jvc29mdcbdb3jwb3jhdglvbjeumcwga1u:2,ba40727d7d257b00f89fc6ca7296c9833b7b75b2:[],backward:[],badpass:2,baiwadanbgkqhkig9w0baqsfaaocaqeavyc1iawgkoxxaotqxan0lj1j5vx01:2,base64:2,base:[2,3],base_addr:[],baseaddr:2,baseaddress:3,basic:2,bbbb:2,bbyefbecivg:2,becaus:2,been:3,befor:[],begin:2,behaviour:[],behind:[],being:[],benableprivileg:[],bewar:[],bgkqhkig9w0baqefaaocaq8amiibcgkcaqeaywcacyghnink3ecpyu2uz7lcv9q:2,binherithandl:3,bit:2,blablabla:[],blob:[],block:[],bool:[],border:3,both:[],break_on_ret:2,breakpoint:[1,2],buffer:[0,2,3],bufferlength:3,buffers:3,byref:3,bytearrai:[0,2],c_char_p:[],c_uint:2,c_ulong:[],c_void_p:2,calc:2,calcul:[],call:[2,3],callabl:[],callback:[],callind:[],can:[2,3],cannot:2,capit:2,caption:2,care:[],carr:[],cast:2,cat:2,catalog:2,catalogsign:2,catroot:2,caus:2,cauthsvc:3,cbbufsiz:3,cbcertencod:3,cbdata:2,cbencod:3,cbencryptedblob:3,cbhash:3,cbtobeencrypt:3,ccccbbbb:2,ccert:2,cchbuffer:3,cchbufferlength:3,cchfilenamemax:3,cchname:3,cchnamestr:3,cchreferenceddomainnam:3,cer:2,cert:[0,2,3],cert_name_simple_display_typ:0,cert_or_certlist:0,cert_query_content_flag_al:0,cert_query_content_pkcs7_signed_emb:2,cert_stor:[0,2],cert_to_verif:2,certaddcertificatecontexttostor:3,certcomparecertif:3,certcreatecertificatecontext:3,certcreateselfsigncertif:3,certduplicatecertificatecontext:[0,3],certenumcertificatecontextproperti:3,certenumcertificatesinstor:3,certfil:2,certfindcertificateinstor:3,certgetcertificatechain:3,certgetcertificatecontextproperti:3,certgetnamestringa:[0,3],certgetnamestringw:3,certif:1,certif_nam:2,certifact:2,certificatcontext:2,certificatecontext:2,certlist:2,certopenstor:3,certstrtonamea:3,certstrtonamew:3,certverifycertificatechainpolici:2,chain:[0,2],chang:0,check:[1,2],check_debug:[],check_is_elev:2,check_signatur:2,choos:2,chr:2,cimv2:[],classmethod:0,clientportobjectattribut:3,close:2,closehandl:3,clsctx_inproc_serv:3,clsid:2,cmapi:2,cmd:2,cmp:[],cmsg_signer_info:0,cocreateinst:3,code3:[],code4:[],code:1,code_addr:2,code_s:2,codetesteur:2,coinit_multithread:3,coinitializeex:3,coinitializesecur:3,com:[0,1],com_inetfwpolicy2:2,combinaison:[],comctl32:2,comimplement:[],cominterfac:[],command:[2,3],commandlin:2,common:2,common_nam:2,commonnam:2,compar:3,complet:2,complex:[],compon:1,compressedbuff:3,compressedbuffers:3,compressionformat:3,comput:3,computedfamili:[],computedmodel:[],computer_nam:2,computernam:[],condit:[],condrv:2,conn:2,connect:2,connectionmessag:3,connectionmessageattribut:3,connectionporthandl:3,connectionportobjectattribut:3,connectionrequest:3,consol:2,contain:[0,2],contan:0,content:[0,1,2],content_typ:[0,2],context:[0,1,2,3],context_exec:2,context_syswow:[],contextflag:[],contextmanag:[],contextrecord:2,contextu:[],continuedebugev:3,control:2,control_accept:2,conveni:[],convertsidtostringsida:3,convertsidtostringsidw:3,convertstringsidtosida:3,convertstringsidtosidw:3,copi:[],corporation1:2,correct:2,correspond:[],counter:2,cp_handl:2,cproc:[],cprovparam:2,cpuid:1,creat:[0,2],create_connect:2,create_consol:2,create_displac:[],create_file_from_handl:[],create_funct:2,create_inst:2,create_process:2,create_suspend:2,create_thread:2,createdisposit:3,createfile_callback:[],createfilea:[2,3],createfileacallback:[],createfilemappinga:3,createfilemappingw:3,createfilew:3,createopt:3,createprocessa:3,createprocessw:3,createremotethread:3,createsuspend:3,createthread:3,createtoolhelp32snapshot:3,creation:[],crecipientcert:3,cross:1,crypt:2,crypt_algo:2,crypt_algorithm_identifi:2,crypt_deletekeyset:2,crypt_export:[0,2],crypt_key_prov_info:2,crypt_user_keyset:0,cryptacquirecertificateprivatekei:3,cryptacquirecontexta:3,cryptacquirecontextw:[0,2,3],cryptcatadminacquirecontext:3,cryptcatadmincalchashfromfilehandl:3,cryptcatadminenumcatalogfromhash:3,cryptcatadminreleasecatalogcontext:3,cryptcatadminreleasecontext:3,cryptcatcataloginfofromcontext:3,cryptcontext:2,cryptdecodeobject:3,cryptdecryptmessag:3,cryptdestroykei:[2,3],cryptencodeobjectex:3,cryptencryptmessag:3,cryptexportkei:3,cryptgenkei:[2,3],cryptmsggetparam:3,crypto:1,cryptoapi:[1,2],cryptobj:2,cryptobject:2,cryptpars:2,cryptqueryobject:3,cryptreleasecontext:[0,3],cs_32bit:[],cs_64bit:[],cthread:[],ctx:2,ctype:[0,2,3],ctypes_funct:[2,3],ctypes_gener:[],curent:[],current:[0,3],current_process:[],current_profile_typ:[],current_thread:2,current_us:2,currentprocess:2,currentthread:[],currentvers:2,cuwqtwgls2gd5a:2,dai:[],dat:2,data:[0,2],dbg:2,dbg_continu:[],dbg_exception_not_handl:[],dbginterfac:[],dead:[],deadlock:[],deadthread:[],debug:1,debug_exeception_ev:[],debug_functionbp:2,debug_process:2,debug_str:[],debugactiveprocess:3,debugactiveprocessstop:3,debugbreak:3,debugbreakprocess:3,debugcontrol:[],debugg:1,debugger_membp_singlestep:2,debugger_print_ldrloaddl:2,debugingg:[],debugsetprocesskillonexit:3,decod:2,decor:[],decrypt:2,decryptpars:2,def:2,defin:[],definit:[],defint:[],del_bp:[],delet:[],demo:0,depend:2,deref:2,describ:[],descript:2,descriptor:[],descrption:2,desiredaccess:3,desktop:[0,2],dest:2,destin:[],destroi:2,detach:[],devic:2,deviceapi:2,deviceiocontrol:3,dict:2,didn:[],die:[],diff:2,differ:[],direct:[],directli:0,directoryhandl:3,disabl:[],disable_all_memory_breakpoint:[],disableallprivileg:3,disabledmemorybreakpoint:[],disassembl:[],disk:0,disp:[],dispatch:[],displac:[],displai:[],dll:[2,3],dll_load:2,dll_path:[],do_cpuid:[],doc:[],document:[2,3],doe:[2,3],don:2,done:2,dr0:[],dr1:[],dr2:[],dr3:[],dr6:[],dr7:[],drive:[1,2],drive_cdrom:[],drive_fix:2,drive_no_root_dir:[],drive_ramdisk:[],drive_remot:[],drive_remov:[],drive_unknown:[],driver:2,drx:[],dst:2,dummyunionnam:[],dump:2,duplic:0,duplicatehandl:3,dwadddisposit:3,dwauthnlevel:3,dwblobtyp:3,dwcapabl:3,dwcertencodingtyp:3,dwclscontext:3,dwcoinit:3,dwcontinuestatu:3,dwcreationdisposit:3,dwcreationflag:[2,3],dwdesiredaccess:3,dwexitcod:3,dwexpectedcontenttypeflag:3,dwexpectedformattypeflag:3,dwfileoffsethigh:3,dwfileoffsetlow:3,dwfindflag:3,dwfindtyp:3,dwfirstchanc:[],dwflag:[0,2,3],dwflagsandattribut:3,dwfreetyp:3,dwhandl:3,dwimplevel:3,dwindex:3,dwiocontrolcod:3,dwkeyspec:2,dwlen:3,dwlength:3,dwmaximumsizehigh:3,dwmaximumsizelow:3,dwmillisecond:3,dwmsgandcertencodingtyp:3,dwnumberofbytestomap:3,dwobjecttyp:3,dwoption:3,dword:[],dwoutbuflen:3,dwparamtyp:3,dwprocessid:[2,3],dwpropid:3,dwprovtyp:[0,2,3],dwservicest:3,dwservicetyp:3,dwsharemod:3,dwsize:3,dwstacksiz:3,dwstrtype:3,dwthreadaffinitymask:3,dwthreadid:3,dwtype:3,dynam:[],e24a88fa88:2,e2b3c97f:2,eabuff:3,each:0,ealength:3,earli:1,easi:2,eax:2,ebp:2,ebx:2,echo:2,econtext32:[],econtext64:[],econtextwow64:[],ecrypt_data_blob:2,ecx:2,edi:2,edit:[],edr7:[],edx:2,eeflag:2,eexception_debug_info32:[],eexception_debug_info64:[],eexception_point:[],eexception_record32:[],eexception_record64:[],eexception_record:[],eflag:2,ehcertstor:2,eip:2,element:0,elev:2,elif:[],els:2,emb:[],embd:[0,2],embed:[],enabl:2,enable_privileg:[],encod:[0,2],encount:[],encrypt:1,encryption_demo:2,end:2,endswith:2,engizuyhxgvqzrdrhu4g4:2,enhanc:[],enough:3,entri:2,enumer:2,enumservicesstatusexa:3,enumservicesstatusexw:3,enumwindow:3,environ:2,equal:3,errcheck:3,errno:2,error:[2,3],esec:[],esi:2,esp:2,establish:2,eudc:2,even:[],event:2,eventhandl:3,everi:2,ewpxyxnoaw5ndg9umrawdgydvqqhewdszwrtb25kmr4whaydvqqkexvnawnyb3nv:2,ewrnt1bsmtqwmgydvqqfeysymjk4nzkrmtq3ndq5ymutmtvhoc00zwjhltkzzjmt:2,exampl:1,exc:2,exc_addr:2,exc_cod:2,except:[1,2,3],exception_access_viol:2,exception_breakpoint:2,exception_continue_execut:2,exception_single_step:2,exceptionaddress:2,exceptioncod:2,exceptionflag:[],exceptioninform:2,exceptionrecord:2,exe:2,exec:2,execut:[1,2],execute_64bits_code_from_syswow:[],execute_python:2,execute_python_unsaf:[],exempl:3,exist:2,exit:2,exit_callback:[],exit_cod:2,exit_process:[],exit_thread:[],exitprocess:3,exitthread:3,exp:2,expect:[],expir:[],explan:[],explor:1,export_directori:[],export_nam:[],expr:[],extendedregist:[],extract:[0,2],extract_argu:2,f6f92166d7dd:2,f750e6c3:2,fail:[2,3],fake_modul:2,fals:[0,2,3],famili:[],far:[],fat32:2,fault:[],fault_addr:2,featur:[],ff556253:[],fhandl:2,field:[],file:[0,2,3],file_attribute_norm:3,file_h:2,file_map_all_access:3,fileattribut:3,filehandl:[2,3],filenam:[0,2],filesystem:2,filetyp:2,finaluncompresseds:3,find:2,firewal:2,firewallrul:[],first:[2,3],firsthandl:3,fixedinteractiveconsol:2,flag:[0,2,3],flallocationtyp:3,flnewprotect:3,floatsav:[],flprotect:3,follow:2,font:2,force_bit:[],forcibl:2,form:[],format:[2,3],forward:[],found:2,free:[],freeconsol:3,freespac:2,frm:[],from:[0,2],from_address:2,from_buff:[0,2],from_fil:[0,2],from_str:2,from_system_stor:[0,2],ftype:[],full:[],full_signature_inform:2,fullnam:2,func:2,func_getprocaddress32:[],func_getprocaddress64:[],func_nam:[2,3],func_result:2,func_strlena32:[],func_strlena64:[],func_strlenw32:[],func_strlenw64:[],functionbp:[],gate:1,gdef:2,gdi32:2,gdiplu:2,gdiplus_6595b64144ccf1df_1:2,gencrypt:2,gener:[1,2],generate_pfx:2,generate_selfsigned_certif:2,generate_syswow64_cal:[],generated_def:[2,3],generateinitvector:0,generic_read:3,geninitvector:0,genkei:[0,2],genkeyspars:2,genuineintel:[],get:2,get_cert:[0,2],get_cod:2,get_exception_bit:[],get_exception_cod:2,get_exception_context:2,get_firewallen:2,get_handle_from_fil:[],get_mapped_filenam:[],get_memory_breakpoint_at:[],get_nam:0,get_optionalhead:2,get_proc_family_model:[],get_signer_certif:[0,2],get_signer_data:[0,2],get_vendor_id:[],getattr:2,getcomputernamea:3,getcomputernamew:3,getcurrentprocess:3,getcurrentprocessornumb:3,getcurrentthread:3,getcurrentthreadid:3,getcursorpo:3,getdrivetypea:3,getdrivetypew:3,getexitcodeprocess:3,getexitcodethread:3,getextendedtcpt:3,getfileversioninfoa:3,getfileversioninfosizea:3,getfileversioninfosizew:3,getfileversioninfow:3,getift:3,getinterfaceinfo:3,getipaddrt:3,getlasterror:3,getlogicaldrivestringsa:3,getlogicaldrivestringsw:3,getlongpathnamea:3,getmappedfilenameawrapp:3,getmappedfilenamewwrapp:3,getmodulebasenameawrapp:3,getmodulebasenamewwrapp:3,getnamedsecurityinfoa:3,getnamedsecurityinfow:3,getpeernam:2,getpefil:[],getprocaddress32:[],getprocaddress64:[],getprocaddress:3,getprocessdeppolici:3,getprocessid:3,getprocessimagefilenameawrapp:3,getprocessimagefilenamewwrapp:3,getprocesstim:3,getsecurityinfo:3,getshortpathnamea:3,getsidsubauthor:3,getsidsubauthoritycount:3,getstdhandl:3,getsystemmetr:3,getthreadcontext:3,getthreadid:3,gettokeninform:3,getversionexa:3,getversionexw:3,getvolumeinformationa:3,getvolumeinformationw:3,getvolumenameforvolumemountpointa:3,getvolumenameforvolumemountpointw:3,getwindowmodulefilenamea:3,getwindowmodulefilenamew:3,getwindowrect:3,getwindowtexta:3,getwindowtextw:3,ggegtt4pwpqg8ch0jnrkl1fb3kzz7e34:2,github:[],give:[],given:[2,3],goal:[0,2],got:2,group:[],guess:[],gui:[],h1cki4tgezqzceunpnwv6dmuvpciqgeia5phojzyenknd0sx6eqzrynuz1gmn:2,hack:[],had:0,hadditionalstor:3,hakril:2,hand:[],handl:[1,2,3],handle_addr:2,handle_valu:2,handler:[2,3],handlerroutin:3,hanld:[],harddisk0:2,harddiskvolume2:2,hardwar:[],hardware_exec_bp:[],has:[2,3],hasattr:2,hashalgorithm:2,hashlib:2,have:[2,3],haven:0,hcatadmin:3,hcatinfo:3,hcertstor:3,hchainengin:3,hcryptkei:[0,2],hcryptmsg:3,hcryptprov:[2,3],hcryptprovorncryptkei:3,hdevic:3,heaven:1,heavili:3,hello:2,help:[2,3],helper:1,here:[2,3],hex:2,hexdigest:2,hexdump:2,hexpkei:3,hfile:3,hfilemappingobject:3,hhandl:3,hidden:[],hit:[],hkei:[2,3],hkey_current_us:2,hkey_local_machin:2,hmem:3,hmht7km6g8lsmfiga1udeqrlmemkrzbfmq0wcwydvqql:2,hmodul:3,hobject:3,hold:2,hook:1,horribl:[],host:2,hostnam:[],hprocess:3,hprov:3,hscmanag:3,hsnapshot:3,hsourcehandl:3,hsourceprocesshandl:3,hstore:[0,3],htargetprocesshandl:3,htemplatefil:3,hthread:3,http:[0,2],hwnd:3,hxbp:2,hxbreakpoint:2,iat:1,iat_create_fil:[],iat_entri:[],iat_hook:2,iatentri:2,iathook:[],ident:2,identif:[],iid:2,imagepath:2,imagepathnam:[],imm32:2,immedi:[],imp:[],implement:1,import_pfx:2,importerror:2,in073czyitg7mvhbexbofhgncixoufeyhwy1pygjousqsqzs4bj:2,inc:2,includ:[],increment:0,index:[0,1],indic:[],inetfwpolicy2:1,infinit:[2,3],infitin:2,info:2,infolevel:3,inform:[0,2],inherit:[],init:2,init_breakpoint:2,initi:0,initial_cod:2,initialis:2,initvector:0,inject:2,inmessageattribut:3,input_buffer_port:[],input_buffer_s:[],input_buffer_valu:[],instal:[],installd:2,instanc:2,instr:2,instruct:2,int3:[],integr:[],interact:2,interativeconsol:[],interest:[],interfac:[1,2],interface_typ:[],intern:[0,1],invalid:[],io_stack_input_buff:[],io_stack_input_buffer_len:[],iopl_1:[],iopl_2:[],iostatusblock:3,iphlpapierror:3,ipv4:2,ipv6:[],is_amd_proc:[],is_elev:[],is_exit:[],is_intel_proc:[],is_process_32_bit:[],is_sign:2,is_workst:[],is_wow_64:2,issuer:[0,2],item:2,its:[],itself:[],jmp:2,jnz:[],join:2,ju6ih:2,jump:[],just:[],k32:2,k32pe:2,k9dctgaoymff6qukabqidaqab:2,keep:[],kei:[0,2],kernel32:2,kernel32_error_check:[2,3],kernel32error:[0,2,3],kernel:[],kernelbas:2,key_info:[0,2],key_read:[],keyboard:2,keypair:0,keyprovinfo:2,keytyp:0,keyvalu:2,keyword:3,khiu4to5jf25xthf2g:2,kill:2,killonexit:3,knockin:[],know:3,known:[],kwarg:2,kwd:[],l2ec6cyjdqc6hcqbncsbjvq6qgtqbyn:2,l2nlcnrzl01py1dpblbyb1bdqtiwmtffmjaxms0xmc0xos5jcnqwdaydvr0taqh:2,l56:[],lab:[],label:2,lait:2,last:[2,3],lastbranchfromrip:[],lastbranchtorip:[],lastexceptionfromrip:[],lastexceptiontorip:[],layout:2,ldr:2,ldrloaddll:[2,3],ldrloaddll_32_to_64:[],left:0,len0:[],len1:[],len2:[],len3:[],len:[2,3],length:3,let:2,level:[],librari:[0,2],like:[],line:[2,3],linebuf:2,linkhandl:3,linktarget:3,list:[0,2],listen:2,lkd:[],load:[1,2,3],load_dll:[],load_librari:[],loadedmodul:2,loadlibrari:[],loadlibrarya:3,loadlibraryw:3,local:[],local_addr:[],local_address:[],local_debugg:2,local_debugger_remote_process:2,local_handl:[],local_port:2,localdebugg:1,localfre:3,localhost:2,logic:[1,2],logicaldr:2,look:2,lookupaccountsida:3,lookupaccountsidw:3,lookupprivilegevaluea:3,lookupprivilegevaluew:3,loop:2,lower:2,lpaddress:3,lpapplicationnam:3,lparam:3,lpbaseaddress:3,lpbasenam:3,lpbuffer:3,lpbytesreturn:3,lpcbdata:3,lpcommandlin:3,lpcontext:3,lpcreationtim:3,lpcurrentdirectori:3,lpdata:3,lpdatabasenam:3,lpdebugev:3,lpdevicenam:3,lpdirectori:3,lpdwhandl:3,lpenumfunc:3,lpenviron:3,lpexitcod:3,lpexittim:3,lpfile:3,lpfilemappingattribut:3,lpfilenam:3,lpfilesystemflag:3,lpfilesystemnamebuff:3,lpflag:3,lpfloldprotect:3,lpimagefilenam:3,lpinbuff:3,lpkerneltim:3,lplpbuffer:3,lpluid:3,lpmachinenam:3,lpmaximumcomponentlength:3,lpname:3,lpnsize:3,lpnumberofbytesread:3,lpnumberofbyteswritten:3,lpoper:3,lpoutbuff:3,lpoverlap:3,lpparamet:3,lpperman:3,lppoint:3,lpprocessattribut:3,lpprocessinform:3,lpprocnam:3,lprect:3,lpreferenceddomainnam:3,lpreserv:3,lpresumehandl:3,lprootpathnam:3,lpsecurityattribut:3,lpservic:3,lpservicesreturn:3,lpsid:3,lpstartaddress:3,lpstartupinfo:3,lpstring1:3,lpstring2:3,lpstring:3,lpsubblock:3,lpsubkei:[2,3],lpsystemnam:3,lpszlongpath:3,lpszprivileg:[],lpszshortpath:3,lpszstoreprovid:3,lpszstructtyp:3,lpszvolumemountpoint:3,lpszvolumenam:3,lptargethandl:3,lptargetpath:3,lpte:3,lpthreadattribut:3,lpthreadid:3,lptstrfilenam:3,lptype:3,lpusertim:3,lpv:3,lpvalu:3,lpvaluenam:3,lpversioninform:3,lpvolumenamebuff:3,lpvolumeserialnumb:3,lsa_unicode_str:[],lstrcmpa:3,lstrcmpw:3,machin:[],made:[],magic:2,mai:[],main:0,major:[],make:1,manag:[0,1],mandatori:3,mani:[],manual:2,manuali:[],map:[],mape:[],mapviewoffil:3,mask:[],match:2,maximumlength:[],mayb:2,mean:3,mem:2,mem_access:[],mem_commit:3,mem_releas:3,membp:[],memori:[0,2],memory_basic_inform:[],memory_breakpoint:[],memory_st:[],memorybreakpoint:2,memoryinform:3,memoryinformationclass:3,memoryinformationlength:3,messag:[0,2],metavar:2,method:[0,2],microsoft:[0,2],might:[],miifbdcca:2,minor:[],mismatch:[],miss:3,mnemon:[],mode:[],model:1,modul:[0,1,2,3],module_to_trac:2,modulefilenam:3,modulehandl:3,more:2,most:[2,3],mov:2,ms679286:[],ms679287:[],ms679334:[],ms679335:[],ms680351:[],ms680545:[],ms680587:[],ms681403:[],msctf:2,msdn:[0,2],msg:0,msvcr90:2,msxml6:2,mteymdm5mzfafw0xodaxmteymdm5mzfamhaxczajbgnvbaytalvtmrmweqydvqqi:2,much:[],mui:2,multipleinstr:2,must:[2,3],mxcsr:[],my_ex:[],my_fail_kei:2,my_secret_kei:2,mydebugg:2,myfunctionbp:2,myinterfac:[],mykei:2,mypassword:2,name:[0,2],name_valu:2,nametyp:0,narg:2,nativ:1,native_cod:2,native_exec:[1,2],nativeutil:1,nb_cert:[0,2],nb_repeat:2,nb_signer:[0,2],nbufferlength:3,need:[2,3],neededparamat:3,neededparamet:3,neg:2,net_fw_action_:[],net_fw_action_allow:[],net_fw_action_block:[],net_fw_profile2_domain:2,net_fw_profile2_priv:2,net_fw_profile2_publ:2,net_fw_profile_type2_:[],net_fw_rule_dir_in:[],net_fw_rule_dir_out:[],net_fw_rule_direction_:[],netfwpolicy2clsid:2,network:1,new_align:[],new_in_memori:[0,2],new_protect:[],newaccessprotect:3,newli:2,newstat:3,nfilesystemnames:3,nfunc:2,nice:[],ninbuffers:3,nindex:3,nmaxcount:3,nnumberofbytestoread:3,nnumberofbytestowrit:3,non:2,none:[0,2,3],nop:2,normal:2,note:0,notepad:2,noth:3,noumex:[],noutbuffers:3,now:[0,2],now_valu:2,nshowcmd:3,nsize:3,nstdhandl:3,nsubauthor:3,ntalpcacceptconnectport:3,ntalpcconnectport:3,ntalpcconnectportex:3,ntalpccreateport:3,ntalpcsendwaitreceiveport:3,ntcreatefil:[2,3],ntcreatefile_iat:2,ntcreatethreadex:3,ntcreatethreadex_32_to_64:[],ntdll:2,ntf:2,ntgetcontextthread:3,ntgetcontextthread_32_to_64:[],ntopendirectoryobject:3,ntopenev:3,ntopensymboliclinkobject:3,ntprotectvirtualmemori:3,ntquerydirectoryobject:3,ntqueryinformationprocess:3,ntqueryinformationprocess_32_to_64:[],ntqueryinformationthread:3,ntqueryinformationthread_32_to_64:[],ntqueryobject:3,ntquerysymboliclinkobject:3,ntquerysysteminform:3,ntqueryvirtualmemori:3,ntqueryvirtualmemory_32_to_64:[],ntsetcontextthread:3,ntsetcontextthread_32_to_64:[],ntwow64readvirtualmemory64:3,ntwow64writevirtualmemory64:3,number:0,numberofbytestoprotect:3,numberparamet:[],nvolumenames:3,nwashington1:2,nyolocertif:2,o4ibgdccaxwwhwydvr0lbbgwfgykkwybbagcnwodbgyikwybbquhawmwhqydvr0o:2,object:[0,1,2],objectattribut:[2,3],objectinform:3,objectinformationclass:3,objectinformationlength:3,objectnam:2,objecttyp:3,occur:[],offer:0,offset:2,old:[],old_protect:[],oldaccessprotect:3,oldvalu:3,ole32:2,oleacc:2,oleaut32:2,on_create_process:[],on_create_thread:[],on_except:2,on_exit_process:[],on_exit_thread:[],on_load_dl:[],on_output_debug_str:[],on_rip:[],on_single_step:2,on_unload_dl:[],onc:[],one:[0,2],ones:[],onli:2,open:2,open_exist:3,open_reg_hook:2,open_subkei:[],openasself:3,openeventa:3,openeventw:3,openkei:2,openprocess:3,openprocesstoken:3,openscmanagera:3,openscmanagerw:3,openthread:3,openthreadtoken:3,oper:[],operand:[],ord:2,order:[],ordereddict:[],ordin:[2,3],origin:[],originali:[],osnam:2,other:[],ouput:2,our:2,our_connect:2,ourself:2,out:0,out_2_or_4:[],out_4:[],out_ioctl:[],outmessageattribut:3,outnam:2,output:2,own:[],owner:2,p1home:[],p2home:[],p3home:[],p4home:[],p5home:[],p6home:[],package_35_for_kb3128650:2,page:[1,2],page_execute_readwrit:[2,3],page_noaccess:2,page_readwrit:[2,3],pain:[],pair:2,panel:2,param:2,param_nam:3,paramet:3,parent:[],pars:1,parse_arg:2,parser:2,part:[],partition2:2,pass:3,password:[0,2],path:2,pathnam:2,pathtofil:3,pauthlist:3,pbcertencod:3,pbdata:[2,3],pbdecrypt:3,pbencod:3,pbencryptedblob:3,pbhash:3,pblock:3,pbtobeencrypt:3,pca:2,pcbbytesneed:3,pcbdata:3,pcbdecrypt:3,pcbencod:3,pcbencryptedblob:3,pcbhash:3,pcbstructinfo:3,pccert_context:0,pcert:3,pcertcontext:3,pcertid1:3,pcertid2:3,pchainpara:3,pdecryptpara:3,pdwcontenttyp:3,pdwdatalen:3,pdwformattyp:3,pdwkeyspec:3,pdwmsgandcertencodingtyp:3,pdwsize:3,pdwtype:3,pe_pars:2,peb:1,peb_addr:[],peb_syswow:[],pefil:[1,2],pencodepara:3,pencryptpara:3,pendtim:3,perform:[],perform_cal:[2,3],pesect:2,peus:3,pextens:3,pfcallerfreeprovorncryptkei:3,pfw_tmp_key_contain:2,pfx:[0,2],pfxexportcertstoreex:3,pfxfile:2,pfximportcertstor:[2,3],pfxpassword:2,pgactionid:3,pgsubsystem:3,phcatadmin:3,phcertstor:3,phcryptprovorncryptkei:3,phkei:3,phkresult:[2,3],phmsg:3,phprevcatinfo:3,phprov:3,pid:2,piftabl:3,pipaddrt:3,pkcs12_no_persist_kei:0,pkeyprovinfo:3,place:[],plai:2,plu:[],pobjectnam:3,poc:2,point:[0,3],pointer:0,pop:[],pop_calc_32:2,pop_calc_64:2,pop_shel:[],port:2,portattribut:3,portcontext:3,porthandl:3,portnam:3,possess:[],possibl:[],post:2,pouet:[],ppchaincontext:3,ppdacl:3,ppfx:[2,3],ppid:2,pprevcertcontext:3,pprint:2,ppsacl:3,ppsecuritydescriptor:3,ppsidgroup:3,ppsidown:3,ppstorecontext:3,ppszerror:3,ppv:3,ppvcontext:3,ppxchgcert:3,prefix:[],present:[],preserved1:3,preserved3:3,pretti:[],prevent:[],previousst:3,print:2,printer:2,printunicodestr:2,privat:2,privileg:[],pro:2,problabl:0,problem:[],proc:2,process32first:3,process32next:3,process:[1,3],process_all_access:3,processhandl:3,processid:2,processinform:3,processinformationclass:3,processinformationlength:3,processor:[],product:2,product_typ:2,profession:[],profil:2,prog:2,program:[],progress:1,project:[],properti:0,prot:[],protect:[0,2],protocol:1,prov:[0,2],prov_rsa_ful:2,provid:[0,3],proxi:3,pscatinfo:3,psecdesc:3,psid:3,psignaturealgorithm:3,pstarttim:3,psubjectissuerblob:3,pszcontain:[0,3],pszfilenam:3,pszgroupnam:3,psznamestr:3,pszobjid:2,pszprovid:[0,3],pszx500:3,ptcprow:3,ptcptabl:3,ptime:3,ptr:[],pulen:3,punkout:3,purpos:[],push:2,put:1,pvdata:3,pvencod:3,pvfindpara:3,pvobject:3,pvoid:2,pvpara:3,pvparamet:3,pvreserv:3,pvstructinfo:3,pvtypepara:3,pwszcontainernam:2,pwszprovnam:2,pwvtdata:3,pycod:[],pyhkei:2,python27:2,python32:2,python64:2,python:2,python_cod:2,python_execut:2,pythondll_modul:2,pythonforwindow:2,pythonforwindowstmpcontain:2,pythont:3,pythonxx:2,qhsszio1k5n1udlpfwtn29buglsrttxpv5ocfntlo:2,queri:[],query_memori:[],querydosdevicea:3,querydosdevicew:3,queryworkingsetexwrapp:3,queryworkingsetwrapp:3,question:2,quit:[],qword:[],r10:2,r11:2,r12:2,r13:2,r14:2,r15:2,rais:[0,2,3],randint:[],random:0,rang:2,raw64:[],raw:[0,2],raw_cert:2,raw_seri:[0,2],rax:2,rbp:2,rbx:2,rclsid:3,rcx:2,rdata:2,rdi:2,rdx:2,read:[0,2],read_byt:[],read_dword:[],read_memori:2,read_memory_into:[],read_ptr:2,read_qword:[],read_short:[],read_str:[],read_wstr:2,readfil:3,readprocessmemori:3,real:0,real_funct:2,receivemessag:3,receivemessageattribut:3,recent:[2,3],record:[],redirect:[],refcount:0,refer:[],reg:2,reg_nam:[],regclosekei:3,reggetvaluea:3,reggetvaluew:3,regist:2,register_start:2,registered_own:2,registeredown:2,registri:1,regopenkeyexa:[2,3],regopenkeyexa_iat:2,regopenkeyexacallback:2,regopenkeyexw:3,regqueryvalueexa:3,regqueryvalueexw:3,regroup:[],reject:[],relat:1,releas:2,reli:3,reloc:2,remot:[],remote_addr:2,remote_address:[],remote_calc:[],remote_cod:2,remote_host:[],remote_port:2,remote_process:2,remote_proto:[],remote_veh_segv:2,remotectyp:1,remoteloadedmodul:2,remotemanualloadlibrai:[],remotepeb32:[],remotepeb64:[],remotepeb:2,remotepythonerror:2,remotewinunicodestr:2,remov:[],remove_hook:[],removevectoredexceptionhandl:3,replac:2,report_ctx_diff:2,repr:2,repres:0,represent:[0,2],req:[],request:1,requir:2,requiredbuffers:3,requiredserversid:3,res:2,res_15:[],res_1:[],res_3:[],res_5:[],reserv:3,reset:2,resolut:[],resolv:[],respect:2,restartscan:3,restor:[],restore_all_memory_breakpoint:[],result:[2,3],resultat:[],resum:2,resumethread:3,ret:2,ret_trigg:2,ret_valu:2,retriev:0,retrycr:[0,2],returnedlength:3,returnlength:3,returnsingleentri:3,revers:[],rewrit:2,rewritebreakpoint:2,rewrot:[],rgprecipientcert:3,rgprovparam:2,right:[],riid:3,rip:2,rip_info:[],rlxmnhc8jtgzk96czmdbpauuwdachnmtkiwqf6axzsbbwsekqejvdbygaocuiyh4:2,root:2,root_stor:2,rsa:2,rsi:2,rsp:2,rsrc:2,rtldecompressbuff:3,rtype:[],rule:[],run:2,rw0:[],rw1:[],rw2:[],rw3:[],rwx:2,sad:[],safe:2,sai:2,sam:[],samdesir:[2,3],same:[],sampl:[0,1],save:0,sbgna5cjtxqc7iyp9c7rxbmthv5bnftonsn6d9n8zu:2,sc_manager_all_access:3,scale:[],se_debug_nam:[],search:1,secret:2,section:2,secur:2,securityinfo:3,see:[0,2],seg:[],segc:[],segd:[],sege:[],segf:[],segfault:[],segg:[],segment:[],segss:[],select:2,selector:[],self:[0,2,3],selfsign:0,send:2,sendmessag:3,sendmessageattribut:3,serial:[0,2],serv:2,server:[],serversecurityrequir:3,servic:[1,2],service_continue_pend:[],service_file_system_driv:[],service_interactive_process:[],service_kernel_driv:2,service_nam:[],service_paus:[],service_pause_pend:[],service_run:2,service_runs_in_system_process:[],service_start_pend:[],service_stop:[],service_stop_pend:[],service_win32_own_process:[],service_win32_share_process:2,servicea:2,servicestatu:2,set:[2,3],set_context:2,set_default:2,set_hook:2,set_syswow_context:[],setattr:2,setconsolectrlhandl:3,setstdhandl:3,settcpentri:3,setthreadaffinitymask:3,setthreadcontext:3,settokeninform:3,setup:2,setup_target_context:2,sha1:2,sha256:2,shareaccess:3,shell32:2,shellcod:[],shellexecutea:3,shellexecutew:3,should:0,show_window:[],sid:3,side:[],sign:[0,2],sign_info:2,signatur:[1,2],signature_algo:[0,2],signer:[0,2],signer_certif:[],simpl:[0,2],simple_x64:[1,2],simple_x86:[1,2],simpler:[],simpli:[],singl:[],single_step:2,single_step_count:2,singlesteponwrit:2,singlesteppingdebugg:2,size:2,sizeof:[],sizeofcod:2,sleep:2,socket:1,softwar:2,softwaretyp:2,sofwar:2,sogeti:[],some:[0,2,3],some_export:2,someth:[],soon:[],sourc:0,space:[],special:3,specifi:2,split:2,src:2,stack:2,stackoverflow:2,standard:[],standard_bp:[],start:2,start_addr:2,start_address:[],start_regist:2,start_valu:2,startswith:2,startup:2,state:2,staticcach:2,statu:2,stdin:3,stdout:[],step:[],still:[],still_act:[],storag:3,store:[0,2],store_const:2,store_nam:0,store_tru:2,str:[0,2],string:[0,2],stringsid:3,strip:2,strlen:[],strlena32:[],strlena64:[],strlenw32:[],strlenw64:[],struct:[],structur:[0,1],stub:[],stuff:2,subclass:3,subcommand:2,subject:0,subkei:2,subkeys_nam:2,submodul:[],subpars:2,success:[],support:0,sure:[],surkei:[],suspend:2,suspendthread:3,svchost:2,sys:2,system32:2,system:[0,1],systeminform:3,systeminformationclass:3,systeminformationlength:3,syswow64:[1,2],syswow64apiproxi:[],syswow:[],szoid_nist_aes128_cbc:0,szoid_nist_aes192_cbc:0,szoid_nist_aes256_cbc:0,szoid_oiwsec_descbc:0,szoid_rsa_des_ede3_cbc:0,szoid_rsa_sha256rsa:2,szpassword:[2,3],tableclass:3,tagclsctx:3,tagcoinit:3,tagthreadentry32:[],take:3,talk:[],target:2,target_addr:2,target_fil:2,target_func:2,target_host:2,target_nam:2,target_pag:2,target_port:2,targetedbit:[],tcp4:[],tcp4connect:[],tcp6:[],tcp6connect:[],tcp:2,tcp_table_owner_pid_al:3,teb:[],teb_bas:[],techniqu:[],tell:0,temporari:0,termin:[],terminaison:2,terminateprocess:3,terminatethread:3,test:2,test_cod:2,test_code_x64:2,test_code_x86:2,text:2,th32processid:3,thei:2,them:[],themself:[],thi:[0,2,3],thing:3,thisit:[],those:[],thread32first:3,thread32next:3,thread:[1,2,3],thread_all_access:3,thread_exec:2,threadhandl:3,threadinform:3,threadinformationclass:3,threadinformationlength:3,three:[],through:[],tid:[],time:[0,2,3],time_info:[],timeinfo:[],timeout:3,tmp:2,to_dump:[],todo:[],token:[],tokenhandl:3,tokeninform:3,tokeninformationclass:3,tokeninformationlength:3,trace:2,traceback:[2,3],transform:[],transform_type_to_remote32bit:[],transform_type_to_remote64bit:[],transpar:3,tri:3,trigger:2,trivial:[],trust:[0,2],trust_e_nosignatur:2,try_generate_stub_target:[],tupl:[],two:[],txt:2,type:[0,2],typeerror:3,typenam:2,ucchmax:3,uexitcod:3,ugli:[],ukvab:2,ulaf:3,ulong64:[],ulopt:[2,3],ultra:[],uncompressedbuff:3,uncompressedbuffers:3,unicod:[],unicode_string_addr:2,unknow:[],unknown1:3,unknown2:3,unknown:[2,3],unload_dl:[],unstabl:[],usabl:[],use:[0,2],used:[0,2],useful:2,user:2,usermodetim:2,usernam:[],using:[0,1],utf16:[],utf8:[],util:[1,2],uxthem:2,valid:2,valu:[0,2,3],value_nam:[],valueerror:2,vari:[],variabl:2,variant_bool:2,variou:3,vector:0,vectorcontrol:[],vectoredexcept:1,vectoredhandl:3,vectorregist:[],veh:2,veh_segv:2,vendorid:[],ver_nt_domain_control:[],ver_nt_serv:[],ver_nt_workst:2,verif:2,verifi:2,verqueryvaluea:3,verqueryvaluew:3,version:2,version_nam:2,via:2,view:[],vif:[],vip:[],virtual_alloc:2,virtual_fre:[],virtual_protect:[],virtualalloc:[1,2],virtualallocex:3,virtualfre:3,virtualfreeex:3,virtualprotect:[2,3],virtualprotectex:3,virtualqueryex:3,vista:[],vol:2,volatil:2,volum:1,vsvmktr:2,vtabl:[],vtbtmfegccsgaqufbzachkvodhrwoi8vd3d3lm1py3jvc29mdc5jb20vcgtpb3bz:2,wai:2,wait:2,waitfordebugev:3,waitforsingleobject:3,want:[],wchvemxqxk5eofne6yekuarbgbmnwltfrpwklmvtnl9r:2,whatev:[],when:[],where:[],which:[],whole:[],wide:[],win32:[],win32_logicaldisk:2,win32_process:2,wincfunc:[],windef:2,window:1,windowfrompoint:3,windows_info:2,windowscert:2,windowserror:[2,3],windowsvers:2,winerror:0,winfunc:[2,3],winmm:2,winobject:2,winoject:2,winprocess:[],winproxi:[1,2],winstruct:2,winsx:2,winthread:2,wintrust:1,winunicodestr:2,winverifytrust:3,without:[2,3],wmi:1,wmi_request:2,wmirequest:2,won:[],word:[],work:[1,2],workaround:[],would:2,wow64disablewow64fsredirect:3,wow64enablewow64fsredirect:3,wow64fsenableredirect:3,wow64getthreadcontext:3,wow64revertwow64fsredirect:3,wow64setthreadcontext:3,wrap:[],wrapper:[0,3],write:[0,2],write_byt:[],write_code_in_target:2,write_dword:[],write_memori:2,write_qword:[],write_short:[],writefil:3,writeprocessmemori:3,wrote:2,wstring:[],wstring_addr:2,wvalu:2,x000:2,x001:2,x00:2,x00u:[],x010:2,x01:2,x01t:2,x02:2,x02us1:2,x03:2,x03u:2,x040:2,x04:2,x04f:[],x05:2,x05y:2,x06:2,x07:2,x07redmond1:2,x08:2,x0b0:2,x0c:2,x0e:2,x100:2,x10:2,x10w:2,x11:2,x11u:2,x12x:2,x130:2,x133:2,x13:2,x14:2,x14f:2,x151:2,x15microsoft:2,x17:2,x18:2,x19:2,x1am:2,x1av:2,x1b:2,x1c:2,x1e0:2,x1f:2,x64:[1,2],x64_cpuid:[],x7f:2,x80:2,x80v:2,x81:2,x82:2,x841:2,x84:[],x84qy:2,x86:[1,2],x86_cpuid:[],x86_microsoft:2,x86cpuidresult:[],x86h:2,x870:2,x89:2,x8b:[],x8ba:[],x8bn:[],x8bq:[],x8c:2,x8ez:2,x90:2,x91:2,x93:2,x94:2,x977:[],x99cea:2,xa0:2,xa2d:2,xa4:2,xa6:2,xa6uo:2,xaahpj:2,xaam:2,xabnzr:2,xabo:2,xac:2,xad:2,xaf:2,xb2:2,xb3:2,xb8:2,xb9:2,xb9k:2,xbb:2,xbbybpu6:2,xbc:2,xc0:2,xc0bbbb:[],xc2:2,xc2rg:2,xc30:2,xc3:[],xc6:2,xc7:[],xc8:2,xca:2,xcc:2,xcctv:2,xcd:2,xce:2,xd0z:2,xd1n:2,xd2m:2,xd4:2,xd4j:2,xd8:[],xd8t:2,xd9:2,xdc:2,xe0lwf:2,xe1:2,xe3:2,xe5:2,xe7:2,xe8:2,xe9:2,xeb:[],xec:2,xeckk:2,xed9:2,xed:2,xedf:2,xee:[],xef1:[],xef:[],xf2:2,xf3:2,xf5:2,xf7:2,xf8:2,xf9:2,xfal:2,xfd:2,xfe:[],xor:[],y3jsl01py1dpblbyb1bdqtiwmtffmjaxms0xmc0xos5jcmwwyqyikwybbquhaqe:2,yaeno:2,yet:0,ygawibagitmwaaaqzuwyxemckydgaaaaabbjanbgkqhkig9w0baqsf:2,yield:[],yolocertif:2,yolohxbp:2,yop:2,you:2,your:[],yourself:[],yun:2,z5pmuf8va9tmfqg:2,zdexmge1yzq1ntuymb8ga1udiwqymbaafkkpajmofssxem2q:2,znqgq29ycg9yyxrpb24xgjaybgnvbamteu1py3jvc29mdcbxaw5kb3dzmiibijan:2},titles:["9. windows.crypto – CryptoAPI","Welcome to PythonForWindows’s documentation!","13. Samples of code","4. windows.winproxy – Windows API"],titleterms:{"function":3,The:[],Using:[],api:3,argument:[],assembl:[],breakpoint:[],callback:[],certif:[0,2],certificatecontext:0,check:[],code:2,com:2,compon:0,connect:[],context:[],cpuid:[],cross:[],cryptcontext:0,crypto:[0,2],cryptoapi:0,cryptobject:0,current:2,current_process:2,currentprocess:[],currentthread:[],debug:2,debugg:2,decrypt:0,demo:2,disablewow64fsredirect:[],document:1,drive:[],earli:[],ehcertstor:0,encrypt:[0,2],exampl:3,except:[],execut:[],explor:2,firewal:[],functionbp:2,gate:[],gener:0,generate_kei:0,generate_pfx:0,generate_selfsigned_certif:0,handl:[],heaven:[],helper:[],hook:2,iat:2,iatentri:[],implement:[],import_pfx:0,indic:1,inetfwpolicy2:2,info:[],inform:[],interfac:[],intern:[],keyvalu:[],load:[],loadedmodul:[],local:2,localdebugg:2,logic:[],make:2,manag:[],model:[],modul:[],nativ:2,native_exec:[],nativeutil:[],network:2,object:[],pars:[],pe_pars:[],peb:2,pefil:[],pointer:[],process:2,progress:[],protocol:[],put:[],pyhkei:[],pythonforwindow:1,record:[],registri:2,relat:[],remot:2,remotectyp:[],request:2,sampl:2,servic:[],signatur:[],signaturedata:[],simple_x64:[],simple_x86:[],singl:2,socket:2,step:2,structur:[],system:2,syswow64:[],tabl:1,tester:2,testeur:[],thread:[],token:[],type:[],using:2,util:[],vector:[],vectoredexcept:2,virtualalloc:3,virtualprotect:[],volum:[],welcom:1,window:[0,2,3],winprocess:2,winproxi:3,winthread:[],wintrust:2,wmi:2,work:[],x64:[],x86:[]}}) \ No newline at end of file diff --git a/docs/build/html/service.html b/docs/build/html/service.html index 1d7237d..79c0959 100644 --- a/docs/build/html/service.html +++ b/docs/build/html/service.html @@ -6,7 +6,7 @@ - 2.7. Service — PythonForWindows 0.2 documentation + 2.7. Service — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + +
    @@ -198,7 +199,7 @@

    This Page

    @@ -231,13 +232,13 @@
  • previous |
  • - - + +
    \ No newline at end of file diff --git a/docs/build/html/utils.html b/docs/build/html/utils.html index e4bc134..960a8ff 100644 --- a/docs/build/html/utils.html +++ b/docs/build/html/utils.html @@ -6,7 +6,7 @@ - 5. windows.utils – Windows Utilities — PythonForWindows 0.2 documentation + 5. windows.utils – Windows Utilities — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - +
    @@ -80,7 +82,7 @@ like VirtualProtect
    if is_process_32_bits:
         def pop_calc_64():
             with windows.utils.DisableWow64FsRedirection():
    -            return windows.utils.create_process(r"C:\Windows\system32\calc.exe", True)
    +            return windows.utils.create_process(r"C:\Windows\system32\calc.exe", True)
     
    @@ -173,7 +175,7 @@ Useful in injection of GUI process

    This Page

    @@ -206,12 +208,12 @@ Useful in injection of GUI process

  • previous |
  • - + \ No newline at end of file diff --git a/docs/build/html/various.html b/docs/build/html/various.html index 7b7f3a5..b6a2fcb 100644 --- a/docs/build/html/various.html +++ b/docs/build/html/various.html @@ -6,7 +6,7 @@ - 2. The windows objects — PythonForWindows 0.2 documentation + 2. The windows objects — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -122,7 +124,7 @@ parts are accessible.

    This Page

    @@ -155,12 +157,12 @@ parts are accessible.

  • previous |
  • - + \ No newline at end of file diff --git a/docs/build/html/volume.html b/docs/build/html/volume.html index fa4cca8..b0ac3a3 100644 --- a/docs/build/html/volume.html +++ b/docs/build/html/volume.html @@ -6,7 +6,7 @@ - 2.8. Volume – The logical drives — PythonForWindows 0.2 documentation + 2.8. Volume – The logical drives — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + + @@ -135,7 +136,7 @@

    This Page

    @@ -168,13 +169,13 @@
  • previous |
  • - - + + \ No newline at end of file diff --git a/docs/build/html/windows.html b/docs/build/html/windows.html index 916fef5..672bded 100644 --- a/docs/build/html/windows.html +++ b/docs/build/html/windows.html @@ -6,7 +6,7 @@ - 1. The windows module — PythonForWindows 0.2 documentation + 1. The windows module — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -143,7 +145,7 @@ It also offers some submodules aimed to help the interfacing with
    -network = <windows.winobject.network.Network object at 0x04FC0C30>
    +network = <windows.winobject.network.Network object at 0x04C87C90>

    Object of class windows.winobject.network.Network

    @@ -184,7 +186,7 @@ It also offers some submodules aimed to help the interfacing with
    -registry = <windows.winobject.registry.Registry object at 0x04FC0C50>
    +registry = <windows.winobject.registry.Registry object at 0x04C87CB0>

    Object of class windows.winobject.registry.Registry

    @@ -307,7 +309,7 @@ It also offers some submodules aimed to help the interfacing with

    This Page

    @@ -340,12 +342,12 @@ It also offers some submodules aimed to help the interfacing with previous | - + \ No newline at end of file diff --git a/docs/build/html/winproxy.html b/docs/build/html/winproxy.html index e07570b..332c35d 100644 --- a/docs/build/html/winproxy.html +++ b/docs/build/html/winproxy.html @@ -6,7 +6,7 @@ - 4. windows.winproxy – Windows API — PythonForWindows 0.2 documentation + 4. windows.winproxy – Windows API — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -168,6 +170,7 @@ It also heavily relies on CertAddCertificateContextToStore:

    +
    CertAddCertificateContextToStore(hCertStore, pCertContext, dwAddDisposition, ppStoreContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    + +
  • CertCompareCertificate:

    +
    CertCompareCertificate(dwCertEncodingType, pCertId1, pCertId2)
    +This function does not raise is compare has failed:
    +        return 0 if cert are NOT equals
    +
    +Errcheck:
    +   Nothing special
    +
    +
    +
  • +
  • CertCreateCertificateContext:

    +
    CertCreateCertificateContext(dwCertEncodingType, pbCertEncoded, cbCertEncoded)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertCreateSelfSignCertificate:

    +
    CertCreateSelfSignCertificate(hCryptProvOrNCryptKey, pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime, pEndTime, pExtensions)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertDuplicateCertificateContext:

    +
    CertDuplicateCertificateContext(pCertContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertEnumCertificateContextProperties:

    +
    CertEnumCertificateContextProperties(pCertContext, dwPropId)
    +Errcheck:
    +   Nothing special
    +
    +
    +
  • +
  • CertEnumCertificatesInStore:

    +
    CertEnumCertificatesInStore(hCertStore, pPrevCertContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertFindCertificateInStore:

    +
    CertFindCertificateInStore(hCertStore, dwCertEncodingType, dwFindFlags, dwFindType, pvFindPara, pPrevCertContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertGetCertificateChain:

    +
    CertGetCertificateChain(hChainEngine, pCertContext, pTime, hAdditionalStore, pChainPara, dwFlags, pvReserved, ppChainContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertGetCertificateContextProperty:

    +
    CertGetCertificateContextProperty(pCertContext, dwPropId, pvData, pcbData)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertGetNameStringA:

    +
    CertGetNameStringA(pCertContext, dwType, dwFlags, pvTypePara, pszNameString, cchNameString)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertGetNameStringW:

    +
    CertGetNameStringW(pCertContext, dwType, dwFlags, pvTypePara, pszNameString, cchNameString)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertOpenStore:

    +
    CertOpenStore(lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertStrToNameA:

    +
    CertStrToNameA(dwCertEncodingType, pszX500, dwStrType, pvReserved, pbEncoded, pcbEncoded, ppszError)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CertStrToNameW:

    +
    CertStrToNameW(dwCertEncodingType, pszX500, dwStrType, pvReserved, pbEncoded, pcbEncoded, ppszError)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • CoCreateInstance:

  • +
  • ConvertSidToStringSidW:

    +
    ConvertSidToStringSidW(Sid, StringSid)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • ConvertStringSidToSidA:

    +
    ConvertStringSidToSidA(StringSid, Sid)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • ConvertStringSidToSidW:

    +
    ConvertStringSidToSidW(StringSid, Sid)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • CreateFileA:

  • +
  • CryptAcquireContextA:

    +
    CryptAcquireContextA(phProv, pszContainer, pszProvider, dwProvType, dwFlags)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptAcquireContextW:

    +
    CryptAcquireContextW(phProv, pszContainer, pszProvider, dwProvType, dwFlags)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • CryptCATAdminAcquireContext:

  • +
  • CryptDecryptMessage:

    +
    CryptDecryptMessage(pDecryptPara, pbEncryptedBlob, cbEncryptedBlob, pbDecrypted, pcbDecrypted, ppXchgCert)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptDestroyKey:

    +
    CryptDestroyKey(hKey)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptEncodeObjectEx:

    +
    CryptEncodeObjectEx(dwCertEncodingType, lpszStructType, pvStructInfo, dwFlags, pEncodePara, pvEncoded, pcbEncoded)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptEncryptMessage:

    +
    CryptEncryptMessage(pEncryptPara, cRecipientCert, rgpRecipientCert, pbToBeEncrypted, cbToBeEncrypted, pbEncryptedBlob, pcbEncryptedBlob)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptExportKey:

    +
    CryptExportKey(hKey, hExpKey, dwBlobType, dwFlags, pbData, pdwDataLen)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptGenKey:

    +
    CryptGenKey(hProv, Algid, dwFlags, phKey)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptMsgGetParam:

    +
    CryptMsgGetParam(hCryptMsg, dwParamType, dwIndex, pvData, pcbData)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptQueryObject:

    +
    CryptQueryObject(dwObjectType, pvObject, dwExpectedContentTypeFlags, dwExpectedFormatTypeFlags, dwFlags, pdwMsgAndCertEncodingType, pdwContentType, pdwFormatType, phCertStore, phMsg, ppvContext)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • CryptReleaseContext:

    +
    CryptReleaseContext(hProv, dwFlags)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • DeviceIoControl:

  • GetExtendedTcpTable:

  • GetMappedFileNameAWrapper:

  • +
  • GetNamedSecurityInfoW:

    +
    GetNamedSecurityInfoW(pObjectName, ObjectType, SecurityInfo, ppsidOwner=None, ppsidGroup=None, ppDacl=None, ppSacl=None, ppSecurityDescriptor=None)
    +Errcheck:
    +   raise Kernel32Error if result is NOT 0
    +
    +
    +
  • +
  • GetProcessDEPPolicy:

    +
    GetProcessDEPPolicy(hProcess, lpFlags, lpPermanent)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • GetProcessImageFileNameAWrapper:

  • +
  • GetShortPathNameA:

    +
    GetShortPathNameA(lpszLongPath, lpszShortPath, cchBuffer=None)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • GetThreadContext:

  • LdrLoadDll:

  • NtAlpcCreatePort:

  • NtCreateThreadEx:

  • +
  • PFXExportCertStoreEx:

    +
    PFXExportCertStoreEx(hStore, pPFX, szPassword, pvPara, dwFlags)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • PFXImportCertStore:

    +
    PFXImportCertStore(pPFX, szPassword, dwFlags)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • Process32First:

  • ReadProcessMemory:

  • +
  • RegQueryValueExW:

    +
    RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
    +Errcheck:
    +   raise Kernel32Error if result is NOT 0
    +
    +
    +
  • RemoveVectoredExceptionHandler:

  • +
  • SetConsoleCtrlHandler:

    +
    SetConsoleCtrlHandler(HandlerRoutine, Add)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • SetThreadAffinityMask:

  • +
  • ShellExecuteA:

    +
    ShellExecuteA(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • +
  • ShellExecuteW:

    +
    ShellExecuteW(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd)
    +Errcheck:
    +   raise Kernel32Error if result is 0
    +
    +
    +
  • Thread32First:

  • Wow64SetThreadContext:

  • - + \ No newline at end of file diff --git a/docs/build/html/wintrust.html b/docs/build/html/wintrust.html index 6516642..967c2d1 100644 --- a/docs/build/html/wintrust.html +++ b/docs/build/html/wintrust.html @@ -6,7 +6,7 @@ - 6. windows.wintrust – Checking signature — PythonForWindows 0.2 documentation + 6. windows.wintrust – Checking signature — PythonForWindows 0.2 documentation @@ -17,13 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - + + @@ -43,7 +45,7 @@
  • previous |
  • - + @@ -192,7 +194,7 @@ It allows to check the signature of a file.

    This Page

    @@ -225,12 +227,12 @@ It allows to check the signature of a file.

  • previous |
  • - + \ No newline at end of file diff --git a/docs/build/html/wip.html b/docs/build/html/wip.html index ffe3b2d..c768605 100644 --- a/docs/build/html/wip.html +++ b/docs/build/html/wip.html @@ -6,7 +6,7 @@ - 10. Early Work In Progress — PythonForWindows 0.2 documentation + 11. Early Work In Progress — PythonForWindows 0.2 documentation @@ -17,15 +17,17 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - - + + + + @@ -53,7 +55,7 @@
    -

    10. Early Work In Progress

    +

    11. Early Work In Progress

    Here are some features that are still work in progress. Code might be unstable and/or ultra-ugly.

    <Nothing right now>

    @@ -66,14 +68,14 @@

    Previous topic

    9. IAT hooking

    + title="previous chapter">10. IAT hooking

    Next topic

    11. Internals

    + title="next chapter">12. Internals

    This Page

    @@ -101,17 +103,17 @@ modules |
  • - next |
  • - previous |
  • - +
    \ No newline at end of file diff --git a/docs/build/html/wmi.html b/docs/build/html/wmi.html index ff9c88c..920f026 100644 --- a/docs/build/html/wmi.html +++ b/docs/build/html/wmi.html @@ -6,7 +6,7 @@ - 2.9. WMI – Make request to WMI — PythonForWindows 0.2 documentation + 2.9. WMI – Make request to WMI — PythonForWindows 0.2 documentation @@ -17,14 +17,15 @@ VERSION: '0.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', - HAS_SOURCE: true + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt' }; - - + + @@ -44,8 +45,8 @@
  • previous |
  • - - + +
    @@ -97,7 +98,7 @@

    This Page

    @@ -130,13 +131,13 @@
  • previous |
  • - - + + \ No newline at end of file