Search is not available for this dataset
text
stringlengths
75
104k
def _bcrypt_sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature via CNG :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if hash_algorithm == 'raw': digest = data else: hash_constant = { 'md5': BcryptConst.BCRYPT_MD5_ALGORITHM, 'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM, 'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM, 'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM, 'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM }[hash_algorithm] digest = getattr(hashlib, hash_algorithm)(data).digest() padding_info = null() flags = 0 if private_key.algorithm == 'rsa': if rsa_pss_padding: hash_length = { 'md5': 16, 'sha1': 20, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] flags = BcryptConst.BCRYPT_PAD_PSS padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.cbSalt = hash_length else: flags = BcryptConst.BCRYPT_PAD_PKCS1 padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it if hash_algorithm == 'raw': padding_info_struct.pszAlgId = null() else: hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) if private_key.algorithm == 'dsa' and private_key.bit_size > 1024 and hash_algorithm in set(['md5', 'sha1']): raise ValueError(pretty_message( ''' Windows does not support sha1 signatures with DSA keys based on sha224, sha256 or sha512 ''' )) out_len = new(bcrypt, 'DWORD *') res = bcrypt.BCryptSignHash( private_key.key_handle, padding_info, digest, len(digest), null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) if private_key.algorithm == 'rsa': padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) res = bcrypt.BCryptSignHash( private_key.key_handle, padding_info, digest, len(digest), buffer, buffer_len, out_len, flags ) handle_error(res) signature = bytes_from_buffer(buffer, deref(out_len)) if private_key.algorithm != 'rsa': # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures, # so we have to convert it here for the verification to work signature = algos.DSASignature.from_p1363(signature).dump() return signature
def _encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not isinstance(rsa_oaep_padding, bool): raise TypeError(pretty_message( ''' rsa_oaep_padding must be a bool, not %s ''', type_name(rsa_oaep_padding) )) if _backend == 'winlegacy': return _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding) return _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding)
def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ flags = 0 if rsa_oaep_padding: flags = Advapi32Const.CRYPT_OAEP out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptEncrypt( certificate_or_public_key.ex_key_handle, null(), True, flags, null(), out_len, 0 ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) write_to_buffer(buffer, data) pointer_set(out_len, len(data)) res = advapi32.CryptEncrypt( certificate_or_public_key.ex_key_handle, null(), True, flags, buffer, out_len, buffer_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len))[::-1]
def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key via CNG :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ flags = BcryptConst.BCRYPT_PAD_PKCS1 if rsa_oaep_padding is True: flags = BcryptConst.BCRYPT_PAD_OAEP padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(BcryptConst.BCRYPT_SHA1_ALGORITHM) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.pbLabel = null() padding_info_struct.cbLabel = 0 padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) else: padding_info = null() out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptEncrypt( certificate_or_public_key.key_handle, data, len(data), padding_info, null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) res = bcrypt.BCryptEncrypt( certificate_or_public_key.key_handle, data, len(data), padding_info, null(), 0, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len))
def _decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' ciphertext must be a byte string, not %s ''', type_name(ciphertext) )) if not isinstance(rsa_oaep_padding, bool): raise TypeError(pretty_message( ''' rsa_oaep_padding must be a bool, not %s ''', type_name(rsa_oaep_padding) )) if _backend == 'winlegacy': return _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding) return _bcrypt_decrypt(private_key, ciphertext, rsa_oaep_padding)
def _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key via CryptoAPI :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ flags = 0 if rsa_oaep_padding: flags = Advapi32Const.CRYPT_OAEP ciphertext = ciphertext[::-1] buffer = buffer_from_bytes(ciphertext) out_len = new(advapi32, 'DWORD *', len(ciphertext)) res = advapi32.CryptDecrypt( private_key.ex_key_handle, null(), True, flags, buffer, out_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len))
def self_signed(self): """ :return: A boolean - if the certificate is self-signed """ if self._self_signed is None: self._self_signed = False if self.asn1.self_signed in set(['yes', 'maybe']): signature_algo = self.asn1['signature_algorithm'].signature_algo hash_algo = self.asn1['signature_algorithm'].hash_algo if signature_algo == 'rsassa_pkcs1v15': verify_func = rsa_pkcs1v15_verify elif signature_algo == 'dsa': verify_func = dsa_verify elif signature_algo == 'ecdsa': verify_func = ecdsa_verify else: raise OSError(pretty_message( ''' Unable to verify the signature of the certificate since it uses the unsupported algorithm %s ''', signature_algo )) try: verify_func( self, self.asn1['signature_value'].native, self.asn1['tbs_certificate'].dump(), hash_algo ) self._self_signed = True except (SignatureError): pass return self._self_signed
def _obtain_credentials(self): """ Obtains a credentials handle from secur32.dll for use with SChannel """ protocol_values = { 'SSLv3': Secur32Const.SP_PROT_SSL3_CLIENT, 'TLSv1': Secur32Const.SP_PROT_TLS1_CLIENT, 'TLSv1.1': Secur32Const.SP_PROT_TLS1_1_CLIENT, 'TLSv1.2': Secur32Const.SP_PROT_TLS1_2_CLIENT, } protocol_bit_mask = 0 for key, value in protocol_values.items(): if key in self._protocols: protocol_bit_mask |= value algs = [ Secur32Const.CALG_AES_128, Secur32Const.CALG_AES_256, Secur32Const.CALG_3DES, Secur32Const.CALG_SHA1, Secur32Const.CALG_ECDHE, Secur32Const.CALG_DH_EPHEM, Secur32Const.CALG_RSA_KEYX, Secur32Const.CALG_RSA_SIGN, Secur32Const.CALG_ECDSA, Secur32Const.CALG_DSS_SIGN, ] if 'TLSv1.2' in self._protocols: algs.extend([ Secur32Const.CALG_SHA512, Secur32Const.CALG_SHA384, Secur32Const.CALG_SHA256, ]) alg_array = new(secur32, 'ALG_ID[%s]' % len(algs)) for index, alg in enumerate(algs): alg_array[index] = alg flags = Secur32Const.SCH_USE_STRONG_CRYPTO | Secur32Const.SCH_CRED_NO_DEFAULT_CREDS if not self._manual_validation and not self._extra_trust_roots: flags |= Secur32Const.SCH_CRED_AUTO_CRED_VALIDATION else: flags |= Secur32Const.SCH_CRED_MANUAL_CRED_VALIDATION schannel_cred_pointer = struct(secur32, 'SCHANNEL_CRED') schannel_cred = unwrap(schannel_cred_pointer) schannel_cred.dwVersion = Secur32Const.SCHANNEL_CRED_VERSION schannel_cred.cCreds = 0 schannel_cred.paCred = null() schannel_cred.hRootStore = null() schannel_cred.cMappers = 0 schannel_cred.aphMappers = null() schannel_cred.cSupportedAlgs = len(alg_array) schannel_cred.palgSupportedAlgs = alg_array schannel_cred.grbitEnabledProtocols = protocol_bit_mask schannel_cred.dwMinimumCipherStrength = 0 schannel_cred.dwMaximumCipherStrength = 0 # Default session lifetime is 10 hours schannel_cred.dwSessionLifespan = 0 schannel_cred.dwFlags = flags schannel_cred.dwCredFormat = 0 cred_handle_pointer = new(secur32, 'CredHandle *') result = secur32.AcquireCredentialsHandleW( null(), Secur32Const.UNISP_NAME, Secur32Const.SECPKG_CRED_OUTBOUND, null(), schannel_cred_pointer, null(), null(), cred_handle_pointer, null() ) handle_error(result) self._credentials_handle = cred_handle_pointer
def wrap(cls, socket, hostname, session=None): """ Takes an existing socket and adds TLS :param socket: A socket.socket object to wrap with TLS :param hostname: A unicode string of the hostname or IP the socket is connected to :param session: An existing TLSSession object to allow for session reuse, specific protocol or manual certificate validation :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(socket, socket_.socket): raise TypeError(pretty_message( ''' socket must be an instance of socket.socket, not %s ''', type_name(socket) )) if not isinstance(hostname, str_cls): raise TypeError(pretty_message( ''' hostname must be a unicode string, not %s ''', type_name(hostname) )) if session is not None and not isinstance(session, TLSSession): raise TypeError(pretty_message( ''' session must be an instance of oscrypto.tls.TLSSession, not %s ''', type_name(session) )) new_socket = cls(None, None, session=session) new_socket._socket = socket new_socket._hostname = hostname # Since we don't create the socket connection here, we can't try to # reconnect with a lower version of the TLS protocol, so we just # move the data to public exception type TLSVerificationError() try: new_socket._handshake() except (_TLSDowngradeError) as e: new_e = TLSVerificationError(e.message, e.certificate) raise new_e except (_TLSRetryError) as e: new_e = TLSError(e.message) raise new_e return new_socket
def _create_buffers(self, number): """ Creates a SecBufferDesc struct and contained SecBuffer structs :param number: The number of contains SecBuffer objects to create :return: A tuple of (SecBufferDesc pointer, SecBuffer array) """ buffers = new(secur32, 'SecBuffer[%d]' % number) for index in range(0, number): buffers[index].cbBuffer = 0 buffers[index].BufferType = Secur32Const.SECBUFFER_EMPTY buffers[index].pvBuffer = null() sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc') sec_buffer_desc = unwrap(sec_buffer_desc_pointer) sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION sec_buffer_desc.cBuffers = number sec_buffer_desc.pBuffers = buffers return (sec_buffer_desc_pointer, buffers)
def _extra_trust_root_validation(self): """ Manually invoked windows certificate chain builder and verification step when there are extra trust roots to include in the search process """ store = None cert_chain_context_pointer = None try: # We set up an in-memory store to pass as an extra store to grab # certificates from when performing the verification store = crypt32.CertOpenStore( Crypt32Const.CERT_STORE_PROV_MEMORY, Crypt32Const.X509_ASN_ENCODING, null(), 0, null() ) if is_null(store): handle_crypt32_error(0) cert_hashes = set() for cert in self._session._extra_trust_roots: cert_data = cert.dump() result = crypt32.CertAddEncodedCertificateToStore( store, Crypt32Const.X509_ASN_ENCODING, cert_data, len(cert_data), Crypt32Const.CERT_STORE_ADD_USE_EXISTING, null() ) if not result: handle_crypt32_error(0) cert_hashes.add(cert.sha256) cert_context_pointer_pointer = new(crypt32, 'PCERT_CONTEXT *') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_REMOTE_CERT_CONTEXT, cert_context_pointer_pointer ) handle_error(result) cert_context_pointer = unwrap(cert_context_pointer_pointer) cert_context_pointer = cast(crypt32, 'PCERT_CONTEXT', cert_context_pointer) # We have to do a funky shuffle here because FILETIME from kernel32 # is different than FILETIME from crypt32 when using cffi. If we # overwrite the "now_pointer" variable, cffi releases the backing # memory and we end up getting a validation error about certificate # expiration time. orig_now_pointer = new(kernel32, 'FILETIME *') kernel32.GetSystemTimeAsFileTime(orig_now_pointer) now_pointer = cast(crypt32, 'FILETIME *', orig_now_pointer) usage_identifiers = new(crypt32, 'char *[3]') usage_identifiers[0] = cast(crypt32, 'char *', Crypt32Const.PKIX_KP_SERVER_AUTH) usage_identifiers[1] = cast(crypt32, 'char *', Crypt32Const.SERVER_GATED_CRYPTO) usage_identifiers[2] = cast(crypt32, 'char *', Crypt32Const.SGC_NETSCAPE) cert_enhkey_usage_pointer = struct(crypt32, 'CERT_ENHKEY_USAGE') cert_enhkey_usage = unwrap(cert_enhkey_usage_pointer) cert_enhkey_usage.cUsageIdentifier = 3 cert_enhkey_usage.rgpszUsageIdentifier = cast(crypt32, 'char **', usage_identifiers) cert_usage_match_pointer = struct(crypt32, 'CERT_USAGE_MATCH') cert_usage_match = unwrap(cert_usage_match_pointer) cert_usage_match.dwType = Crypt32Const.USAGE_MATCH_TYPE_OR cert_usage_match.Usage = cert_enhkey_usage cert_chain_para_pointer = struct(crypt32, 'CERT_CHAIN_PARA') cert_chain_para = unwrap(cert_chain_para_pointer) cert_chain_para.RequestedUsage = cert_usage_match cert_chain_para_size = sizeof(crypt32, cert_chain_para) cert_chain_para.cbSize = cert_chain_para_size cert_chain_context_pointer_pointer = new(crypt32, 'PCERT_CHAIN_CONTEXT *') result = crypt32.CertGetCertificateChain( null(), cert_context_pointer, now_pointer, store, cert_chain_para_pointer, Crypt32Const.CERT_CHAIN_CACHE_END_CERT | Crypt32Const.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY, null(), cert_chain_context_pointer_pointer ) handle_crypt32_error(result) cert_chain_policy_para_flags = Crypt32Const.CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS cert_chain_context_pointer = unwrap(cert_chain_context_pointer_pointer) # Unwrap the chain and if the final element in the chain is one of # extra trust roots, set flags so that we trust the certificate even # though it is not in the Trusted Roots store cert_chain_context = unwrap(cert_chain_context_pointer) num_chains = native(int, cert_chain_context.cChain) if num_chains == 1: first_simple_chain_pointer = unwrap(cert_chain_context.rgpChain) first_simple_chain = unwrap(first_simple_chain_pointer) num_elements = native(int, first_simple_chain.cElement) last_element_pointer = first_simple_chain.rgpElement[num_elements - 1] last_element = unwrap(last_element_pointer) last_element_cert = unwrap(last_element.pCertContext) last_element_cert_data = bytes_from_buffer( last_element_cert.pbCertEncoded, native(int, last_element_cert.cbCertEncoded) ) last_cert = x509.Certificate.load(last_element_cert_data) if last_cert.sha256 in cert_hashes: cert_chain_policy_para_flags |= Crypt32Const.CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG ssl_extra_cert_chain_policy_para_pointer = struct(crypt32, 'SSL_EXTRA_CERT_CHAIN_POLICY_PARA') ssl_extra_cert_chain_policy_para = unwrap(ssl_extra_cert_chain_policy_para_pointer) ssl_extra_cert_chain_policy_para.cbSize = sizeof(crypt32, ssl_extra_cert_chain_policy_para) ssl_extra_cert_chain_policy_para.dwAuthType = Crypt32Const.AUTHTYPE_SERVER ssl_extra_cert_chain_policy_para.fdwChecks = 0 ssl_extra_cert_chain_policy_para.pwszServerName = cast( crypt32, 'wchar_t *', buffer_from_unicode(self._hostname) ) cert_chain_policy_para_pointer = struct(crypt32, 'CERT_CHAIN_POLICY_PARA') cert_chain_policy_para = unwrap(cert_chain_policy_para_pointer) cert_chain_policy_para.cbSize = sizeof(crypt32, cert_chain_policy_para) cert_chain_policy_para.dwFlags = cert_chain_policy_para_flags cert_chain_policy_para.pvExtraPolicyPara = cast(crypt32, 'void *', ssl_extra_cert_chain_policy_para_pointer) cert_chain_policy_status_pointer = struct(crypt32, 'CERT_CHAIN_POLICY_STATUS') cert_chain_policy_status = unwrap(cert_chain_policy_status_pointer) cert_chain_policy_status.cbSize = sizeof(crypt32, cert_chain_policy_status) result = crypt32.CertVerifyCertificateChainPolicy( Crypt32Const.CERT_CHAIN_POLICY_SSL, cert_chain_context_pointer, cert_chain_policy_para_pointer, cert_chain_policy_status_pointer ) handle_crypt32_error(result) cert_context = unwrap(cert_context_pointer) cert_data = bytes_from_buffer(cert_context.pbCertEncoded, native(int, cert_context.cbCertEncoded)) cert = x509.Certificate.load(cert_data) error = cert_chain_policy_status.dwError if error: if error == Crypt32Const.CERT_E_EXPIRED: raise_expired_not_yet_valid(cert) if error == Crypt32Const.CERT_E_UNTRUSTEDROOT: oscrypto_cert = load_certificate(cert) if oscrypto_cert.self_signed: raise_self_signed(cert) else: raise_no_issuer(cert) if error == Crypt32Const.CERT_E_CN_NO_MATCH: raise_hostname(cert, self._hostname) if error == Crypt32Const.TRUST_E_CERT_SIGNATURE: raise_weak_signature(cert) if error == Crypt32Const.CRYPT_E_REVOKED: raise_revoked(cert) raise_verification(cert) if cert.hash_algo in set(['md5', 'md2']): raise_weak_signature(cert) finally: if store: crypt32.CertCloseStore(store, 0) if cert_chain_context_pointer: crypt32.CertFreeCertificateChain(cert_chain_context_pointer)
def _handshake(self, renegotiate=False): """ Perform an initial TLS handshake, or a renegotiation :param renegotiate: If the handshake is for a renegotiation """ in_buffers = None out_buffers = None new_context_handle_pointer = None try: if renegotiate: temp_context_handle_pointer = self._context_handle_pointer else: new_context_handle_pointer = new(secur32, 'CtxtHandle *') temp_context_handle_pointer = new_context_handle_pointer requested_flags = { Secur32Const.ISC_REQ_REPLAY_DETECT: 'replay detection', Secur32Const.ISC_REQ_SEQUENCE_DETECT: 'sequence detection', Secur32Const.ISC_REQ_CONFIDENTIALITY: 'confidentiality', Secur32Const.ISC_REQ_ALLOCATE_MEMORY: 'memory allocation', Secur32Const.ISC_REQ_INTEGRITY: 'integrity', Secur32Const.ISC_REQ_STREAM: 'stream orientation', Secur32Const.ISC_REQ_USE_SUPPLIED_CREDS: 'disable automatic client auth', } self._context_flags = 0 for flag in requested_flags: self._context_flags |= flag in_sec_buffer_desc_pointer, in_buffers = self._create_buffers(2) in_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_sec_buffer_desc_pointer, out_buffers = self._create_buffers(2) out_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_buffers[1].BufferType = Secur32Const.SECBUFFER_ALERT output_context_flags_pointer = new(secur32, 'ULONG *') if renegotiate: first_handle = temp_context_handle_pointer second_handle = null() else: first_handle = null() second_handle = temp_context_handle_pointer result = secur32.InitializeSecurityContextW( self._session._credentials_handle, first_handle, self._hostname, self._context_flags, 0, 0, null(), 0, second_handle, out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) if result not in set([Secur32Const.SEC_E_OK, Secur32Const.SEC_I_CONTINUE_NEEDED]): handle_error(result, TLSError) if not renegotiate: temp_context_handle_pointer = second_handle else: temp_context_handle_pointer = first_handle handshake_server_bytes = b'' handshake_client_bytes = b'' if out_buffers[0].cbBuffer > 0: token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) handshake_client_bytes += token self._socket.send(token) out_buffers[0].cbBuffer = 0 secur32.FreeContextBuffer(out_buffers[0].pvBuffer) out_buffers[0].pvBuffer = null() in_data_buffer = buffer_from_bytes(32768) in_buffers[0].pvBuffer = cast(secur32, 'BYTE *', in_data_buffer) bytes_read = b'' while result != Secur32Const.SEC_E_OK: try: fail_late = False bytes_read = self._socket.recv(8192) if bytes_read == b'': raise_disconnection() except (socket_error_cls): fail_late = True handshake_server_bytes += bytes_read self._received_bytes += bytes_read in_buffers[0].cbBuffer = len(self._received_bytes) write_to_buffer(in_data_buffer, self._received_bytes) result = secur32.InitializeSecurityContextW( self._session._credentials_handle, temp_context_handle_pointer, self._hostname, self._context_flags, 0, 0, in_sec_buffer_desc_pointer, 0, null(), out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) if result == Secur32Const.SEC_E_INCOMPLETE_MESSAGE: in_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN # Windows 10 seems to fill the second input buffer with # a BufferType of SECBUFFER_MISSING (4), which if not # cleared causes the handshake to fail. if in_buffers[1].BufferType != Secur32Const.SECBUFFER_EMPTY: in_buffers[1].BufferType = Secur32Const.SECBUFFER_EMPTY in_buffers[1].cbBuffer = 0 if not is_null(in_buffers[1].pvBuffer): secur32.FreeContextBuffer(in_buffers[1].pvBuffer) in_buffers[1].pvBuffer = null() if fail_late: raise_disconnection() continue if result == Secur32Const.SEC_E_ILLEGAL_MESSAGE: if detect_client_auth_request(handshake_server_bytes): raise_client_auth() alert_info = parse_alert(handshake_server_bytes) if alert_info and alert_info == (2, 70): raise_protocol_version() raise_handshake() if result == Secur32Const.SEC_E_WRONG_PRINCIPAL: chain = extract_chain(handshake_server_bytes) raise_hostname(chain[0], self._hostname) if result == Secur32Const.SEC_E_CERT_EXPIRED: chain = extract_chain(handshake_server_bytes) raise_expired_not_yet_valid(chain[0]) if result == Secur32Const.SEC_E_UNTRUSTED_ROOT: chain = extract_chain(handshake_server_bytes) cert = chain[0] oscrypto_cert = load_certificate(cert) if not oscrypto_cert.self_signed: raise_no_issuer(cert) raise_self_signed(cert) if result == Secur32Const.SEC_E_INTERNAL_ERROR: if get_dh_params_length(handshake_server_bytes) < 1024: raise_dh_params() if result == Secur32Const.SEC_I_INCOMPLETE_CREDENTIALS: raise_client_auth() if result == Crypt32Const.TRUST_E_CERT_SIGNATURE: raise_weak_signature(cert) if result == Secur32Const.SEC_E_INVALID_TOKEN: # If an alert it present, there may have been a handshake # error due to the server using a certificate path with a # trust root using MD2 or MD5 combined with TLS 1.2. To # work around this, if the user allows anything other than # TLS 1.2, we just remove it from the acceptable protocols # and try again. if out_buffers[1].cbBuffer > 0: alert_bytes = bytes_from_buffer(out_buffers[1].pvBuffer, out_buffers[1].cbBuffer) handshake_client_bytes += alert_bytes alert_number = alert_bytes[6:7] if alert_number == b'\x28' or alert_number == b'\x2b': if 'TLSv1.2' in self._session._protocols and len(self._session._protocols) > 1: chain = extract_chain(handshake_server_bytes) raise _TLSDowngradeError( 'Server certificate verification failed - weak certificate signature algorithm', chain[0] ) if detect_client_auth_request(handshake_server_bytes): raise_client_auth() if detect_other_protocol(handshake_server_bytes): raise_protocol_error(handshake_server_bytes) raise_handshake() # These are semi-common errors with TLSv1.2 on Windows 7 an 8 # that appears to be due to poor handling of the # ServerKeyExchange for DHE_RSA cipher suites. The solution # is to retry the handshake. if result == Secur32Const.SEC_E_BUFFER_TOO_SMALL or result == Secur32Const.SEC_E_MESSAGE_ALTERED: if 'TLSv1.2' in self._session._protocols: raise _TLSRetryError('TLS handshake failed') if fail_late: raise_disconnection() if result == Secur32Const.SEC_E_INVALID_PARAMETER: if get_dh_params_length(handshake_server_bytes) < 1024: raise_dh_params() if result not in set([Secur32Const.SEC_E_OK, Secur32Const.SEC_I_CONTINUE_NEEDED]): handle_error(result, TLSError) if out_buffers[0].cbBuffer > 0: token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) handshake_client_bytes += token self._socket.send(token) out_buffers[0].cbBuffer = 0 secur32.FreeContextBuffer(out_buffers[0].pvBuffer) out_buffers[0].pvBuffer = null() if in_buffers[1].BufferType == Secur32Const.SECBUFFER_EXTRA: extra_amount = in_buffers[1].cbBuffer self._received_bytes = self._received_bytes[-extra_amount:] in_buffers[1].BufferType = Secur32Const.SECBUFFER_EMPTY in_buffers[1].cbBuffer = 0 secur32.FreeContextBuffer(in_buffers[1].pvBuffer) in_buffers[1].pvBuffer = null() # The handshake is complete, so discard any extra bytes if result == Secur32Const.SEC_E_OK: handshake_server_bytes = handshake_server_bytes[-extra_amount:] else: self._received_bytes = b'' connection_info_pointer = struct(secur32, 'SecPkgContext_ConnectionInfo') result = secur32.QueryContextAttributesW( temp_context_handle_pointer, Secur32Const.SECPKG_ATTR_CONNECTION_INFO, connection_info_pointer ) handle_error(result, TLSError) connection_info = unwrap(connection_info_pointer) self._protocol = { Secur32Const.SP_PROT_SSL2_CLIENT: 'SSLv2', Secur32Const.SP_PROT_SSL3_CLIENT: 'SSLv3', Secur32Const.SP_PROT_TLS1_CLIENT: 'TLSv1', Secur32Const.SP_PROT_TLS1_1_CLIENT: 'TLSv1.1', Secur32Const.SP_PROT_TLS1_2_CLIENT: 'TLSv1.2', }.get(native(int, connection_info.dwProtocol), str_cls(connection_info.dwProtocol)) if self._protocol in set(['SSLv3', 'TLSv1', 'TLSv1.1', 'TLSv1.2']): session_info = parse_session_info(handshake_server_bytes, handshake_client_bytes) self._cipher_suite = session_info['cipher_suite'] self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] output_context_flags = deref(output_context_flags_pointer) for flag in requested_flags: if (flag | output_context_flags) == 0: raise OSError(pretty_message( ''' Unable to obtain a credential context with the property %s ''', requested_flags[flag] )) if not renegotiate: self._context_handle_pointer = temp_context_handle_pointer new_context_handle_pointer = None stream_sizes_pointer = struct(secur32, 'SecPkgContext_StreamSizes') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_STREAM_SIZES, stream_sizes_pointer ) handle_error(result) stream_sizes = unwrap(stream_sizes_pointer) self._header_size = native(int, stream_sizes.cbHeader) self._message_size = native(int, stream_sizes.cbMaximumMessage) self._trailer_size = native(int, stream_sizes.cbTrailer) self._buffer_size = self._header_size + self._message_size + self._trailer_size if self._session._extra_trust_roots: self._extra_trust_root_validation() except (OSError, socket_.error): self.close() raise finally: if out_buffers: if not is_null(out_buffers[0].pvBuffer): secur32.FreeContextBuffer(out_buffers[0].pvBuffer) if not is_null(out_buffers[1].pvBuffer): secur32.FreeContextBuffer(out_buffers[1].pvBuffer) if new_context_handle_pointer: secur32.DeleteSecurityContext(new_context_handle_pointer)
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) if self._context_handle_pointer is None: # Allow the user to read any remaining decrypted data if self._decrypted_bytes != b'': output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output self._raise_closed() # The first time read is called, set up a single contiguous buffer that # it used by DecryptMessage() to populate the three output buffers. # Since we are creating the buffer, we do not need to free it other # than allowing Python to GC it once this object is GCed. if not self._decrypt_data_buffer: self._decrypt_data_buffer = buffer_from_bytes(self._buffer_size) self._decrypt_desc, self._decrypt_buffers = self._create_buffers(4) self._decrypt_buffers[0].BufferType = Secur32Const.SECBUFFER_DATA self._decrypt_buffers[0].pvBuffer = cast(secur32, 'BYTE *', self._decrypt_data_buffer) to_recv = max(max_length, self._buffer_size) # These variables are set to reduce dict access and function calls # in the read loop. Also makes the code easier to read. null_value = null() buf0 = self._decrypt_buffers[0] buf1 = self._decrypt_buffers[1] buf2 = self._decrypt_buffers[2] buf3 = self._decrypt_buffers[3] def _reset_buffers(): buf0.BufferType = Secur32Const.SECBUFFER_DATA buf0.pvBuffer = cast(secur32, 'BYTE *', self._decrypt_data_buffer) buf0.cbBuffer = 0 buf1.BufferType = Secur32Const.SECBUFFER_EMPTY buf1.pvBuffer = null_value buf1.cbBuffer = 0 buf2.BufferType = Secur32Const.SECBUFFER_EMPTY buf2.pvBuffer = null_value buf2.cbBuffer = 0 buf3.BufferType = Secur32Const.SECBUFFER_EMPTY buf3.pvBuffer = null_value buf3.cbBuffer = 0 output = self._decrypted_bytes output_len = len(output) self._decrypted_bytes = b'' # Don't block if we have buffered data available if output_len > 0 and not self.select_read(0): self._decrypted_bytes = b'' return output # This read loop will only be run if there wasn't enough # buffered data to fulfill the requested max_length do_read = len(self._received_bytes) == 0 while output_len < max_length: if do_read: self._received_bytes += self._socket.recv(to_recv) if len(self._received_bytes) == 0: raise_disconnection() data_len = min(len(self._received_bytes), self._buffer_size) if data_len == 0: break self._decrypt_buffers[0].cbBuffer = data_len write_to_buffer(self._decrypt_data_buffer, self._received_bytes[0:data_len]) result = secur32.DecryptMessage( self._context_handle_pointer, self._decrypt_desc, 0, null() ) do_read = False if result == Secur32Const.SEC_E_INCOMPLETE_MESSAGE: _reset_buffers() do_read = True continue elif result == Secur32Const.SEC_I_CONTEXT_EXPIRED: self._remote_closed = True self.shutdown() break elif result == Secur32Const.SEC_I_RENEGOTIATE: self._handshake(renegotiate=True) return self.read(max_length) elif result != Secur32Const.SEC_E_OK: handle_error(result, TLSError) valid_buffer_types = set([ Secur32Const.SECBUFFER_EMPTY, Secur32Const.SECBUFFER_STREAM_HEADER, Secur32Const.SECBUFFER_STREAM_TRAILER ]) extra_amount = None for buf in (buf0, buf1, buf2, buf3): buffer_type = buf.BufferType if buffer_type == Secur32Const.SECBUFFER_DATA: output += bytes_from_buffer(buf.pvBuffer, buf.cbBuffer) output_len = len(output) elif buffer_type == Secur32Const.SECBUFFER_EXTRA: extra_amount = native(int, buf.cbBuffer) elif buffer_type not in valid_buffer_types: raise OSError(pretty_message( ''' Unexpected decrypt output buffer of type %s ''', buffer_type )) if extra_amount: self._received_bytes = self._received_bytes[data_len - extra_amount:] else: self._received_bytes = self._received_bytes[data_len:] # Here we reset the structs for the next call to DecryptMessage() _reset_buffers() # If we have read something, but there is nothing left to read, we # break so that we don't block for longer than necessary if self.select_read(0): do_read = True if not do_read and len(self._received_bytes) == 0: break # If the output is more than we requested (because data is decrypted in # blocks), we save the extra in a buffer if len(output) > max_length: self._decrypted_bytes = output[max_length:] output = output[0:max_length] return output
def select_read(self, timeout=None): """ Blocks until the socket is ready to be read from, or the timeout is hit :param timeout: A float - the period of time to wait for data to be read. None for no time limit. :return: A boolean - if data is ready to be read. Will only be False if timeout is not None. """ # If we have buffered data, we consider a read possible if len(self._decrypted_bytes) > 0: return True read_ready, _, _ = select.select([self._socket], [], [], timeout) return len(read_ready) > 0
def read_exactly(self, num_bytes): """ Reads exactly the specified number of bytes from the socket :param num_bytes: An integer - the exact number of bytes to read :return: A byte string of the data that was read """ output = b'' remaining = num_bytes while remaining > 0: output += self.read(remaining) remaining = num_bytes - len(output) return output
def write(self, data): """ Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if self._context_handle_pointer is None: self._raise_closed() if not self._encrypt_data_buffer: self._encrypt_data_buffer = buffer_from_bytes(self._header_size + self._message_size + self._trailer_size) self._encrypt_desc, self._encrypt_buffers = self._create_buffers(4) self._encrypt_buffers[0].BufferType = Secur32Const.SECBUFFER_STREAM_HEADER self._encrypt_buffers[0].cbBuffer = self._header_size self._encrypt_buffers[0].pvBuffer = cast(secur32, 'BYTE *', self._encrypt_data_buffer) self._encrypt_buffers[1].BufferType = Secur32Const.SECBUFFER_DATA self._encrypt_buffers[1].pvBuffer = ref(self._encrypt_data_buffer, self._header_size) self._encrypt_buffers[2].BufferType = Secur32Const.SECBUFFER_STREAM_TRAILER self._encrypt_buffers[2].cbBuffer = self._trailer_size self._encrypt_buffers[2].pvBuffer = ref(self._encrypt_data_buffer, self._header_size + self._message_size) while len(data) > 0: to_write = min(len(data), self._message_size) write_to_buffer(self._encrypt_data_buffer, data[0:to_write], self._header_size) self._encrypt_buffers[1].cbBuffer = to_write self._encrypt_buffers[2].pvBuffer = ref(self._encrypt_data_buffer, self._header_size + to_write) result = secur32.EncryptMessage( self._context_handle_pointer, 0, self._encrypt_desc, 0 ) if result != Secur32Const.SEC_E_OK: handle_error(result, TLSError) to_send = native(int, self._encrypt_buffers[0].cbBuffer) to_send += native(int, self._encrypt_buffers[1].cbBuffer) to_send += native(int, self._encrypt_buffers[2].cbBuffer) try: self._socket.send(bytes_from_buffer(self._encrypt_data_buffer, to_send)) except (socket_.error) as e: if e.errno == 10053: raise_disconnection() raise data = data[to_send:]
def select_write(self, timeout=None): """ Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be False if timeout is not None. """ _, write_ready, _ = select.select([], [self._socket], [], timeout) return len(write_ready) > 0
def shutdown(self): """ Shuts down the TLS session and then shuts down the underlying socket :raises: OSError - when an error is returned by the OS crypto library """ if self._context_handle_pointer is None: return out_buffers = None try: # ApplyControlToken fails with SEC_E_UNSUPPORTED_FUNCTION # when called on Windows 7 if _win_version_info >= (6, 2): buffers = new(secur32, 'SecBuffer[1]') # This is a SCHANNEL_SHUTDOWN token (DWORD of 1) buffers[0].cbBuffer = 4 buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN buffers[0].pvBuffer = cast(secur32, 'BYTE *', buffer_from_bytes(b'\x01\x00\x00\x00')) sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc') sec_buffer_desc = unwrap(sec_buffer_desc_pointer) sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION sec_buffer_desc.cBuffers = 1 sec_buffer_desc.pBuffers = buffers result = secur32.ApplyControlToken(self._context_handle_pointer, sec_buffer_desc_pointer) handle_error(result, TLSError) out_sec_buffer_desc_pointer, out_buffers = self._create_buffers(2) out_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_buffers[1].BufferType = Secur32Const.SECBUFFER_ALERT output_context_flags_pointer = new(secur32, 'ULONG *') result = secur32.InitializeSecurityContextW( self._session._credentials_handle, self._context_handle_pointer, self._hostname, self._context_flags, 0, 0, null(), 0, null(), out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) acceptable_results = set([ Secur32Const.SEC_E_OK, Secur32Const.SEC_E_CONTEXT_EXPIRED, Secur32Const.SEC_I_CONTINUE_NEEDED ]) if result not in acceptable_results: handle_error(result, TLSError) token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) try: # If there is an error sending the shutdown, ignore it since the # connection is likely gone at this point self._socket.send(token) except (socket_.error): pass finally: if out_buffers: if not is_null(out_buffers[0].pvBuffer): secur32.FreeContextBuffer(out_buffers[0].pvBuffer) if not is_null(out_buffers[1].pvBuffer): secur32.FreeContextBuffer(out_buffers[1].pvBuffer) secur32.DeleteSecurityContext(self._context_handle_pointer) self._context_handle_pointer = None try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass
def close(self): """ Shuts down the TLS session and socket and forcibly closes it """ try: self.shutdown() finally: if self._socket: try: self._socket.close() except (socket_.error): pass self._socket = None
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ cert_context_pointer_pointer = new(crypt32, 'CERT_CONTEXT **') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_REMOTE_CERT_CONTEXT, cert_context_pointer_pointer ) handle_error(result, TLSError) cert_context_pointer = unwrap(cert_context_pointer_pointer) cert_context_pointer = cast(crypt32, 'CERT_CONTEXT *', cert_context_pointer) cert_context = unwrap(cert_context_pointer) cert_data = bytes_from_buffer(cert_context.pbCertEncoded, native(int, cert_context.cbCertEncoded)) self._certificate = x509.Certificate.load(cert_data) self._intermediates = [] store_handle = None try: store_handle = cert_context.hCertStore context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, null()) while not is_null(context_pointer): context = unwrap(context_pointer) data = bytes_from_buffer(context.pbCertEncoded, native(int, context.cbCertEncoded)) # The cert store seems to include the end-entity certificate as # the last entry, but we already have that from the struct. if data != cert_data: self._intermediates.append(x509.Certificate.load(data)) context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, context_pointer) finally: if store_handle: crypt32.CertCloseStore(store_handle, 0)
def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._context_handle_pointer is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._certificate
def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._context_handle_pointer is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates
def handle_cf_error(error_pointer): """ Checks a CFErrorRef and throws an exception if there is an error to report :param error_pointer: A CFErrorRef :raises: OSError - when the CFErrorRef contains an error """ if is_null(error_pointer): return error = unwrap(error_pointer) if is_null(error): return cf_string_domain = CoreFoundation.CFErrorGetDomain(error) domain = CFHelpers.cf_string_to_unicode(cf_string_domain) CoreFoundation.CFRelease(cf_string_domain) num = CoreFoundation.CFErrorGetCode(error) cf_string_ref = CoreFoundation.CFErrorCopyDescription(error) output = CFHelpers.cf_string_to_unicode(cf_string_ref) CoreFoundation.CFRelease(cf_string_ref) if output is None: if domain == 'NSOSStatusErrorDomain': code_map = { -2147416010: 'ACL add failed', -2147416025: 'ACL base certs not supported', -2147416019: 'ACL challenge callback failed', -2147416015: 'ACL change failed', -2147416012: 'ACL delete failed', -2147416017: 'ACL entry tag not found', -2147416011: 'ACL replace failed', -2147416021: 'ACL subject type not supported', -2147415789: 'Algid mismatch', -2147415726: 'Already logged in', -2147415040: 'Apple add application ACL subject', -2147415036: 'Apple invalid key end date', -2147415037: 'Apple invalid key start date', -2147415039: 'Apple public key incomplete', -2147415038: 'Apple signature mismatch', -2147415034: 'Apple SSLv2 rollback', -2147415802: 'Attach handle busy', -2147415731: 'Block size mismatch', -2147415722: 'Crypto data callback failed', -2147415804: 'Device error', -2147415835: 'Device failed', -2147415803: 'Device memory error', -2147415836: 'Device reset', -2147415728: 'Device verify failed', -2147416054: 'Function failed', -2147416057: 'Function not implemented', -2147415807: 'Input length error', -2147415837: 'Insufficient client identification', -2147416063: 'Internal error', -2147416027: 'Invalid access credentials', -2147416026: 'Invalid ACL base certs', -2147416020: 'Invalid ACL challenge callback', -2147416016: 'Invalid ACL edit mode', -2147416018: 'Invalid ACL entry tag', -2147416022: 'Invalid ACL subject value', -2147415759: 'Invalid algorithm', -2147415678: 'Invalid attr access credentials', -2147415704: 'Invalid attr alg params', -2147415686: 'Invalid attr base', -2147415738: 'Invalid attr block size', -2147415680: 'Invalid attr dl db handle', -2147415696: 'Invalid attr effective bits', -2147415692: 'Invalid attr end date', -2147415752: 'Invalid attr init vector', -2147415682: 'Invalid attr iteration count', -2147415754: 'Invalid attr key', -2147415740: 'Invalid attr key length', -2147415700: 'Invalid attr key type', -2147415702: 'Invalid attr label', -2147415698: 'Invalid attr mode', -2147415708: 'Invalid attr output size', -2147415748: 'Invalid attr padding', -2147415742: 'Invalid attr passphrase', -2147415688: 'Invalid attr prime', -2147415674: 'Invalid attr private key format', -2147415676: 'Invalid attr public key format', -2147415746: 'Invalid attr random', -2147415706: 'Invalid attr rounds', -2147415750: 'Invalid attr salt', -2147415744: 'Invalid attr seed', -2147415694: 'Invalid attr start date', -2147415684: 'Invalid attr subprime', -2147415672: 'Invalid attr symmetric key format', -2147415690: 'Invalid attr version', -2147415670: 'Invalid attr wrapped key format', -2147415760: 'Invalid context', -2147416000: 'Invalid context handle', -2147415976: 'Invalid crypto data', -2147415994: 'Invalid data', -2147415768: 'Invalid data count', -2147415723: 'Invalid digest algorithm', -2147416059: 'Invalid input pointer', -2147415766: 'Invalid input vector', -2147415792: 'Invalid key', -2147415780: 'Invalid keyattr mask', -2147415782: 'Invalid keyusage mask', -2147415790: 'Invalid key class', -2147415776: 'Invalid key format', -2147415778: 'Invalid key label', -2147415783: 'Invalid key pointer', -2147415791: 'Invalid key reference', -2147415727: 'Invalid login name', -2147416014: 'Invalid new ACL entry', -2147416013: 'Invalid new ACL owner', -2147416058: 'Invalid output pointer', -2147415765: 'Invalid output vector', -2147415978: 'Invalid passthrough id', -2147416060: 'Invalid pointer', -2147416024: 'Invalid sample value', -2147415733: 'Invalid signature', -2147415787: 'Key blob type incorrect', -2147415786: 'Key header inconsistent', -2147415724: 'Key label already exists', -2147415788: 'Key usage incorrect', -2147416061: 'Mds error', -2147416062: 'Memory error', -2147415677: 'Missing attr access credentials', -2147415703: 'Missing attr alg params', -2147415685: 'Missing attr base', -2147415737: 'Missing attr block size', -2147415679: 'Missing attr dl db handle', -2147415695: 'Missing attr effective bits', -2147415691: 'Missing attr end date', -2147415751: 'Missing attr init vector', -2147415681: 'Missing attr iteration count', -2147415753: 'Missing attr key', -2147415739: 'Missing attr key length', -2147415699: 'Missing attr key type', -2147415701: 'Missing attr label', -2147415697: 'Missing attr mode', -2147415707: 'Missing attr output size', -2147415747: 'Missing attr padding', -2147415741: 'Missing attr passphrase', -2147415687: 'Missing attr prime', -2147415673: 'Missing attr private key format', -2147415675: 'Missing attr public key format', -2147415745: 'Missing attr random', -2147415705: 'Missing attr rounds', -2147415749: 'Missing attr salt', -2147415743: 'Missing attr seed', -2147415693: 'Missing attr start date', -2147415683: 'Missing attr subprime', -2147415671: 'Missing attr symmetric key format', -2147415689: 'Missing attr version', -2147415669: 'Missing attr wrapped key format', -2147415801: 'Not logged in', -2147415840: 'No user interaction', -2147416029: 'Object ACL not supported', -2147416028: 'Object ACL required', -2147416030: 'Object manip auth denied', -2147416031: 'Object use auth denied', -2147416032: 'Operation auth denied', -2147416055: 'OS access denied', -2147415806: 'Output length error', -2147415725: 'Private key already exists', -2147415730: 'Private key not found', -2147415989: 'Privilege not granted', -2147415805: 'Privilege not supported', -2147415729: 'Public key inconsistent', -2147415732: 'Query size unknown', -2147416023: 'Sample value not supported', -2147416056: 'Self check failed', -2147415838: 'Service not available', -2147415736: 'Staged operation in progress', -2147415735: 'Staged operation not started', -2147415779: 'Unsupported keyattr mask', -2147415781: 'Unsupported keyusage mask', -2147415785: 'Unsupported key format', -2147415777: 'Unsupported key label', -2147415784: 'Unsupported key size', -2147415839: 'User canceled', -2147415767: 'Vector of bufs unsupported', -2147415734: 'Verify failed', } if num in code_map: output = code_map[num] if not output: output = '%s %s' % (domain, num) raise OSError(output)
def wrap(cls, socket, hostname, session=None): """ Takes an existing socket and adds TLS :param socket: A socket.socket object to wrap with TLS :param hostname: A unicode string of the hostname or IP the socket is connected to :param session: An existing TLSSession object to allow for session reuse, specific protocol or manual certificate validation :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(socket, socket_.socket): raise TypeError(pretty_message( ''' socket must be an instance of socket.socket, not %s ''', type_name(socket) )) if not isinstance(hostname, str_cls): raise TypeError(pretty_message( ''' hostname must be a unicode string, not %s ''', type_name(hostname) )) if session is not None and not isinstance(session, TLSSession): raise TypeError(pretty_message( ''' session must be an instance of oscrypto.tls.TLSSession, not %s ''', type_name(session) )) new_socket = cls(None, None, session=session) new_socket._socket = socket new_socket._hostname = hostname new_socket._handshake() return new_socket
def _handshake(self): """ Perform an initial TLS handshake """ self._ssl = None self._rbio = None self._wbio = None try: self._ssl = libssl.SSL_new(self._session._ssl_ctx) if is_null(self._ssl): self._ssl = None handle_openssl_error(0) mem_bio = libssl.BIO_s_mem() self._rbio = libssl.BIO_new(mem_bio) if is_null(self._rbio): handle_openssl_error(0) self._wbio = libssl.BIO_new(mem_bio) if is_null(self._wbio): handle_openssl_error(0) libssl.SSL_set_bio(self._ssl, self._rbio, self._wbio) utf8_domain = self._hostname.encode('utf-8') libssl.SSL_ctrl( self._ssl, LibsslConst.SSL_CTRL_SET_TLSEXT_HOSTNAME, LibsslConst.TLSEXT_NAMETYPE_host_name, utf8_domain ) libssl.SSL_set_connect_state(self._ssl) if self._session._ssl_session: libssl.SSL_set_session(self._ssl, self._session._ssl_session) self._bio_write_buffer = buffer_from_bytes(self._buffer_size) self._read_buffer = buffer_from_bytes(self._buffer_size) handshake_server_bytes = b'' handshake_client_bytes = b'' while True: result = libssl.SSL_do_handshake(self._ssl) handshake_client_bytes += self._raw_write() if result == 1: break error = libssl.SSL_get_error(self._ssl, result) if error == LibsslConst.SSL_ERROR_WANT_READ: chunk = self._raw_read() if chunk == b'': if handshake_server_bytes == b'': raise_disconnection() if detect_client_auth_request(handshake_server_bytes): raise_client_auth() raise_protocol_error(handshake_server_bytes) handshake_server_bytes += chunk elif error == LibsslConst.SSL_ERROR_WANT_WRITE: handshake_client_bytes += self._raw_write() elif error == LibsslConst.SSL_ERROR_ZERO_RETURN: self._gracefully_closed = True self._shutdown(False) self._raise_closed() else: info = peek_openssl_error() if libcrypto_version_info < (1, 1): dh_key_info = ( 20, LibsslConst.SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, LibsslConst.SSL_R_DH_KEY_TOO_SMALL ) else: dh_key_info = ( 20, LibsslConst.SSL_F_TLS_PROCESS_SKE_DHE, LibsslConst.SSL_R_DH_KEY_TOO_SMALL ) if info == dh_key_info: raise_dh_params() if libcrypto_version_info < (1, 1): unknown_protocol_info = ( 20, LibsslConst.SSL_F_SSL23_GET_SERVER_HELLO, LibsslConst.SSL_R_UNKNOWN_PROTOCOL ) else: unknown_protocol_info = ( 20, LibsslConst.SSL_F_SSL3_GET_RECORD, LibsslConst.SSL_R_WRONG_VERSION_NUMBER ) if info == unknown_protocol_info: raise_protocol_error(handshake_server_bytes) tls_version_info_error = ( 20, LibsslConst.SSL_F_SSL23_GET_SERVER_HELLO, LibsslConst.SSL_R_TLSV1_ALERT_PROTOCOL_VERSION ) if info == tls_version_info_error: raise_protocol_version() handshake_error_info = ( 20, LibsslConst.SSL_F_SSL23_GET_SERVER_HELLO, LibsslConst.SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE ) if info == handshake_error_info: raise_handshake() handshake_failure_info = ( 20, LibsslConst.SSL_F_SSL3_READ_BYTES, LibsslConst.SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE ) if info == handshake_failure_info: raise_client_auth() if libcrypto_version_info < (1, 1): cert_verify_failed_info = ( 20, LibsslConst.SSL_F_SSL3_GET_SERVER_CERTIFICATE, LibsslConst.SSL_R_CERTIFICATE_VERIFY_FAILED ) else: cert_verify_failed_info = ( 20, LibsslConst.SSL_F_TLS_PROCESS_SERVER_CERTIFICATE, LibsslConst.SSL_R_CERTIFICATE_VERIFY_FAILED ) if info == cert_verify_failed_info: verify_result = libssl.SSL_get_verify_result(self._ssl) chain = extract_chain(handshake_server_bytes) self_signed = False time_invalid = False no_issuer = False cert = None oscrypto_cert = None if chain: cert = chain[0] oscrypto_cert = load_certificate(cert) self_signed = oscrypto_cert.self_signed issuer_error_codes = set([ LibsslConst.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, LibsslConst.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, LibsslConst.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ]) if verify_result in issuer_error_codes: no_issuer = not self_signed time_error_codes = set([ LibsslConst.X509_V_ERR_CERT_HAS_EXPIRED, LibsslConst.X509_V_ERR_CERT_NOT_YET_VALID ]) time_invalid = verify_result in time_error_codes if time_invalid: raise_expired_not_yet_valid(cert) if no_issuer: raise_no_issuer(cert) if self_signed: raise_self_signed(cert) if oscrypto_cert and oscrypto_cert.asn1.hash_algo in set(['md5', 'md2']): raise_weak_signature(oscrypto_cert) raise_verification(cert) handle_openssl_error(0, TLSError) session_info = parse_session_info( handshake_server_bytes, handshake_client_bytes ) self._protocol = session_info['protocol'] self._cipher_suite = session_info['cipher_suite'] self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] if self._cipher_suite.find('_DHE_') != -1: dh_params_length = get_dh_params_length(handshake_server_bytes) if dh_params_length < 1024: self.close() raise_dh_params() # When saving the session for future requests, we use # SSL_get1_session() variant to increase the reference count. This # prevents the session from being freed when one connection closes # before another is opened. However, since we increase the ref # count, we also have to explicitly free any previous session. if self._session_id == 'new' or self._session_ticket == 'new': if self._session._ssl_session: libssl.SSL_SESSION_free(self._session._ssl_session) self._session._ssl_session = libssl.SSL_get1_session(self._ssl) if not self._session._manual_validation: if self.certificate.hash_algo in set(['md5', 'md2']): raise_weak_signature(self.certificate) # OpenSSL does not do hostname or IP address checking in the end # entity certificate, so we must perform that check if not self.certificate.is_valid_domain_ip(self._hostname): raise_hostname(self.certificate, self._hostname) except (OSError, socket_.error): if self._ssl: libssl.SSL_free(self._ssl) self._ssl = None self._rbio = None self._wbio = None # The BIOs are freed by SSL_free(), so we only need to free # them if for some reason SSL_free() was not called else: if self._rbio: libssl.BIO_free(self._rbio) self._rbio = None if self._wbio: libssl.BIO_free(self._wbio) self._wbio = None self.close() raise
def _raw_read(self): """ Reads data from the socket and writes it to the memory bio used by libssl to decrypt the data. Returns the unencrypted data for the purpose of debugging handshakes. :return: A byte string of ciphertext from the socket. Used for debugging the handshake only. """ data = self._raw_bytes try: data += self._socket.recv(8192) except (socket_.error): pass output = data written = libssl.BIO_write(self._rbio, data, len(data)) self._raw_bytes = data[written:] return output
def _raw_write(self): """ Takes ciphertext from the memory bio and writes it to the socket. :return: A byte string of ciphertext going to the socket. Used for debugging the handshake only. """ data_available = libssl.BIO_ctrl_pending(self._wbio) if data_available == 0: return b'' to_read = min(self._buffer_size, data_available) read = libssl.BIO_read(self._wbio, self._bio_write_buffer, to_read) to_write = bytes_from_buffer(self._bio_write_buffer, read) output = to_write while len(to_write): raise_disconnect = False try: sent = self._socket.send(to_write) except (socket_.error) as e: # Handle ECONNRESET and EPIPE if e.errno == 104 or e.errno == 32: raise_disconnect = True else: raise if raise_disconnect: raise_disconnection() to_write = to_write[sent:] if len(to_write): self.select_write() return output
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) buffered_length = len(self._decrypted_bytes) # If we already have enough buffered data, just use that if buffered_length >= max_length: output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output if self._ssl is None: self._raise_closed() # Don't block if we have buffered data available, since it is ok to # return less than the max_length if buffered_length > 0 and not self.select_read(0): output = self._decrypted_bytes self._decrypted_bytes = b'' return output # Only read enough to get the requested amount when # combined with buffered data to_read = min(self._buffer_size, max_length - buffered_length) output = self._decrypted_bytes # The SSL_read() loop handles renegotiations, so we need to handle # requests for both reads and writes again = True while again: again = False result = libssl.SSL_read(self._ssl, self._read_buffer, to_read) self._raw_write() if result <= 0: error = libssl.SSL_get_error(self._ssl, result) if error == LibsslConst.SSL_ERROR_WANT_READ: if self._raw_read() != b'': again = True continue raise_disconnection() elif error == LibsslConst.SSL_ERROR_WANT_WRITE: self._raw_write() again = True continue elif error == LibsslConst.SSL_ERROR_ZERO_RETURN: self._gracefully_closed = True self._shutdown(False) break else: handle_openssl_error(0, TLSError) output += bytes_from_buffer(self._read_buffer, result) if self._gracefully_closed and len(output) == 0: self._raise_closed() self._decrypted_bytes = output[max_length:] return output[0:max_length]
def write(self, data): """ Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ data_len = len(data) while data_len: if self._ssl is None: self._raise_closed() result = libssl.SSL_write(self._ssl, data, data_len) self._raw_write() if result <= 0: error = libssl.SSL_get_error(self._ssl, result) if error == LibsslConst.SSL_ERROR_WANT_READ: if self._raw_read() != b'': continue raise_disconnection() elif error == LibsslConst.SSL_ERROR_WANT_WRITE: self._raw_write() continue elif error == LibsslConst.SSL_ERROR_ZERO_RETURN: self._gracefully_closed = True self._shutdown(False) self._raise_closed() else: handle_openssl_error(0, TLSError) data = data[result:] data_len = len(data)
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._ssl is None: return while True: result = libssl.SSL_shutdown(self._ssl) # Don't be noisy if the socket is already closed try: self._raw_write() except (TLSDisconnectError): pass if result >= 0: break if result < 0: error = libssl.SSL_get_error(self._ssl, result) if error == LibsslConst.SSL_ERROR_WANT_READ: if self._raw_read() != b'': continue else: break elif error == LibsslConst.SSL_ERROR_WANT_WRITE: self._raw_write() continue else: handle_openssl_error(0, TLSError) if manual: self._local_closed = True libssl.SSL_free(self._ssl) self._ssl = None # BIOs are freed by SSL_free() self._rbio = None self._wbio = None try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ stack_pointer = libssl.SSL_get_peer_cert_chain(self._ssl) if is_null(stack_pointer): handle_openssl_error(0, TLSError) if libcrypto_version_info < (1, 1): number_certs = libssl.sk_num(stack_pointer) else: number_certs = libssl.OPENSSL_sk_num(stack_pointer) self._intermediates = [] for index in range(0, number_certs): if libcrypto_version_info < (1, 1): x509_ = libssl.sk_value(stack_pointer, index) else: x509_ = libssl.OPENSSL_sk_value(stack_pointer, index) buffer_size = libcrypto.i2d_X509(x509_, null()) cert_buffer = buffer_from_bytes(buffer_size) cert_pointer = buffer_pointer(cert_buffer) cert_length = libcrypto.i2d_X509(x509_, cert_pointer) handle_openssl_error(cert_length) cert_data = bytes_from_buffer(cert_buffer, cert_length) cert = x509.Certificate.load(cert_data) if index == 0: self._certificate = cert else: self._intermediates.append(cert)
def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._ssl is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._certificate
def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._ssl is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates
def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) if len(data) % 16 != 0: raise ValueError(pretty_message( ''' data must be a multiple of 16 bytes long - is %s ''', len(data) )) return (iv, _encrypt('aes', key, data, iv, False))
def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt('aes', key, data, iv, False)
def tripledes_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) cipher = 'tripledes_3key' if len(key) == 16: cipher = 'tripledes_2key' return (iv, _encrypt(cipher, key, data, iv, True))
def _advapi32_create_handles(cipher, key, iv): """ Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The HCRYPTPROV must be released by close_context_handle() and the HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :param iv: The initialization vector - a byte string - unused for RC4 :return: A tuple of (HCRYPTPROV, HCRYPTKEY) """ context_handle = None if cipher == 'aes': algorithm_id = { 16: Advapi32Const.CALG_AES_128, 24: Advapi32Const.CALG_AES_192, 32: Advapi32Const.CALG_AES_256, }[len(key)] else: algorithm_id = { 'des': Advapi32Const.CALG_DES, 'tripledes_2key': Advapi32Const.CALG_3DES_112, 'tripledes_3key': Advapi32Const.CALG_3DES, 'rc2': Advapi32Const.CALG_RC2, 'rc4': Advapi32Const.CALG_RC4, }[cipher] provider = Advapi32Const.MS_ENH_RSA_AES_PROV context_handle = open_context_handle(provider, verify_only=False) blob_header_pointer = struct(advapi32, 'BLOBHEADER') blob_header = unwrap(blob_header_pointer) blob_header.bType = Advapi32Const.PLAINTEXTKEYBLOB blob_header.bVersion = Advapi32Const.CUR_BLOB_VERSION blob_header.reserved = 0 blob_header.aiKeyAlg = algorithm_id blob_struct_pointer = struct(advapi32, 'PLAINTEXTKEYBLOB') blob_struct = unwrap(blob_struct_pointer) blob_struct.hdr = blob_header blob_struct.dwKeySize = len(key) blob = struct_bytes(blob_struct_pointer) + key flags = 0 if cipher in set(['rc2', 'rc4']) and len(key) == 5: flags = Advapi32Const.CRYPT_NO_SALT key_handle_pointer = new(advapi32, 'HCRYPTKEY *') res = advapi32.CryptImportKey( context_handle, blob, len(blob), null(), flags, key_handle_pointer ) handle_error(res) key_handle = unwrap(key_handle_pointer) if cipher == 'rc2': buf = new(advapi32, 'DWORD *', len(key) * 8) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_EFFECTIVE_KEYLEN, buf, 0 ) handle_error(res) if cipher != 'rc4': res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_IV, iv, 0 ) handle_error(res) buf = new(advapi32, 'DWORD *', Advapi32Const.CRYPT_MODE_CBC) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_MODE, buf, 0 ) handle_error(res) buf = new(advapi32, 'DWORD *', Advapi32Const.PKCS5_PADDING) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_PADDING, buf, 0 ) handle_error(res) return (context_handle, key_handle)
def _bcrypt_create_key_handle(cipher, key): """ Creates a BCRYPT_KEY_HANDLE for symmetric encryption/decryption. The handle must be released by bcrypt.BCryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :return: A BCRYPT_KEY_HANDLE """ alg_handle = None alg_constant = { 'aes': BcryptConst.BCRYPT_AES_ALGORITHM, 'des': BcryptConst.BCRYPT_DES_ALGORITHM, 'tripledes_2key': BcryptConst.BCRYPT_3DES_112_ALGORITHM, 'tripledes_3key': BcryptConst.BCRYPT_3DES_ALGORITHM, 'rc2': BcryptConst.BCRYPT_RC2_ALGORITHM, 'rc4': BcryptConst.BCRYPT_RC4_ALGORITHM, }[cipher] try: alg_handle = open_alg_handle(alg_constant) blob_type = BcryptConst.BCRYPT_KEY_DATA_BLOB blob_struct_pointer = struct(bcrypt, 'BCRYPT_KEY_DATA_BLOB_HEADER') blob_struct = unwrap(blob_struct_pointer) blob_struct.dwMagic = BcryptConst.BCRYPT_KEY_DATA_BLOB_MAGIC blob_struct.dwVersion = BcryptConst.BCRYPT_KEY_DATA_BLOB_VERSION1 blob_struct.cbKeyData = len(key) blob = struct_bytes(blob_struct_pointer) + key if cipher == 'rc2': buf = new(bcrypt, 'DWORD *', len(key) * 8) res = bcrypt.BCryptSetProperty( alg_handle, BcryptConst.BCRYPT_EFFECTIVE_KEY_LENGTH, buf, 4, 0 ) handle_error(res) key_handle_pointer = new(bcrypt, 'BCRYPT_KEY_HANDLE *') res = bcrypt.BCryptImportKey( alg_handle, null(), blob_type, key_handle_pointer, null(), 0, blob, len(blob), 0 ) handle_error(res) return unwrap(key_handle_pointer) finally: if alg_handle: close_alg_handle(alg_handle)
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != 'rc4' and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != 'rc4' and not padding: raise ValueError('padding must be specified') if _backend == 'winlegacy': return _advapi32_encrypt(cipher, key, data, iv, padding) return _bcrypt_encrypt(cipher, key, data, iv, padding)
def _advapi32_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ context_handle = None key_handle = None try: context_handle, key_handle = _advapi32_create_handles(cipher, key, iv) out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptEncrypt( key_handle, null(), True, 0, null(), out_len, 0 ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) write_to_buffer(buffer, data) pointer_set(out_len, len(data)) res = advapi32.CryptEncrypt( key_handle, null(), True, 0, buffer, out_len, buffer_len ) handle_error(res) output = bytes_from_buffer(buffer, deref(out_len)) # Remove padding when not required. CryptoAPI doesn't support this, so # we just manually remove it. if cipher == 'aes' and not padding: if output[-16:] != (b'\x10' * 16): raise ValueError('Invalid padding generated by OS crypto library') output = output[:-16] return output finally: if key_handle: advapi32.CryptDestroyKey(key_handle) if context_handle: close_context_handle(context_handle)
def _bcrypt_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CNG :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ key_handle = None try: key_handle = _bcrypt_create_key_handle(cipher, key) if iv is None: iv_len = 0 else: iv_len = len(iv) flags = 0 if padding is True: flags = BcryptConst.BCRYPT_BLOCK_PADDING out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptEncrypt( key_handle, data, len(data), null(), null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) iv_buffer = buffer_from_bytes(iv) if iv else null() res = bcrypt.BCryptEncrypt( key_handle, data, len(data), null(), iv_buffer, iv_len, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) finally: if key_handle: bcrypt.BCryptDestroyKey(key_handle)
def _decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != 'rc4' and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != 'rc4' and padding is None: raise ValueError('padding must be specified') if _backend == 'winlegacy': return _advapi32_decrypt(cipher, key, data, iv, padding) return _bcrypt_decrypt(cipher, key, data, iv, padding)
def _advapi32_decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ context_handle = None key_handle = None try: context_handle, key_handle = _advapi32_create_handles(cipher, key, iv) # Add removed padding when not required. CryptoAPI doesn't support no # padding, so we just add it back in if cipher == 'aes' and not padding: data += (b'\x10' * 16) buffer = buffer_from_bytes(data) out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptDecrypt( key_handle, null(), True, 0, buffer, out_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) finally: if key_handle: advapi32.CryptDestroyKey(key_handle) if context_handle: close_context_handle(context_handle)
def handle_error(error_num): """ Extracts the last Windows error message into a python unicode string :param error_num: The number to get the error string for :return: A unicode string error message """ if error_num == 0: return messages = { BcryptConst.STATUS_NOT_FOUND: 'The object was not found', BcryptConst.STATUS_INVALID_PARAMETER: 'An invalid parameter was passed to a service or function', BcryptConst.STATUS_NO_MEMORY: ( 'Not enough virtual memory or paging file quota is available to complete the specified operation' ), BcryptConst.STATUS_INVALID_HANDLE: 'An invalid HANDLE was specified', BcryptConst.STATUS_INVALID_SIGNATURE: 'The cryptographic signature is invalid', BcryptConst.STATUS_NOT_SUPPORTED: 'The request is not supported', BcryptConst.STATUS_BUFFER_TOO_SMALL: 'The buffer is too small to contain the entry', BcryptConst.STATUS_INVALID_BUFFER_SIZE: 'The size of the buffer is invalid for the specified operation', } output = 'NTSTATUS error 0x%0.2X' % error_num if error_num is not None and error_num in messages: output += ': ' + messages[error_num] raise OSError(output)
def handle_openssl_error(result, exception_class=None): """ Checks if an error occured, and if so throws an OSError containing the last OpenSSL error message :param result: An integer result code - 1 or greater indicates success :param exception_class: The exception class to use for the exception if an error occurred :raises: OSError - when an OpenSSL error occurs """ if result > 0: return if exception_class is None: exception_class = OSError error_num = libcrypto.ERR_get_error() buffer = buffer_from_bytes(120) libcrypto.ERR_error_string(error_num, buffer) # Since we are dealing with a string, it is NULL terminated error_string = byte_string_from_buffer(buffer) raise exception_class(_try_decode(error_string))
def peek_openssl_error(): """ Peeks into the error stack and pulls out the lib, func and reason :return: A three-element tuple of integers (lib, func, reason) """ error = libcrypto.ERR_peek_error() lib = int((error >> 24) & 0xff) func = int((error >> 12) & 0xfff) reason = int(error & 0xfff) return (lib, func, reason)
def _is_osx_107(): """ :return: A bool if the current machine is running OS X 10.7 """ if sys.platform != 'darwin': return False version = platform.mac_ver()[0] return tuple(map(int, version.split('.')))[0:2] == (10, 7)
def add_pss_padding(hash_algorithm, salt_length, key_length, message): """ Pads a byte string using the EMSA-PSS-Encode operation described in PKCS#1 v2.2. :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param salt_length: The length of the salt as an integer - typically the same as the length of the output from the hash_algorithm :param key_length: The length of the RSA key, in bits :param message: A byte string of the message to pad :return: The encoded (passed) message """ if _backend != 'winlegacy' and sys.platform != 'darwin': raise SystemError(pretty_message( ''' Pure-python RSA PSS signature padding addition code is only for Windows XP/2003 and OS X ''' )) if not isinstance(message, byte_cls): raise TypeError(pretty_message( ''' message must be a byte string, not %s ''', type_name(message) )) if not isinstance(salt_length, int_types): raise TypeError(pretty_message( ''' salt_length must be an integer, not %s ''', type_name(salt_length) )) if salt_length < 0: raise ValueError(pretty_message( ''' salt_length must be 0 or more - is %s ''', repr(salt_length) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 512: raise ValueError(pretty_message( ''' key_length must be 512 or more - is %s ''', repr(key_length) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) hash_func = getattr(hashlib, hash_algorithm) # The maximal bit size of a non-negative integer is one less than the bit # size of the key since the first bit is used to store sign em_bits = key_length - 1 em_len = int(math.ceil(em_bits / 8)) message_digest = hash_func(message).digest() hash_length = len(message_digest) if em_len < hash_length + salt_length + 2: raise ValueError(pretty_message( ''' Key is not long enough to use with specified hash_algorithm and salt_length ''' )) if salt_length > 0: salt = os.urandom(salt_length) else: salt = b'' m_prime = (b'\x00' * 8) + message_digest + salt m_prime_digest = hash_func(m_prime).digest() padding = b'\x00' * (em_len - salt_length - hash_length - 2) db = padding + b'\x01' + salt db_mask = _mgf1(hash_algorithm, m_prime_digest, em_len - hash_length - 1) masked_db = int_to_bytes(int_from_bytes(db) ^ int_from_bytes(db_mask)) masked_db = fill_width(masked_db, len(db_mask)) zero_bits = (8 * em_len) - em_bits left_bit_mask = ('0' * zero_bits) + ('1' * (8 - zero_bits)) left_int_mask = int(left_bit_mask, 2) if left_int_mask != 255: masked_db = chr_cls(left_int_mask & ord(masked_db[0:1])) + masked_db[1:] return masked_db + m_prime_digest + b'\xBC'
def verify_pss_padding(hash_algorithm, salt_length, key_length, message, signature): """ Verifies the PSS padding on an encoded message :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param salt_length: The length of the salt as an integer - typically the same as the length of the output from the hash_algorithm :param key_length: The length of the RSA key, in bits :param message: A byte string of the message to pad :param signature: The signature to verify :return: A boolean indicating if the signature is invalid """ if _backend != 'winlegacy' and sys.platform != 'darwin': raise SystemError(pretty_message( ''' Pure-python RSA PSS signature padding verification code is only for Windows XP/2003 and OS X ''' )) if not isinstance(message, byte_cls): raise TypeError(pretty_message( ''' message must be a byte string, not %s ''', type_name(message) )) if not isinstance(signature, byte_cls): raise TypeError(pretty_message( ''' signature must be a byte string, not %s ''', type_name(signature) )) if not isinstance(salt_length, int_types): raise TypeError(pretty_message( ''' salt_length must be an integer, not %s ''', type_name(salt_length) )) if salt_length < 0: raise ValueError(pretty_message( ''' salt_length must be 0 or more - is %s ''', repr(salt_length) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) hash_func = getattr(hashlib, hash_algorithm) em_bits = key_length - 1 em_len = int(math.ceil(em_bits / 8)) message_digest = hash_func(message).digest() hash_length = len(message_digest) if em_len < hash_length + salt_length + 2: return False if signature[-1:] != b'\xBC': return False zero_bits = (8 * em_len) - em_bits masked_db_length = em_len - hash_length - 1 masked_db = signature[0:masked_db_length] first_byte = ord(masked_db[0:1]) bits_that_should_be_zero = first_byte >> (8 - zero_bits) if bits_that_should_be_zero != 0: return False m_prime_digest = signature[masked_db_length:masked_db_length + hash_length] db_mask = _mgf1(hash_algorithm, m_prime_digest, em_len - hash_length - 1) left_bit_mask = ('0' * zero_bits) + ('1' * (8 - zero_bits)) left_int_mask = int(left_bit_mask, 2) if left_int_mask != 255: db_mask = chr_cls(left_int_mask & ord(db_mask[0:1])) + db_mask[1:] db = int_to_bytes(int_from_bytes(masked_db) ^ int_from_bytes(db_mask)) if len(db) < len(masked_db): db = (b'\x00' * (len(masked_db) - len(db))) + db zero_length = em_len - hash_length - salt_length - 2 zero_string = b'\x00' * zero_length if not constant_compare(db[0:zero_length], zero_string): return False if db[zero_length:zero_length + 1] != b'\x01': return False salt = db[0 - salt_length:] m_prime = (b'\x00' * 8) + message_digest + salt h_prime = hash_func(m_prime).digest() return constant_compare(m_prime_digest, h_prime)
def _mgf1(hash_algorithm, seed, mask_length): """ The PKCS#1 MGF1 mask generation algorithm :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param seed: A byte string to use as the seed for the mask :param mask_length: The desired mask length, as an integer :return: A byte string of the mask """ if not isinstance(seed, byte_cls): raise TypeError(pretty_message( ''' seed must be a byte string, not %s ''', type_name(seed) )) if not isinstance(mask_length, int_types): raise TypeError(pretty_message( ''' mask_length must be an integer, not %s ''', type_name(mask_length) )) if mask_length < 1: raise ValueError(pretty_message( ''' mask_length must be greater than 0 - is %s ''', repr(mask_length) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) output = b'' hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] iterations = int(math.ceil(mask_length / hash_length)) pack = struct.Struct(b'>I').pack hash_func = getattr(hashlib, hash_algorithm) for counter in range(0, iterations): b = pack(counter) output += hash_func(seed + b).digest() return output[0:mask_length]
def _add_pkcs1v15_padding(key_length, data, operation): """ Adds PKCS#1 v1.5 padding to a message :param key_length: An integer of the number of bytes in the key :param data: A byte string to unpad :param operation: A unicode string of "encrypting" or "signing" :return: The padded data as a byte string """ if operation == 'encrypting': second_byte = b'\x02' else: second_byte = b'\x01' if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 64: raise ValueError(pretty_message( ''' key_length must be 64 or more - is %s ''', repr(key_length) )) if len(data) > key_length - 11: raise ValueError(pretty_message( ''' data must be between 1 and %s bytes long - is %s ''', key_length - 11, len(data) )) required_bytes = key_length - 3 - len(data) padding = b'' while required_bytes > 0: temp_padding = rand_bytes(required_bytes) # Remove null bytes since they are markers in PKCS#1 v1.5 temp_padding = b''.join(temp_padding.split(b'\x00')) padding += temp_padding required_bytes -= len(temp_padding) return b'\x00' + second_byte + padding + b'\x00' + data
def _remove_pkcs1v15_padding(key_length, data, operation): """ Removes PKCS#1 v1.5 padding from a message using constant time operations :param key_length: An integer of the number of bytes in the key :param data: A byte string to unpad :param operation: A unicode string of "decrypting" or "verifying" :return: The unpadded data as a byte string """ if operation == 'decrypting': second_byte = 2 else: second_byte = 1 if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 64: raise ValueError(pretty_message( ''' key_length must be 64 or more - is %s ''', repr(key_length) )) if len(data) != key_length: raise ValueError('Error %s' % operation) error = 0 trash = 0 padding_end = 0 # Uses bitwise operations on an error variable and another trash variable # to perform constant time error checking/token scanning on the data for i in range(0, len(data)): byte = data[i:i + 1] byte_num = ord(byte) # First byte should be \x00 if i == 0: error |= byte_num # Second byte should be \x02 for decryption, \x01 for verification elif i == 1: error |= int((byte_num | second_byte) != second_byte) # Bytes 3-10 should not be \x00 elif i < 10: error |= int((byte_num ^ 0) == 0) # Byte 11 or after that is zero is end of padding else: non_zero = byte_num | 0 if padding_end == 0: if non_zero: trash |= i else: padding_end |= i else: if non_zero: trash |= i else: trash |= i if error != 0: raise ValueError('Error %s' % operation) return data[padding_end + 1:]
def raw_rsa_private_crypt(private_key, data): """ Performs a raw RSA algorithm in a byte string using a private key. This is a low-level primitive and is prone to disastrous results if used incorrectly. :param private_key: An oscrypto.asymmetric.PrivateKey object :param data: A byte string of the plaintext to be signed or ciphertext to be decrypted. Must be less than or equal to the length of the private key. In the case of signing, padding must already be applied. In the case of decryption, padding must be removed afterward. :return: A byte string of the transformed data """ if _backend != 'winlegacy': raise SystemError('Pure-python RSA crypt is only for Windows XP/2003') if not hasattr(private_key, 'asn1') or not isinstance(private_key.asn1, PrivateKeyInfo): raise TypeError(pretty_message( ''' private_key must be an instance of the oscrypto.asymmetric.PrivateKey class, not %s ''', type_name(private_key) )) algo = private_key.asn1['private_key_algorithm']['algorithm'].native if algo != 'rsa': raise ValueError(pretty_message( ''' private_key must be an RSA key, not %s ''', algo.upper() )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) rsa_private_key = private_key.asn1['private_key'].parsed transformed_int = pow( int_from_bytes(data), rsa_private_key['private_exponent'].native, rsa_private_key['modulus'].native ) return int_to_bytes(transformed_int, width=private_key.asn1.byte_size)
def raw_rsa_public_crypt(certificate_or_public_key, data): """ Performs a raw RSA algorithm in a byte string using a certificate or public key. This is a low-level primitive and is prone to disastrous results if used incorrectly. :param certificate_or_public_key: An oscrypto.asymmetric.PublicKey or oscrypto.asymmetric.Certificate object :param data: A byte string of the signature when verifying, or padded plaintext when encrypting. Must be less than or equal to the length of the public key. When verifying, padding will need to be removed afterwards. When encrypting, padding must be applied before. :return: A byte string of the transformed data """ if _backend != 'winlegacy': raise SystemError('Pure-python RSA crypt is only for Windows XP/2003') has_asn1 = hasattr(certificate_or_public_key, 'asn1') valid_types = (PublicKeyInfo, Certificate) if not has_asn1 or not isinstance(certificate_or_public_key.asn1, valid_types): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the oscrypto.asymmetric.PublicKey or oscrypto.asymmetric.Certificate classes, not %s ''', type_name(certificate_or_public_key) )) algo = certificate_or_public_key.asn1['algorithm']['algorithm'].native if algo != 'rsa': raise ValueError(pretty_message( ''' certificate_or_public_key must be an RSA key, not %s ''', algo.upper() )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) rsa_public_key = certificate_or_public_key.asn1['public_key'].parsed transformed_int = pow( int_from_bytes(data), rsa_public_key['public_exponent'].native, rsa_public_key['modulus'].native ) return int_to_bytes( transformed_int, width=certificate_or_public_key.asn1.byte_size )
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_): """ KDF from RFC7292 appendix B.2 - https://tools.ietf.org/html/rfc7292#page-19 :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :param id_: The ID of the usage - 1 for key, 2 for iv, 3 for mac :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError(pretty_message( ''' iterations must be greater than 0 - is %s ''', repr(iterations) )) if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError(pretty_message( ''' key_length must be greater than 0 - is %s ''', repr(key_length) )) if hash_algorithm not in set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md5", "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) if id_ not in set([1, 2, 3]): raise ValueError(pretty_message( ''' id_ must be one of 1, 2, 3, not %s ''', repr(id_) )) utf16_password = password.decode('utf-8').encode('utf-16be') + b'\x00\x00' digest_type = { 'md5': libcrypto.EVP_md5, 'sha1': libcrypto.EVP_sha1, 'sha224': libcrypto.EVP_sha224, 'sha256': libcrypto.EVP_sha256, 'sha384': libcrypto.EVP_sha384, 'sha512': libcrypto.EVP_sha512, }[hash_algorithm]() output_buffer = buffer_from_bytes(key_length) result = libcrypto.PKCS12_key_gen_uni( utf16_password, len(utf16_password), salt, len(salt), id_, iterations, key_length, output_buffer, digest_type ) handle_openssl_error(result) return bytes_from_buffer(output_buffer)
def extract_from_system(cert_callback=None, callback_only_on_failure=False): """ Extracts trusted CA certificates from the OS X trusted root keychain. :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :param callback_only_on_failure: A boolean - if the callback should only be called when a certificate is not exported. :raises: OSError - when an error is returned by the OS crypto library :return: A list of 3-element tuples: - 0: a byte string of a DER-encoded certificate - 1: a set of unicode strings that are OIDs of purposes to trust the certificate for - 2: a set of unicode strings that are OIDs of purposes to reject the certificate for """ certs_pointer_pointer = new(CoreFoundation, 'CFArrayRef *') res = Security.SecTrustCopyAnchorCertificates(certs_pointer_pointer) handle_sec_error(res) certs_pointer = unwrap(certs_pointer_pointer) certificates = {} trust_info = {} all_purposes = '2.5.29.37.0' default_trust = (set(), set()) length = CoreFoundation.CFArrayGetCount(certs_pointer) for index in range(0, length): cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(certs_pointer, index) der_cert, cert_hash = _cert_details(cert_pointer) certificates[cert_hash] = der_cert CoreFoundation.CFRelease(certs_pointer) for domain in [SecurityConst.kSecTrustSettingsDomainUser, SecurityConst.kSecTrustSettingsDomainAdmin]: cert_trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *') res = Security.SecTrustSettingsCopyCertificates(domain, cert_trust_settings_pointer_pointer) if res == SecurityConst.errSecNoTrustSettings: continue handle_sec_error(res) cert_trust_settings_pointer = unwrap(cert_trust_settings_pointer_pointer) length = CoreFoundation.CFArrayGetCount(cert_trust_settings_pointer) for index in range(0, length): cert_pointer = CoreFoundation.CFArrayGetValueAtIndex(cert_trust_settings_pointer, index) trust_settings_pointer_pointer = new(CoreFoundation, 'CFArrayRef *') res = Security.SecTrustSettingsCopyTrustSettings(cert_pointer, domain, trust_settings_pointer_pointer) # In OS X 10.11, this value started being seen. From the comments in # the Security Framework Reference, the lack of any settings should # indicate "always trust this certificate" if res == SecurityConst.errSecItemNotFound: continue # If the trust settings for a certificate are invalid, we need to # assume the certificate should not be trusted if res == SecurityConst.errSecInvalidTrustSettings: der_cert, cert_hash = _cert_details(cert_pointer) if cert_hash in certificates: _cert_callback( cert_callback, certificates[cert_hash], 'invalid trust settings' ) del certificates[cert_hash] continue handle_sec_error(res) trust_settings_pointer = unwrap(trust_settings_pointer_pointer) trust_oids = set() reject_oids = set() settings_length = CoreFoundation.CFArrayGetCount(trust_settings_pointer) for settings_index in range(0, settings_length): settings_dict_entry = CoreFoundation.CFArrayGetValueAtIndex(trust_settings_pointer, settings_index) settings_dict = CFHelpers.cf_dictionary_to_dict(settings_dict_entry) # No policy OID means the trust result is for all purposes policy_oid = settings_dict.get('kSecTrustSettingsPolicy', {}).get('SecPolicyOid', all_purposes) # 0 = kSecTrustSettingsResultInvalid # 1 = kSecTrustSettingsResultTrustRoot # 2 = kSecTrustSettingsResultTrustAsRoot # 3 = kSecTrustSettingsResultDeny # 4 = kSecTrustSettingsResultUnspecified trust_result = settings_dict.get('kSecTrustSettingsResult', 1) should_trust = trust_result != 0 and trust_result != 3 if should_trust: trust_oids.add(policy_oid) else: reject_oids.add(policy_oid) der_cert, cert_hash = _cert_details(cert_pointer) # If rejected for all purposes, we don't export the certificate if all_purposes in reject_oids: if cert_hash in certificates: _cert_callback( cert_callback, certificates[cert_hash], 'explicitly distrusted' ) del certificates[cert_hash] else: if all_purposes in trust_oids: trust_oids = set([all_purposes]) trust_info[cert_hash] = (trust_oids, reject_oids) CoreFoundation.CFRelease(trust_settings_pointer) CoreFoundation.CFRelease(cert_trust_settings_pointer) output = [] for cert_hash in certificates: if not callback_only_on_failure: _cert_callback(cert_callback, certificates[cert_hash], None) cert_trust_info = trust_info.get(cert_hash, default_trust) output.append((certificates[cert_hash], cert_trust_info[0], cert_trust_info[1])) return output
def _cert_callback(callback, der_cert, reason): """ Constructs an asn1crypto.x509.Certificate object and calls the export callback :param callback: The callback to call :param der_cert: A byte string of the DER-encoded certificate :param reason: None if cert is being exported, or a unicode string of the reason it is not being exported """ if not callback: return callback(x509.Certificate.load(der_cert), reason)
def _cert_details(cert_pointer): """ Return the certificate and a hash of it :param cert_pointer: A SecCertificateRef :return: A 2-element tuple: - [0]: A byte string of the SHA1 hash of the cert - [1]: A byte string of the DER-encoded contents of the cert """ data_pointer = None try: data_pointer = Security.SecCertificateCopyData(cert_pointer) der_cert = CFHelpers.cf_data_to_bytes(data_pointer) cert_hash = hashlib.sha1(der_cert).digest() return (der_cert, cert_hash) finally: if data_pointer is not None: CoreFoundation.CFRelease(data_pointer)
def _extract_error(): """ Extracts the last OS error message into a python unicode string :return: A unicode string error message """ error_num = errno() try: error_string = os.strerror(error_num) except (ValueError): return str_cls(error_num) if isinstance(error_string, str_cls): return error_string return _try_decode(error_string)
def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError('iterations must be greater than 0') if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError('key_length must be greater than 0') if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) algo = { 'sha1': CommonCryptoConst.kCCPRFHmacAlgSHA1, 'sha224': CommonCryptoConst.kCCPRFHmacAlgSHA224, 'sha256': CommonCryptoConst.kCCPRFHmacAlgSHA256, 'sha384': CommonCryptoConst.kCCPRFHmacAlgSHA384, 'sha512': CommonCryptoConst.kCCPRFHmacAlgSHA512 }[hash_algorithm] output_buffer = buffer_from_bytes(key_length) result = CommonCrypto.CCKeyDerivationPBKDF( CommonCryptoConst.kCCPBKDF2, password, len(password), salt, len(salt), algo, iterations, output_buffer, key_length ) if result != 0: raise OSError(_extract_error()) return bytes_from_buffer(output_buffer)
def rand_bytes(length): """ Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string """ if not isinstance(length, int_types): raise TypeError(pretty_message( ''' length must be an integer, not %s ''', type_name(length) )) if length < 1: raise ValueError('length must be greater than 0') if length > 1024: raise ValueError('length must not be greater than 1024') buffer = buffer_from_bytes(length) result = Security.SecRandomCopyBytes(Security.kSecRandomDefault, length, buffer) if result != 0: raise OSError(_extract_error()) return bytes_from_buffer(buffer)
def cf_number_to_number(value): """ Converts a CFNumber object to a python float or integer :param value: The CFNumber object :return: A python number (float or integer) """ type_ = CoreFoundation.CFNumberGetType(_cast_pointer_p(value)) c_type = { 1: c_byte, # kCFNumberSInt8Type 2: ctypes.c_short, # kCFNumberSInt16Type 3: ctypes.c_int32, # kCFNumberSInt32Type 4: ctypes.c_int64, # kCFNumberSInt64Type 5: ctypes.c_float, # kCFNumberFloat32Type 6: ctypes.c_double, # kCFNumberFloat64Type 7: c_byte, # kCFNumberCharType 8: ctypes.c_short, # kCFNumberShortType 9: ctypes.c_int, # kCFNumberIntType 10: c_long, # kCFNumberLongType 11: ctypes.c_longlong, # kCFNumberLongLongType 12: ctypes.c_float, # kCFNumberFloatType 13: ctypes.c_double, # kCFNumberDoubleType 14: c_long, # kCFNumberCFIndexType 15: ctypes.c_int, # kCFNumberNSIntegerType 16: ctypes.c_double, # kCFNumberCGFloatType }[type_] output = c_type(0) CoreFoundation.CFNumberGetValue(_cast_pointer_p(value), type_, byref(output)) return output.value
def cf_dictionary_to_dict(dictionary): """ Converts a CFDictionary object into a python dictionary :param dictionary: The CFDictionary to convert :return: A python dict """ dict_length = CoreFoundation.CFDictionaryGetCount(dictionary) keys = (CFTypeRef * dict_length)() values = (CFTypeRef * dict_length)() CoreFoundation.CFDictionaryGetKeysAndValues( dictionary, _cast_pointer_p(keys), _cast_pointer_p(values) ) output = {} for index in range(0, dict_length): output[CFHelpers.native(keys[index])] = CFHelpers.native(values[index]) return output
def native(cls, value): """ Converts a CF* object into its python equivalent :param value: The CF* object to convert :return: The native python object """ type_id = CoreFoundation.CFGetTypeID(value) if type_id in cls._native_map: return cls._native_map[type_id](value) else: return value
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string = CoreFoundation.CFStringGetCStringPtr( _cast_pointer_p(value), kCFStringEncodingUTF8 ) if string is None: buffer = buffer_from_bytes(1024) result = CoreFoundation.CFStringGetCString( _cast_pointer_p(value), buffer, 1024, kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = byte_string_from_buffer(buffer) if string is not None: string = string.decode('utf-8') return string
def cf_data_to_bytes(value): """ Extracts a bytestring from a CFData object :param value: A CFData object :return: A byte string """ start = CoreFoundation.CFDataGetBytePtr(value) num_bytes = CoreFoundation.CFDataGetLength(value) return string_at(start, num_bytes)
def cf_dictionary_from_pairs(pairs): """ Creates a CFDictionaryRef object from a list of 2-element tuples representing the key and value. Each key should be a CFStringRef and each value some sort of CF* type. :param pairs: A list of 2-element tuples :return: A CFDictionaryRef """ length = len(pairs) keys = [] values = [] for pair in pairs: key, value = pair keys.append(key) values.append(value) keys = (CFStringRef * length)(*keys) values = (CFTypeRef * length)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, _cast_pointer_p(byref(keys)), _cast_pointer_p(byref(values)), length, kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks )
def cf_array_from_list(values): """ Creates a CFArrayRef object from a list of CF* type objects. :param values: A list of CF* type object :return: A CFArrayRef """ length = len(values) values = (CFTypeRef * length)(*values) return CoreFoundation.CFArrayCreate( CoreFoundation.kCFAllocatorDefault, _cast_pointer_p(byref(values)), length, kCFTypeArrayCallBacks )
def cf_number_from_integer(integer): """ Creates a CFNumber object from an integer :param integer: The integer to create the CFNumber for :return: A CFNumber """ integer_as_long = c_long(integer) return CoreFoundation.CFNumberCreate( CoreFoundation.kCFAllocatorDefault, kCFNumberCFIndexType, byref(integer_as_long) )
def cf_number_to_number(value): """ Converts a CFNumber object to a python float or integer :param value: The CFNumber object :return: A python number (float or integer) """ type_ = CoreFoundation.CFNumberGetType(value) type_name_ = { 1: 'int8_t', # kCFNumberSInt8Type 2: 'in16_t', # kCFNumberSInt16Type 3: 'int32_t', # kCFNumberSInt32Type 4: 'int64_t', # kCFNumberSInt64Type 5: 'float', # kCFNumberFloat32Type 6: 'double', # kCFNumberFloat64Type 7: 'char', # kCFNumberCharType 8: 'short', # kCFNumberShortType 9: 'int', # kCFNumberIntType 10: 'long', # kCFNumberLongType 11: 'long long', # kCFNumberLongLongType 12: 'float', # kCFNumberFloatType 13: 'double', # kCFNumberDoubleType 14: 'long', # kCFNumberCFIndexType 15: 'int', # kCFNumberNSIntegerType 16: 'double', # kCFNumberCGFloatType }[type_] output = new(CoreFoundation, type_name_ + ' *') CoreFoundation.CFNumberGetValue(value, type_, output) return deref(output)
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string_ptr = CoreFoundation.CFStringGetCStringPtr( value, kCFStringEncodingUTF8 ) string = None if is_null(string_ptr) else ffi.string(string_ptr) if string is None: buffer = buffer_from_bytes(1024) result = CoreFoundation.CFStringGetCString( value, buffer, 1024, kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = byte_string_from_buffer(buffer) if string is not None: string = string.decode('utf-8') return string
def cf_data_to_bytes(value): """ Extracts a bytestring from a CFData object :param value: A CFData object :return: A byte string """ start = CoreFoundation.CFDataGetBytePtr(value) num_bytes = CoreFoundation.CFDataGetLength(value) return ffi.buffer(start, num_bytes)[:]
def cf_dictionary_from_pairs(pairs): """ Creates a CFDictionaryRef object from a list of 2-element tuples representing the key and value. Each key should be a CFStringRef and each value some sort of CF* type. :param pairs: A list of 2-element tuples :return: A CFDictionaryRef """ length = len(pairs) keys = [] values = [] for pair in pairs: key, value = pair keys.append(key) values.append(value) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, keys, values, length, ffi.addressof(CoreFoundation.kCFTypeDictionaryKeyCallBacks), ffi.addressof(CoreFoundation.kCFTypeDictionaryValueCallBacks) )
def cf_array_from_list(values): """ Creates a CFArrayRef object from a list of CF* type objects. :param values: A list of CF* type object :return: A CFArrayRef """ length = len(values) return CoreFoundation.CFArrayCreate( CoreFoundation.kCFAllocatorDefault, values, length, ffi.addressof(CoreFoundation.kCFTypeArrayCallBacks) )
def cf_number_from_integer(integer): """ Creates a CFNumber object from an integer :param integer: The integer to create the CFNumber for :return: A CFNumber """ integer_as_long = ffi.new('long *', integer) return CoreFoundation.CFNumberCreate( CoreFoundation.kCFAllocatorDefault, kCFNumberCFIndexType, integer_as_long )
def dump_dh_parameters(dh_parameters, encoding='pem'): """ Serializes an asn1crypto.algos.DHParameters object into a byte string :param dh_parameters: An asn1crypto.algos.DHParameters object :param encoding: A unicode string of "pem" or "der" :return: A byte string of the encoded DH parameters """ if encoding not in set(['pem', 'der']): raise ValueError(pretty_message( ''' encoding must be one of "pem", "der", not %s ''', repr(encoding) )) if not isinstance(dh_parameters, algos.DHParameters): raise TypeError(pretty_message( ''' dh_parameters must be an instance of asn1crypto.algos.DHParameters, not %s ''', type_name(dh_parameters) )) output = dh_parameters.dump() if encoding == 'pem': output = pem.armor('DH PARAMETERS', output) return output
def dump_public_key(public_key, encoding='pem'): """ Serializes a public key object into a byte string :param public_key: An oscrypto.asymmetric.PublicKey or asn1crypto.keys.PublicKeyInfo object :param encoding: A unicode string of "pem" or "der" :return: A byte string of the encoded public key """ if encoding not in set(['pem', 'der']): raise ValueError(pretty_message( ''' encoding must be one of "pem", "der", not %s ''', repr(encoding) )) is_oscrypto = isinstance(public_key, PublicKey) if not isinstance(public_key, keys.PublicKeyInfo) and not is_oscrypto: raise TypeError(pretty_message( ''' public_key must be an instance of oscrypto.asymmetric.PublicKey or asn1crypto.keys.PublicKeyInfo, not %s ''', type_name(public_key) )) if is_oscrypto: public_key = public_key.asn1 output = public_key.dump() if encoding == 'pem': output = pem.armor('PUBLIC KEY', output) return output
def dump_certificate(certificate, encoding='pem'): """ Serializes a certificate object into a byte string :param certificate: An oscrypto.asymmetric.Certificate or asn1crypto.x509.Certificate object :param encoding: A unicode string of "pem" or "der" :return: A byte string of the encoded certificate """ if encoding not in set(['pem', 'der']): raise ValueError(pretty_message( ''' encoding must be one of "pem", "der", not %s ''', repr(encoding) )) is_oscrypto = isinstance(certificate, Certificate) if not isinstance(certificate, x509.Certificate) and not is_oscrypto: raise TypeError(pretty_message( ''' certificate must be an instance of oscrypto.asymmetric.Certificate or asn1crypto.x509.Certificate, not %s ''', type_name(certificate) )) if is_oscrypto: certificate = certificate.asn1 output = certificate.dump() if encoding == 'pem': output = pem.armor('CERTIFICATE', output) return output
def dump_private_key(private_key, passphrase, encoding='pem', target_ms=200): """ Serializes a private key object into a byte string of the PKCS#8 format :param private_key: An oscrypto.asymmetric.PrivateKey or asn1crypto.keys.PrivateKeyInfo object :param passphrase: A unicode string of the passphrase to encrypt the private key with. A passphrase of None will result in no encryption. A blank string will result in a ValueError to help ensure that the lack of passphrase is intentional. :param encoding: A unicode string of "pem" or "der" :param target_ms: Use PBKDF2 with the number of iterations that takes about this many milliseconds on the current machine. :raises: ValueError - when a blank string is provided for the passphrase :return: A byte string of the encoded and encrypted public key """ if encoding not in set(['pem', 'der']): raise ValueError(pretty_message( ''' encoding must be one of "pem", "der", not %s ''', repr(encoding) )) if passphrase is not None: if not isinstance(passphrase, str_cls): raise TypeError(pretty_message( ''' passphrase must be a unicode string, not %s ''', type_name(passphrase) )) if passphrase == '': raise ValueError(pretty_message( ''' passphrase may not be a blank string - pass None to disable encryption ''' )) is_oscrypto = isinstance(private_key, PrivateKey) if not isinstance(private_key, keys.PrivateKeyInfo) and not is_oscrypto: raise TypeError(pretty_message( ''' private_key must be an instance of oscrypto.asymmetric.PrivateKey or asn1crypto.keys.PrivateKeyInfo, not %s ''', type_name(private_key) )) if is_oscrypto: private_key = private_key.asn1 output = private_key.dump() if passphrase is not None: cipher = 'aes256_cbc' key_length = 32 kdf_hmac = 'sha256' kdf_salt = rand_bytes(key_length) iterations = pbkdf2_iteration_calculator(kdf_hmac, key_length, target_ms=target_ms, quiet=True) # Need a bare minimum of 10,000 iterations for PBKDF2 as of 2015 if iterations < 10000: iterations = 10000 passphrase_bytes = passphrase.encode('utf-8') key = pbkdf2(kdf_hmac, passphrase_bytes, kdf_salt, iterations, key_length) iv, ciphertext = aes_cbc_pkcs7_encrypt(key, output, None) output = keys.EncryptedPrivateKeyInfo({ 'encryption_algorithm': { 'algorithm': 'pbes2', 'parameters': { 'key_derivation_func': { 'algorithm': 'pbkdf2', 'parameters': { 'salt': algos.Pbkdf2Salt( name='specified', value=kdf_salt ), 'iteration_count': iterations, 'prf': { 'algorithm': kdf_hmac, 'parameters': core.Null() } } }, 'encryption_scheme': { 'algorithm': cipher, 'parameters': iv } } }, 'encrypted_data': ciphertext }).dump() if encoding == 'pem': if passphrase is None: object_type = 'PRIVATE KEY' else: object_type = 'ENCRYPTED PRIVATE KEY' output = pem.armor(object_type, output) return output
def dump_openssl_private_key(private_key, passphrase): """ Serializes a private key object into a byte string of the PEM formats used by OpenSSL. The format chosen will depend on the type of private key - RSA, DSA or EC. Do not use this method unless you really must interact with a system that does not support PKCS#8 private keys. The encryption provided by PKCS#8 is far superior to the OpenSSL formats. This is due to the fact that the OpenSSL formats don't stretch the passphrase, making it very easy to brute-force. :param private_key: An oscrypto.asymmetric.PrivateKey or asn1crypto.keys.PrivateKeyInfo object :param passphrase: A unicode string of the passphrase to encrypt the private key with. A passphrase of None will result in no encryption. A blank string will result in a ValueError to help ensure that the lack of passphrase is intentional. :raises: ValueError - when a blank string is provided for the passphrase :return: A byte string of the encoded and encrypted public key """ if passphrase is not None: if not isinstance(passphrase, str_cls): raise TypeError(pretty_message( ''' passphrase must be a unicode string, not %s ''', type_name(passphrase) )) if passphrase == '': raise ValueError(pretty_message( ''' passphrase may not be a blank string - pass None to disable encryption ''' )) is_oscrypto = isinstance(private_key, PrivateKey) if not isinstance(private_key, keys.PrivateKeyInfo) and not is_oscrypto: raise TypeError(pretty_message( ''' private_key must be an instance of oscrypto.asymmetric.PrivateKey or asn1crypto.keys.PrivateKeyInfo, not %s ''', type_name(private_key) )) if is_oscrypto: private_key = private_key.asn1 output = private_key.unwrap().dump() headers = None if passphrase is not None: iv = rand_bytes(16) headers = OrderedDict() headers['Proc-Type'] = '4,ENCRYPTED' headers['DEK-Info'] = 'AES-128-CBC,%s' % binascii.hexlify(iv).decode('ascii') key_length = 16 passphrase_bytes = passphrase.encode('utf-8') key = hashlib.md5(passphrase_bytes + iv[0:8]).digest() while key_length > len(key): key += hashlib.md5(key + passphrase_bytes + iv[0:8]).digest() key = key[0:key_length] iv, output = aes_cbc_pkcs7_encrypt(key, output, iv) if private_key.algorithm == 'ec': object_type = 'EC PRIVATE KEY' elif private_key.algorithm == 'rsa': object_type = 'RSA PRIVATE KEY' elif private_key.algorithm == 'dsa': object_type = 'DSA PRIVATE KEY' return pem.armor(object_type, output, headers=headers)
def handle_sec_error(error, exception_class=None): """ Checks a Security OSStatus error code and throws an exception if there is an error to report :param error: An OSStatus :param exception_class: The exception class to use for the exception if an error occurred :raises: OSError - when the OSStatus contains an error """ if error == 0: return if error in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]): raise TLSDisconnectError('The remote end closed the connection') if error == SecurityConst.errSSLClosedGraceful: raise TLSGracefulDisconnectError('The remote end closed the connection') cf_error_string = Security.SecCopyErrorMessageString(error, null()) output = CFHelpers.cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == '': output = 'OSStatus %s' % error if exception_class is None: exception_class = OSError raise exception_class(output)
def _get_func_info(docstring, def_lineno, code_lines, prefix): """ Extracts the function signature and description of a Python function :param docstring: A unicode string of the docstring for the function :param def_lineno: An integer line number that function was defined on :param code_lines: A list of unicode string lines from the source file the function was defined in :param prefix: A prefix to prepend to all output lines :return: A 2-element tuple: - [0] A unicode string of the function signature with a docstring of parameter info - [1] A markdown snippet of the function description """ def_index = def_lineno - 1 definition = code_lines[def_index] definition = definition.rstrip() while not definition.endswith(':'): def_index += 1 definition += '\n' + code_lines[def_index].rstrip() definition = textwrap.dedent(definition).rstrip(':') definition = definition.replace('\n', '\n' + prefix) description = '' found_colon = False params = '' for line in docstring.splitlines(): if line and line[0] == ':': found_colon = True if not found_colon: if description: description += '\n' description += line else: if params: params += '\n' params += line description = description.strip() description_md = '' if description: description_md = "%s%s" % (prefix, description.replace('\n', '\n' + prefix)) description_md = re.sub('\n>(\\s+)\n', '\n>\n', description_md) params = params.strip() if params: definition += (':\n%s """\n%s ' % (prefix, prefix)) definition += params.replace('\n', '\n%s ' % prefix) definition += ('\n%s """' % prefix) definition = re.sub('\n>(\\s+)\n', '\n>\n', definition) for search, replace in definition_replacements.items(): definition = definition.replace(search, replace) return (definition, description_md)
def _find_sections(md_ast, sections, last, last_class, total_lines=None): """ Walks through a CommonMark AST to find section headers that delineate content that should be updated by this script :param md_ast: The AST of the markdown document :param sections: A dict to store the start and end lines of a section. The key will be a two-element tuple of the section type ("class", "function", "method" or "attribute") and identifier. The values are a two-element tuple of the start and end line number in the markdown document of the section. :param last: A dict containing information about the last section header seen. Includes the keys "type_name", "identifier", "start_line". :param last_class: A unicode string of the name of the last class found - used when processing methods and attributes. :param total_lines: An integer of the total number of lines in the markdown document - used to work around a bug in the API of the Python port of CommonMark """ def child_walker(node): for child, entering in node.walker(): if child == node: continue yield child, entering for child, entering in child_walker(md_ast): if child.t == 'heading': start_line = child.sourcepos[0][0] if child.level == 2: if last: sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1) last.clear() if child.level in set([3, 5]): heading_elements = [] for heading_child, _ in child_walker(child): heading_elements.append(heading_child) if len(heading_elements) != 2: continue first = heading_elements[0] second = heading_elements[1] if first.t != 'code': continue if second.t != 'text': continue type_name = second.literal.strip() identifier = first.literal.strip().replace('()', '').lstrip('.') if last: sections[(last['type_name'], last['identifier'])] = (last['start_line'], start_line - 1) last.clear() if type_name == 'function': if child.level != 3: continue if type_name == 'class': if child.level != 3: continue last_class.append(identifier) if type_name in set(['method', 'attribute']): if child.level != 5: continue identifier = last_class[-1] + '.' + identifier last.update({ 'type_name': type_name, 'identifier': identifier, 'start_line': start_line, }) elif child.t == 'block_quote': find_sections(child, sections, last, last_class) if last: sections[(last['type_name'], last['identifier'])] = (last['start_line'], total_lines)
def walk_ast(node, code_lines, sections, md_chunks): """ A callback used to walk the Python AST looking for classes, functions, methods and attributes. Generates chunks of markdown markup to replace the existing content. :param node: An _ast module node object :param code_lines: A list of unicode strings - the source lines of the Python file :param sections: A dict of markdown document sections that need to be updated. The key will be a two-element tuple of the section type ("class", "function", "method" or "attribute") and identifier. The values are a two-element tuple of the start and end line number in the markdown document of the section. :param md_chunks: A dict with keys from the sections param and the values being a unicode string containing a chunk of markdown markup. """ if isinstance(node, _ast.FunctionDef): key = ('function', node.name) if key not in sections: return docstring = ast.get_docstring(node) def_lineno = node.lineno + len(node.decorator_list) definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> ') md_chunk = textwrap.dedent(""" ### `%s()` function > ```python > %s > ``` > %s """).strip() % ( node.name, definition, description_md ) + "\n" md_chunks[key] = md_chunk.replace('>\n\n', '') elif isinstance(node, _ast.ClassDef): if ('class', node.name) not in sections: return for subnode in node.body: if isinstance(subnode, _ast.FunctionDef): node_id = node.name + '.' + subnode.name method_key = ('method', node_id) is_method = method_key in sections attribute_key = ('attribute', node_id) is_attribute = attribute_key in sections is_constructor = subnode.name == '__init__' if not is_constructor and not is_attribute and not is_method: continue docstring = ast.get_docstring(subnode) def_lineno = subnode.lineno + len(subnode.decorator_list) if not docstring: continue if is_method or is_constructor: definition, description_md = _get_func_info(docstring, def_lineno, code_lines, '> > ') if is_constructor: key = ('class', node.name) class_docstring = ast.get_docstring(node) or '' class_description = textwrap.dedent(class_docstring).strip() if class_description: class_description_md = "> %s\n>" % (class_description.replace("\n", "\n> ")) else: class_description_md = '' md_chunk = textwrap.dedent(""" ### `%s()` class %s > ##### constructor > > > ```python > > %s > > ``` > > %s """).strip() % ( node.name, class_description_md, definition, description_md ) md_chunk = md_chunk.replace('\n\n\n', '\n\n') else: key = method_key md_chunk = textwrap.dedent(""" > > ##### `.%s()` method > > > ```python > > %s > > ``` > > %s """).strip() % ( subnode.name, definition, description_md ) if md_chunk[-5:] == '\n> >\n': md_chunk = md_chunk[0:-5] else: key = attribute_key description = textwrap.dedent(docstring).strip() description_md = "> > %s" % (description.replace("\n", "\n> > ")) md_chunk = textwrap.dedent(""" > > ##### `.%s` attribute > %s """).strip() % ( subnode.name, description_md ) md_chunks[key] = re.sub('[ \\t]+\n', '\n', md_chunk.rstrip()) elif isinstance(node, _ast.If): for subast in node.body: walk_ast(subast, code_lines, sections, md_chunks) for subast in node.orelse: walk_ast(subast, code_lines, sections, md_chunks)
def run(): """ Looks through the docs/ dir and parses each markdown document, looking for sections to update from Python docstrings. Looks for section headers in the format: - ### `ClassName()` class - ##### `.method_name()` method - ##### `.attribute_name` attribute - ### `function_name()` function The markdown content following these section headers up until the next section header will be replaced by new markdown generated from the Python docstrings of the associated source files. By default maps docs/{name}.md to {modulename}/{name}.py. Allows for custom mapping via the md_source_map variable. """ print('Updating API docs...') md_files = [] for root, _, filenames in os.walk(os.path.join(package_root, 'docs')): for filename in filenames: if not filename.endswith('.md'): continue md_files.append(os.path.join(root, filename)) parser = CommonMark.Parser() for md_file in md_files: md_file_relative = md_file[len(package_root) + 1:] if md_file_relative in md_source_map: py_files = md_source_map[md_file_relative] py_paths = [os.path.join(package_root, py_file) for py_file in py_files] else: py_files = [os.path.basename(md_file).replace('.md', '.py')] py_paths = [os.path.join(package_root, package_name, py_files[0])] if not os.path.exists(py_paths[0]): continue with open(md_file, 'rb') as f: markdown = f.read().decode('utf-8') original_markdown = markdown md_lines = list(markdown.splitlines()) md_ast = parser.parse(markdown) last_class = [] last = {} sections = OrderedDict() find_sections(md_ast, sections, last, last_class, markdown.count("\n") + 1) md_chunks = {} for index, py_file in enumerate(py_files): py_path = py_paths[index] with open(os.path.join(py_path), 'rb') as f: code = f.read().decode('utf-8') module_ast = ast.parse(code, filename=py_file) code_lines = list(code.splitlines()) for node in ast.iter_child_nodes(module_ast): walk_ast(node, code_lines, sections, md_chunks) added_lines = 0 def _replace_md(key, sections, md_chunk, md_lines, added_lines): start, end = sections[key] start -= 1 start += added_lines end += added_lines new_lines = md_chunk.split('\n') added_lines += len(new_lines) - (end - start) # Ensure a newline above each class header if start > 0 and md_lines[start][0:4] == '### ' and md_lines[start - 1][0:1] == '>': added_lines += 1 new_lines.insert(0, '') md_lines[start:end] = new_lines return added_lines for key in sections: if key not in md_chunks: raise ValueError('No documentation found for %s' % key[1]) added_lines = _replace_md(key, sections, md_chunks[key], md_lines, added_lines) markdown = '\n'.join(md_lines).strip() + '\n' if original_markdown != markdown: with open(md_file, 'wb') as f: f.write(markdown.encode('utf-8'))
def ec_generate_pair(curve): """ Generates a EC public/private key pair :param curve: A unicode string. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type :return: A 2-element tuple of (asn1crypto.keys.PublicKeyInfo, asn1crypto.keys.PrivateKeyInfo) """ if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s ''', repr(curve) )) curve_num_bytes = CURVE_BYTES[curve] curve_base_point = { 'secp256r1': SECP256R1_BASE_POINT, 'secp384r1': SECP384R1_BASE_POINT, 'secp521r1': SECP521R1_BASE_POINT, }[curve] while True: private_key_bytes = rand_bytes(curve_num_bytes) private_key_int = int_from_bytes(private_key_bytes, signed=False) if private_key_int > 0 and private_key_int < curve_base_point.order: break private_key_info = keys.PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': keys.PrivateKeyAlgorithm({ 'algorithm': 'ec', 'parameters': keys.ECDomainParameters( name='named', value=curve ) }), 'private_key': keys.ECPrivateKey({ 'version': 'ecPrivkeyVer1', 'private_key': private_key_int }), }) private_key_info['private_key'].parsed['public_key'] = private_key_info.public_key public_key_info = private_key_info.public_key_info return (public_key_info, private_key_info)
def ecdsa_sign(private_key, data, hash_algorithm): """ Generates an ECDSA signature in pure Python (thus slow) :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not hasattr(private_key, 'asn1') or not isinstance(private_key.asn1, keys.PrivateKeyInfo): raise TypeError(pretty_message( ''' private_key must be an instance of the oscrypto.asymmetric.PrivateKey class, not %s ''', type_name(private_key) )) curve_name = private_key.curve if curve_name not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' private_key does not use one of the named curves secp256r1, secp384r1 or secp521r1 ''' )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) hash_func = getattr(hashlib, hash_algorithm) ec_private_key = private_key.asn1['private_key'].parsed private_key_bytes = ec_private_key['private_key'].contents private_key_int = ec_private_key['private_key'].native curve_num_bytes = CURVE_BYTES[curve_name] curve_base_point = { 'secp256r1': SECP256R1_BASE_POINT, 'secp384r1': SECP384R1_BASE_POINT, 'secp521r1': SECP521R1_BASE_POINT, }[curve_name] n = curve_base_point.order # RFC 6979 section 3.2 # a. digest = hash_func(data).digest() hash_length = len(digest) h = int_from_bytes(digest, signed=False) % n # b. V = b'\x01' * hash_length # c. K = b'\x00' * hash_length # d. K = hmac.new(K, V + b'\x00' + private_key_bytes + digest, hash_func).digest() # e. V = hmac.new(K, V, hash_func).digest() # f. K = hmac.new(K, V + b'\x01' + private_key_bytes + digest, hash_func).digest() # g. V = hmac.new(K, V, hash_func).digest() # h. r = 0 s = 0 while True: # h. 1 T = b'' # h. 2 while len(T) < curve_num_bytes: V = hmac.new(K, V, hash_func).digest() T += V # h. 3 k = int_from_bytes(T[0:curve_num_bytes], signed=False) if k == 0 or k >= n: continue # Calculate the signature in the loop in case we need a new k r = (curve_base_point * k).x % n if r == 0: continue s = (inverse_mod(k, n) * (h + (private_key_int * r) % n)) % n if s == 0: continue break return DSASignature({'r': r, 's': s}).dump()
def ecdsa_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an ECDSA signature in pure Python (thus slow) :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ has_asn1 = hasattr(certificate_or_public_key, 'asn1') if not has_asn1 or not isinstance(certificate_or_public_key.asn1, (keys.PublicKeyInfo, Certificate)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the oscrypto.asymmetric.PublicKey or oscrypto.asymmetric.Certificate classes, not %s ''', type_name(certificate_or_public_key) )) curve_name = certificate_or_public_key.curve if curve_name not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' certificate_or_public_key does not use one of the named curves secp256r1, secp384r1 or secp521r1 ''' )) if not isinstance(signature, byte_cls): raise TypeError(pretty_message( ''' signature must be a byte string, not %s ''', type_name(signature) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if hash_algorithm not in set(['sha1', 'sha224', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha224", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) asn1 = certificate_or_public_key.asn1 if isinstance(asn1, Certificate): asn1 = asn1.public_key curve_base_point = { 'secp256r1': SECP256R1_BASE_POINT, 'secp384r1': SECP384R1_BASE_POINT, 'secp521r1': SECP521R1_BASE_POINT, }[curve_name] x, y = asn1['public_key'].to_coords() n = curve_base_point.order # Validates that the point is valid public_key_point = PrimePoint(curve_base_point.curve, x, y, n) try: signature = DSASignature.load(signature) r = signature['r'].native s = signature['s'].native except (ValueError): raise SignatureError('Signature is invalid') invalid = 0 # Check r is valid invalid |= r < 1 invalid |= r >= n # Check s is valid invalid |= s < 1 invalid |= s >= n if invalid: raise SignatureError('Signature is invalid') hash_func = getattr(hashlib, hash_algorithm) digest = hash_func(data).digest() z = int_from_bytes(digest, signed=False) % n w = inverse_mod(s, n) u1 = (z * w) % n u2 = (r * w) % n hash_point = (curve_base_point * u1) + (public_key_point * u2) if r != (hash_point.x % n): raise SignatureError('Signature is invalid')
def system_path(): """ Tries to find a CA certs bundle in common locations :raises: OSError - when no valid CA certs bundle was found on the filesystem :return: The full filesystem path to a CA certs bundle file """ ca_path = None # Common CA cert paths paths = [ '/usr/lib/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-bundle.crt', '/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/ca-bundle.pem', '/usr/local/share/certs/ca-root-nss.crt', '/etc/ssl/cert.pem' ] # First try SSL_CERT_FILE if 'SSL_CERT_FILE' in os.environ: paths.insert(0, os.environ['SSL_CERT_FILE']) for path in paths: if os.path.exists(path) and os.path.getsize(path) > 0: ca_path = path break if not ca_path: raise OSError(pretty_message( ''' Unable to find a CA certs bundle in common locations - try setting the SSL_CERT_FILE environmental variable ''' )) return ca_path
def extract_from_system(cert_callback=None, callback_only_on_failure=False): """ Extracts trusted CA certs from the system CA cert bundle :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :param callback_only_on_failure: A boolean - if the callback should only be called when a certificate is not exported. :return: A list of 3-element tuples: - 0: a byte string of a DER-encoded certificate - 1: a set of unicode strings that are OIDs of purposes to trust the certificate for - 2: a set of unicode strings that are OIDs of purposes to reject the certificate for """ all_purposes = '2.5.29.37.0' ca_path = system_path() output = [] with open(ca_path, 'rb') as f: for armor_type, _, cert_bytes in unarmor(f.read(), multiple=True): # Without more info, a certificate is trusted for all purposes if armor_type == 'CERTIFICATE': if cert_callback: cert_callback(Certificate.load(cert_bytes), None) output.append((cert_bytes, set(), set())) # The OpenSSL TRUSTED CERTIFICATE construct adds OIDs for trusted # and rejected purposes, so we extract that info. elif armor_type == 'TRUSTED CERTIFICATE': cert, aux = TrustedCertificate.load(cert_bytes) reject_all = False trust_oids = set() reject_oids = set() for purpose in aux['trust']: if purpose.dotted == all_purposes: trust_oids = set([purpose.dotted]) break trust_oids.add(purpose.dotted) for purpose in aux['reject']: if purpose.dotted == all_purposes: reject_all = True break reject_oids.add(purpose.dotted) if reject_all: if cert_callback: cert_callback(cert, 'explicitly distrusted') continue if cert_callback and not callback_only_on_failure: cert_callback(cert, None) output.append((cert.dump(), trust_oids, reject_oids)) return output
def extract_from_system(cert_callback=None, callback_only_on_failure=False): """ Extracts trusted CA certificates from the Windows certificate store :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :param callback_only_on_failure: A boolean - if the callback should only be called when a certificate is not exported. :raises: OSError - when an error is returned by the OS crypto library :return: A list of 3-element tuples: - 0: a byte string of a DER-encoded certificate - 1: a set of unicode strings that are OIDs of purposes to trust the certificate for - 2: a set of unicode strings that are OIDs of purposes to reject the certificate for """ certificates = {} processed = {} now = datetime.datetime.utcnow() for store in ["ROOT", "CA"]: store_handle = crypt32.CertOpenSystemStoreW(null(), store) handle_error(store_handle) context_pointer = null() while True: context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, context_pointer) if is_null(context_pointer): break context = unwrap(context_pointer) trust_all = False data = None digest = None if context.dwCertEncodingType != Crypt32Const.X509_ASN_ENCODING: continue data = bytes_from_buffer(context.pbCertEncoded, int(context.cbCertEncoded)) digest = hashlib.sha1(data).digest() if digest in processed: continue processed[digest] = True cert_info = unwrap(context.pCertInfo) not_before_seconds = _convert_filetime_to_timestamp(cert_info.NotBefore) try: not_before = datetime.datetime.fromtimestamp(not_before_seconds) if not_before > now: if cert_callback: cert_callback(Certificate.load(data), 'not yet valid') continue except (ValueError, OSError): # If there is an error converting the not before timestamp, # it is almost certainly because it is from too long ago, # which means the cert is definitely valid by now. pass not_after_seconds = _convert_filetime_to_timestamp(cert_info.NotAfter) try: not_after = datetime.datetime.fromtimestamp(not_after_seconds) if not_after < now: if cert_callback: cert_callback(Certificate.load(data), 'no longer valid') continue except (ValueError, OSError) as e: # The only reason we would get an exception here is if the # expiration time is so far in the future that it can't be # used as a timestamp, or it is before 0. If it is very far # in the future, the cert is still valid, so we only raise # an exception if the timestamp is less than zero. if not_after_seconds < 0: message = e.args[0] + ' - ' + str_cls(not_after_seconds) e.args = (message,) + e.args[1:] raise e trust_oids = set() reject_oids = set() # Here we grab the extended key usage properties that Windows # layers on top of the extended key usage extension that is # part of the certificate itself. For highest security, users # should only use certificates for the intersection of the two # lists of purposes. However, many seen to treat the OS trust # list as an override. to_read = new(crypt32, 'DWORD *', 0) res = crypt32.CertGetEnhancedKeyUsage( context_pointer, Crypt32Const.CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, null(), to_read ) # Per the Microsoft documentation, if CRYPT_E_NOT_FOUND is returned # from get_error(), it means the certificate is valid for all purposes error_code, _ = get_error() if not res and error_code != Crypt32Const.CRYPT_E_NOT_FOUND: handle_error(res) if error_code == Crypt32Const.CRYPT_E_NOT_FOUND: trust_all = True else: usage_buffer = buffer_from_bytes(deref(to_read)) res = crypt32.CertGetEnhancedKeyUsage( context_pointer, Crypt32Const.CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, cast(crypt32, 'CERT_ENHKEY_USAGE *', usage_buffer), to_read ) handle_error(res) key_usage_pointer = struct_from_buffer(crypt32, 'CERT_ENHKEY_USAGE', usage_buffer) key_usage = unwrap(key_usage_pointer) # Having no enhanced usage properties means a cert is distrusted if key_usage.cUsageIdentifier == 0: if cert_callback: cert_callback(Certificate.load(data), 'explicitly distrusted') continue oids = array_from_pointer( crypt32, 'LPCSTR', key_usage.rgpszUsageIdentifier, key_usage.cUsageIdentifier ) for oid in oids: trust_oids.add(oid.decode('ascii')) cert = None # If the certificate is not under blanket trust, we have to # determine what purposes it is rejected for by diffing the # set of OIDs from the certificate with the OIDs that are # trusted. if not trust_all: cert = Certificate.load(data) if cert.extended_key_usage_value: for cert_oid in cert.extended_key_usage_value: oid = cert_oid.dotted if oid not in trust_oids: reject_oids.add(oid) if cert_callback and not callback_only_on_failure: if cert is None: cert = Certificate.load(data) cert_callback(cert, None) certificates[digest] = (data, trust_oids, reject_oids) result = crypt32.CertCloseStore(store_handle, 0) handle_error(result) store_handle = None return certificates.values()
def _convert_filetime_to_timestamp(filetime): """ Windows returns times as 64-bit unsigned longs that are the number of hundreds of nanoseconds since Jan 1 1601. This converts it to a datetime object. :param filetime: A FILETIME struct object :return: An integer unix timestamp """ hundreds_nano_seconds = struct.unpack( b'>Q', struct.pack( b'>LL', filetime.dwHighDateTime, filetime.dwLowDateTime ) )[0] seconds_since_1601 = hundreds_nano_seconds / 10000000 return seconds_since_1601 - 11644473600
def extract_chain(server_handshake_bytes): """ Extracts the X.509 certificates from the server handshake bytes for use when debugging :param server_handshake_bytes: A byte string of the handshake data received from the server :return: A list of asn1crypto.x509.Certificate objects """ output = [] chain_bytes = None for record_type, _, record_data in parse_tls_records(server_handshake_bytes): if record_type != b'\x16': continue for message_type, message_data in parse_handshake_messages(record_data): if message_type == b'\x0b': chain_bytes = message_data break if chain_bytes: break if chain_bytes: # The first 3 bytes are the cert chain length pointer = 3 while pointer < len(chain_bytes): cert_length = int_from_bytes(chain_bytes[pointer:pointer + 3]) cert_start = pointer + 3 cert_end = cert_start + cert_length pointer = cert_end cert_bytes = chain_bytes[cert_start:cert_end] output.append(Certificate.load(cert_bytes)) return output
def detect_client_auth_request(server_handshake_bytes): """ Determines if a CertificateRequest message is sent from the server asking the client for a certificate :param server_handshake_bytes: A byte string of the handshake data received from the server :return: A boolean - if a client certificate request was found """ for record_type, _, record_data in parse_tls_records(server_handshake_bytes): if record_type != b'\x16': continue for message_type, message_data in parse_handshake_messages(record_data): if message_type == b'\x0d': return True return False
def get_dh_params_length(server_handshake_bytes): """ Determines the length of the DH params from the ServerKeyExchange :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None or an integer of the bit size of the DH parameters """ output = None dh_params_bytes = None for record_type, _, record_data in parse_tls_records(server_handshake_bytes): if record_type != b'\x16': continue for message_type, message_data in parse_handshake_messages(record_data): if message_type == b'\x0c': dh_params_bytes = message_data break if dh_params_bytes: break if dh_params_bytes: output = int_from_bytes(dh_params_bytes[0:2]) * 8 return output
def parse_alert(server_handshake_bytes): """ Parses the handshake for protocol alerts :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None or an 2-element tuple of integers: 0: 1 (warning) or 2 (fatal) 1: The alert description (see https://tools.ietf.org/html/rfc5246#section-7.2) """ for record_type, _, record_data in parse_tls_records(server_handshake_bytes): if record_type != b'\x15': continue if len(record_data) != 2: return None return (int_from_bytes(record_data[0:1]), int_from_bytes(record_data[1:2])) return None
def parse_session_info(server_handshake_bytes, client_handshake_bytes): """ Parse the TLS handshake from the client to the server to extract information including the cipher suite selected, if compression is enabled, the session id and if a new or reused session ticket exists. :param server_handshake_bytes: A byte string of the handshake data received from the server :param client_handshake_bytes: A byte string of the handshake data sent to the server :return: A dict with the following keys: - "protocol": unicode string - "cipher_suite": unicode string - "compression": boolean - "session_id": "new", "reused" or None - "session_ticket: "new", "reused" or None """ protocol = None cipher_suite = None compression = False session_id = None session_ticket = None server_session_id = None client_session_id = None for record_type, _, record_data in parse_tls_records(server_handshake_bytes): if record_type != b'\x16': continue for message_type, message_data in parse_handshake_messages(record_data): # Ensure we are working with a ServerHello message if message_type != b'\x02': continue protocol = { b'\x03\x00': "SSLv3", b'\x03\x01': "TLSv1", b'\x03\x02': "TLSv1.1", b'\x03\x03': "TLSv1.2", b'\x03\x04': "TLSv1.3", }[message_data[0:2]] session_id_length = int_from_bytes(message_data[34:35]) if session_id_length > 0: server_session_id = message_data[35:35 + session_id_length] cipher_suite_start = 35 + session_id_length cipher_suite_bytes = message_data[cipher_suite_start:cipher_suite_start + 2] cipher_suite = CIPHER_SUITE_MAP[cipher_suite_bytes] compression_start = cipher_suite_start + 2 compression = message_data[compression_start:compression_start + 1] != b'\x00' extensions_length_start = compression_start + 1 extensions_data = message_data[extensions_length_start:] for extension_type, extension_data in _parse_hello_extensions(extensions_data): if extension_type == 35: session_ticket = "new" break break for record_type, _, record_data in parse_tls_records(client_handshake_bytes): if record_type != b'\x16': continue for message_type, message_data in parse_handshake_messages(record_data): # Ensure we are working with a ClientHello message if message_type != b'\x01': continue session_id_length = int_from_bytes(message_data[34:35]) if session_id_length > 0: client_session_id = message_data[35:35 + session_id_length] cipher_suite_start = 35 + session_id_length cipher_suite_length = int_from_bytes(message_data[cipher_suite_start:cipher_suite_start + 2]) compression_start = cipher_suite_start + 2 + cipher_suite_length compression_length = int_from_bytes(message_data[compression_start:compression_start + 1]) # On subsequent requests, the session ticket will only be seen # in the ClientHello message if server_session_id is None and session_ticket is None: extensions_length_start = compression_start + 1 + compression_length extensions_data = message_data[extensions_length_start:] for extension_type, extension_data in _parse_hello_extensions(extensions_data): if extension_type == 35: session_ticket = "reused" break break if server_session_id is not None: if client_session_id is None: session_id = "new" else: if client_session_id != server_session_id: session_id = "new" else: session_id = "reused" return { "protocol": protocol, "cipher_suite": cipher_suite, "compression": compression, "session_id": session_id, "session_ticket": session_ticket, }
def parse_tls_records(data): """ Creates a generator returning tuples of information about each record in a byte string of data from a TLS client or server. Stops as soon as it find a ChangeCipherSpec message since all data from then on is encrypted. :param data: A byte string of TLS records :return: A generator that yields 3-element tuples: [0] Byte string of record type [1] Byte string of protocol version [2] Byte string of record data """ pointer = 0 data_len = len(data) while pointer < data_len: # Don't try to parse any more once the ChangeCipherSpec is found if data[pointer:pointer + 1] == b'\x14': break length = int_from_bytes(data[pointer + 3:pointer + 5]) yield ( data[pointer:pointer + 1], data[pointer + 1:pointer + 3], data[pointer + 5:pointer + 5 + length] ) pointer += 5 + length
def parse_handshake_messages(data): """ Creates a generator returning tuples of information about each message in a byte string of data from a TLS handshake record :param data: A byte string of a TLS handshake record data :return: A generator that yields 2-element tuples: [0] Byte string of message type [1] Byte string of message data """ pointer = 0 data_len = len(data) while pointer < data_len: length = int_from_bytes(data[pointer + 1:pointer + 4]) yield ( data[pointer:pointer + 1], data[pointer + 4:pointer + 4 + length] ) pointer += 4 + length
def _parse_hello_extensions(data): """ Creates a generator returning tuples of information about each extension from a byte string of extension data contained in a ServerHello ores ClientHello message :param data: A byte string of a extension data from a TLS ServerHello or ClientHello message :return: A generator that yields 2-element tuples: [0] Byte string of extension type [1] Byte string of extension data """ if data == b'': return extentions_length = int_from_bytes(data[0:2]) extensions_start = 2 extensions_end = 2 + extentions_length pointer = extensions_start while pointer < extensions_end: extension_type = int_from_bytes(data[pointer:pointer + 2]) extension_length = int_from_bytes(data[pointer + 2:pointer + 4]) yield ( extension_type, data[pointer + 4:pointer + 4 + extension_length] ) pointer += 4 + extension_length