Search is not available for this dataset
text
stringlengths
75
104k
def raise_hostname(certificate, hostname): """ Raises a TLSVerificationError due to a hostname mismatch :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ is_ip = re.match('^\\d+\\.\\d+\\.\\d+\\.\\d+$', hostname) or hostname.find(':') != -1 if is_ip: hostname_type = 'IP address %s' % hostname else: hostname_type = 'domain name %s' % hostname message = 'Server certificate verification failed - %s does not match' % hostname_type valid_ips = ', '.join(certificate.valid_ips) valid_domains = ', '.join(certificate.valid_domains) if valid_domains: message += ' valid domains: %s' % valid_domains if valid_domains and valid_ips: message += ' or' if valid_ips: message += ' valid IP addresses: %s' % valid_ips raise TLSVerificationError(message, certificate)
def raise_expired_not_yet_valid(certificate): """ Raises a TLSVerificationError due to certificate being expired, or not yet being valid :param certificate: An asn1crypto.x509.Certificate object :raises: TLSVerificationError """ validity = certificate['tbs_certificate']['validity'] not_after = validity['not_after'].native not_before = validity['not_before'].native now = datetime.now(timezone.utc) if not_before > now: formatted_before = not_before.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate not valid until %s' % formatted_before elif not_after < now: formatted_after = not_after.strftime('%Y-%m-%d %H:%M:%SZ') message = 'Server certificate verification failed - certificate expired %s' % formatted_after raise TLSVerificationError(message, certificate)
def detect_other_protocol(server_handshake_bytes): """ Looks at the server handshake bytes to try and detect a different protocol :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None, or a unicode string of "ftp", "http", "imap", "pop3", "smtp" """ if server_handshake_bytes[0:5] == b'HTTP/': return 'HTTP' if server_handshake_bytes[0:4] == b'220 ': if re.match(b'^[^\r\n]*ftp', server_handshake_bytes, re.I): return 'FTP' else: return 'SMTP' if server_handshake_bytes[0:4] == b'220-': return 'FTP' if server_handshake_bytes[0:4] == b'+OK ': return 'POP3' if server_handshake_bytes[0:4] == b'* OK' or server_handshake_bytes[0:9] == b'* PREAUTH': return 'IMAP' return None
def constant_compare(a, b): """ Compares two byte strings in constant time to see if they are equal :param a: The first byte string :param b: The second byte string :return: A boolean if the two byte strings are equal """ if not isinstance(a, byte_cls): raise TypeError(pretty_message( ''' a must be a byte string, not %s ''', type_name(a) )) if not isinstance(b, byte_cls): raise TypeError(pretty_message( ''' b must be a byte string, not %s ''', type_name(b) )) if len(a) != len(b): return False if sys.version_info < (3,): a = [ord(char) for char in a] b = [ord(char) for char in b] result = 0 for x, y in zip(a, b): result |= x ^ y return result == 0
def _try_decode(byte_string): """ Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string """ try: return str_cls(byte_string, _encoding) # If the "correct" encoding did not work, try some defaults, and then just # obliterate characters that we can't seen to decode properly except (UnicodeDecodeError): for encoding in _fallback_encodings: try: return str_cls(byte_string, encoding, errors='strict') except (UnicodeDecodeError): pass return str_cls(byte_string, errors='replace')
def _read_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually read the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type to write the data to :param data_length_pointer: A size_t pointer FFI type of the amount of data to read. Will be overwritten with the amount of data read on return. :return: An integer status code of the result - 0 for success """ self = None try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 bytes_requested = deref(data_length_pointer) timeout = socket.gettimeout() error = None data = b'' try: while len(data) < bytes_requested: # Python 2 on Travis CI seems to have issues with blocking on # recv() for longer than the socket timeout value, so we select if timeout is not None and timeout > 0.0: read_ready, _, _ = select.select([socket], [], [], timeout) if len(read_ready) == 0: raise socket_.error(errno.EAGAIN, 'timed out') chunk = socket.recv(bytes_requested - len(data)) data += chunk if chunk == b'': if len(data) == 0: if timeout is None: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort break except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if self and not self._done_handshake: # SecureTransport doesn't bother to check if the TLS record header # is valid before asking to read more data, which can result in # connection hangs. Here we do basic checks to get around the issue. if len(data) >= 3 and len(self._server_hello) == 0: # Check to ensure it is an alert or handshake first valid_record_type = data[0:1] in set([b'\x15', b'\x16']) # Check if the protocol version is SSL 3.0 or TLS 1.0-1.3 valid_protocol_version = data[1:3] in set([ b'\x03\x00', b'\x03\x01', b'\x03\x02', b'\x03\x03', b'\x03\x04' ]) if not valid_record_type or not valid_protocol_version: self._server_hello += data + _read_remaining(socket) return SecurityConst.errSSLProtocol self._server_hello += data write_to_buffer(data_buffer, data) pointer_set(data_length_pointer, len(data)) if len(data) != bytes_requested: return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: if self: self._exception = e return SecurityConst.errSSLClosedAbort
def _read_remaining(socket): """ Reads everything available from the socket - used for debugging when there is a protocol error :param socket: The socket to read from :return: A byte string of the remaining data """ output = b'' old_timeout = socket.gettimeout() try: socket.settimeout(0.0) output += socket.recv(8192) except (socket_.error): pass finally: socket.settimeout(old_timeout) return output
def _write_callback(connection_id, data_buffer, data_length_pointer): """ Callback called by Secure Transport to actually write to the socket :param connection_id: An integer identifing the connection :param data_buffer: A char pointer FFI type containing the data to write :param data_length_pointer: A size_t pointer FFI type of the amount of data to write. Will be overwritten with the amount of data actually written on return. :return: An integer status code of the result - 0 for success """ try: self = _connection_refs.get(connection_id) if not self: socket = _socket_refs.get(connection_id) else: socket = self._socket if not self and not socket: return 0 data_length = deref(data_length_pointer) data = bytes_from_buffer(data_buffer, data_length) if self and not self._done_handshake: self._client_hello += data error = None try: sent = socket.send(data) except (socket_.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedNoNotify return SecurityConst.errSSLClosedAbort if sent != data_length: pointer_set(data_length_pointer, sent) return SecurityConst.errSSLWouldBlock return 0 except (KeyboardInterrupt) as e: self._exception = e return SecurityConst.errSSLPeerUserCancelled
def _handshake(self): """ Perform an initial TLS handshake """ session_context = None ssl_policy_ref = None crl_search_ref = None crl_policy_ref = None ocsp_search_ref = None ocsp_policy_ref = None policy_array_ref = None try: if osx_version_info < (10, 8): session_context_pointer = new(Security, 'SSLContextRef *') result = Security.SSLNewContext(False, session_context_pointer) handle_sec_error(result) session_context = unwrap(session_context_pointer) else: session_context = Security.SSLCreateContext( null(), SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( session_context, _read_callback_pointer, _write_callback_pointer ) handle_sec_error(result) self._connection_id = id(self) % 2147483647 _connection_refs[self._connection_id] = self _socket_refs[self._connection_id] = self._socket result = Security.SSLSetConnection(session_context, self._connection_id) handle_sec_error(result) utf8_domain = self._hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( session_context, utf8_domain, len(utf8_domain) ) handle_sec_error(result) if osx_version_info >= (10, 10): disable_auto_validation = self._session._manual_validation or self._session._extra_trust_roots explicit_validation = (not self._session._manual_validation) and self._session._extra_trust_roots else: disable_auto_validation = True explicit_validation = not self._session._manual_validation # Ensure requested protocol support is set for the session if osx_version_info < (10, 8): for protocol in ['SSLv2', 'SSLv3', 'TLSv1']: protocol_const = _PROTOCOL_STRING_CONST_MAP[protocol] enabled = protocol in self._session._protocols result = Security.SSLSetProtocolVersionEnabled( session_context, protocol_const, enabled ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetEnableCertVerify(session_context, False) handle_sec_error(result) else: protocol_consts = [_PROTOCOL_STRING_CONST_MAP[protocol] for protocol in self._session._protocols] min_protocol = min(protocol_consts) max_protocol = max(protocol_consts) result = Security.SSLSetProtocolVersionMin( session_context, min_protocol ) handle_sec_error(result) result = Security.SSLSetProtocolVersionMax( session_context, max_protocol ) handle_sec_error(result) if disable_auto_validation: result = Security.SSLSetSessionOption( session_context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) handle_sec_error(result) # Disable all sorts of bad cipher suites supported_ciphers_pointer = new(Security, 'size_t *') result = Security.SSLGetNumberSupportedCiphers(session_context, supported_ciphers_pointer) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) cipher_buffer = buffer_from_bytes(supported_ciphers * 4) supported_cipher_suites_pointer = cast(Security, 'uint32_t *', cipher_buffer) result = Security.SSLGetSupportedCiphers( session_context, supported_cipher_suites_pointer, supported_ciphers_pointer ) handle_sec_error(result) supported_ciphers = deref(supported_ciphers_pointer) supported_cipher_suites = array_from_pointer( Security, 'uint32_t', supported_cipher_suites_pointer, supported_ciphers ) good_ciphers = [] for supported_cipher_suite in supported_cipher_suites: cipher_suite = int_to_bytes(supported_cipher_suite, width=2) cipher_suite_name = CIPHER_SUITE_MAP.get(cipher_suite, cipher_suite) good_cipher = _cipher_blacklist_regex.search(cipher_suite_name) is None if good_cipher: good_ciphers.append(supported_cipher_suite) num_good_ciphers = len(good_ciphers) good_ciphers_array = new(Security, 'uint32_t[]', num_good_ciphers) array_set(good_ciphers_array, good_ciphers) good_ciphers_pointer = cast(Security, 'uint32_t *', good_ciphers_array) result = Security.SSLSetEnabledCiphers( session_context, good_ciphers_pointer, num_good_ciphers ) handle_sec_error(result) # Set a peer id from the session to allow for session reuse, the hostname # is appended to prevent a bug on OS X 10.7 where it tries to reuse a # connection even if the hostnames are different. peer_id = self._session._peer_id + self._hostname.encode('utf-8') result = Security.SSLSetPeerID(session_context, peer_id, len(peer_id)) handle_sec_error(result) handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) if self._exception is not None: exception = self._exception self._exception = None raise exception if osx_version_info < (10, 8) and osx_version_info >= (10, 7): do_validation = explicit_validation and handshake_result == 0 else: do_validation = explicit_validation and handshake_result == SecurityConst.errSSLServerAuthCompleted if do_validation: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) cf_string_hostname = CFHelpers.cf_string_from_unicode(self._hostname) ssl_policy_ref = Security.SecPolicyCreateSSL(True, cf_string_hostname) result = CoreFoundation.CFRelease(cf_string_hostname) handle_cf_error(result) # Create a new policy for OCSP checking to disable it ocsp_oid_pointer = struct(Security, 'CSSM_OID') ocsp_oid = unwrap(ocsp_oid_pointer) ocsp_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_OCSP) ocsp_oid.Data = cast(Security, 'char *', ocsp_oid_buffer) ocsp_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, ocsp_oid_pointer, null(), ocsp_search_ref_pointer ) handle_sec_error(result) ocsp_search_ref = unwrap(ocsp_search_ref_pointer) ocsp_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(ocsp_search_ref, ocsp_policy_ref_pointer) handle_sec_error(result) ocsp_policy_ref = unwrap(ocsp_policy_ref_pointer) ocsp_struct_pointer = struct(Security, 'CSSM_APPLE_TP_OCSP_OPTIONS') ocsp_struct = unwrap(ocsp_struct_pointer) ocsp_struct.Version = SecurityConst.CSSM_APPLE_TP_OCSP_OPTS_VERSION ocsp_struct.Flags = ( SecurityConst.CSSM_TP_ACTION_OCSP_DISABLE_NET | SecurityConst.CSSM_TP_ACTION_OCSP_CACHE_READ_DISABLE ) ocsp_struct_bytes = struct_bytes(ocsp_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(ocsp_struct_bytes) ocsp_struct_buffer = buffer_from_bytes(ocsp_struct_bytes) cssm_data.Data = cast(Security, 'char *', ocsp_struct_buffer) result = Security.SecPolicySetValue(ocsp_policy_ref, cssm_data_pointer) handle_sec_error(result) # Create a new policy for CRL checking to disable it crl_oid_pointer = struct(Security, 'CSSM_OID') crl_oid = unwrap(crl_oid_pointer) crl_oid.Length = len(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid_buffer = buffer_from_bytes(SecurityConst.APPLE_TP_REVOCATION_CRL) crl_oid.Data = cast(Security, 'char *', crl_oid_buffer) crl_search_ref_pointer = new(Security, 'SecPolicySearchRef *') result = Security.SecPolicySearchCreate( SecurityConst.CSSM_CERT_X_509v3, crl_oid_pointer, null(), crl_search_ref_pointer ) handle_sec_error(result) crl_search_ref = unwrap(crl_search_ref_pointer) crl_policy_ref_pointer = new(Security, 'SecPolicyRef *') result = Security.SecPolicySearchCopyNext(crl_search_ref, crl_policy_ref_pointer) handle_sec_error(result) crl_policy_ref = unwrap(crl_policy_ref_pointer) crl_struct_pointer = struct(Security, 'CSSM_APPLE_TP_CRL_OPTIONS') crl_struct = unwrap(crl_struct_pointer) crl_struct.Version = SecurityConst.CSSM_APPLE_TP_CRL_OPTS_VERSION crl_struct.CrlFlags = 0 crl_struct_bytes = struct_bytes(crl_struct_pointer) cssm_data_pointer = struct(Security, 'CSSM_DATA') cssm_data = unwrap(cssm_data_pointer) cssm_data.Length = len(crl_struct_bytes) crl_struct_buffer = buffer_from_bytes(crl_struct_bytes) cssm_data.Data = cast(Security, 'char *', crl_struct_buffer) result = Security.SecPolicySetValue(crl_policy_ref, cssm_data_pointer) handle_sec_error(result) policy_array_ref = CFHelpers.cf_array_from_list([ ssl_policy_ref, crl_policy_ref, ocsp_policy_ref ]) result = Security.SecTrustSetPolicies(trust_ref, policy_array_ref) handle_sec_error(result) if self._session._extra_trust_roots: ca_cert_refs = [] ca_certs = [] for cert in self._session._extra_trust_roots: ca_cert = load_certificate(cert) ca_certs.append(ca_cert) ca_cert_refs.append(ca_cert.sec_certificate_ref) result = Security.SecTrustSetAnchorCertificatesOnly(trust_ref, False) handle_sec_error(result) array_ref = CFHelpers.cf_array_from_list(ca_cert_refs) result = Security.SecTrustSetAnchorCertificates(trust_ref, array_ref) handle_sec_error(result) result_pointer = new(Security, 'SecTrustResultType *') result = Security.SecTrustEvaluate(trust_ref, result_pointer) handle_sec_error(result) trust_result_code = deref(result_pointer) invalid_chain_error_codes = set([ SecurityConst.kSecTrustResultProceed, SecurityConst.kSecTrustResultUnspecified ]) if trust_result_code not in invalid_chain_error_codes: handshake_result = SecurityConst.errSSLXCertChainInvalid else: handshake_result = Security.SSLHandshake(session_context) while handshake_result == SecurityConst.errSSLWouldBlock: handshake_result = Security.SSLHandshake(session_context) self._done_handshake = True handshake_error_codes = set([ SecurityConst.errSSLXCertChainInvalid, SecurityConst.errSSLCertExpired, SecurityConst.errSSLCertNotYetValid, SecurityConst.errSSLUnknownRootCert, SecurityConst.errSSLNoRootCert, SecurityConst.errSSLHostNameMismatch, SecurityConst.errSSLInternal, ]) # In testing, only errSSLXCertChainInvalid was ever returned for # all of these different situations, however we include the others # for completeness. To get the real reason we have to use the # certificate from the handshake and use the deprecated function # SecTrustGetCssmResultCode(). if handshake_result in handshake_error_codes: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) result_code_pointer = new(Security, 'OSStatus *') result = Security.SecTrustGetCssmResultCode(trust_ref, result_code_pointer) result_code = deref(result_code_pointer) chain = extract_chain(self._server_hello) self_signed = False revoked = False expired = False not_yet_valid = False no_issuer = False cert = None bad_hostname = False if chain: cert = chain[0] oscrypto_cert = load_certificate(cert) self_signed = oscrypto_cert.self_signed revoked = result_code == SecurityConst.CSSMERR_TP_CERT_REVOKED no_issuer = not self_signed and result_code == SecurityConst.CSSMERR_TP_NOT_TRUSTED expired = result_code == SecurityConst.CSSMERR_TP_CERT_EXPIRED not_yet_valid = result_code == SecurityConst.CSSMERR_TP_CERT_NOT_VALID_YET bad_hostname = result_code == SecurityConst.CSSMERR_APPLETP_HOSTNAME_MISMATCH # On macOS 10.12, some expired certificates return errSSLInternal if osx_version_info >= (10, 12): validity = cert['tbs_certificate']['validity'] not_before = validity['not_before'].chosen.native not_after = validity['not_after'].chosen.native utcnow = datetime.datetime.now(timezone.utc) expired = not_after < utcnow not_yet_valid = not_before > utcnow if chain and chain[0].hash_algo in set(['md5', 'md2']): raise_weak_signature(chain[0]) if revoked: raise_revoked(cert) if bad_hostname: raise_hostname(cert, self._hostname) elif expired or not_yet_valid: raise_expired_not_yet_valid(cert) elif no_issuer: raise_no_issuer(cert) elif self_signed: raise_self_signed(cert) if detect_client_auth_request(self._server_hello): raise_client_auth() raise_verification(cert) if handshake_result == SecurityConst.errSSLPeerHandshakeFail: if detect_client_auth_request(self._server_hello): raise_client_auth() raise_handshake() if handshake_result == SecurityConst.errSSLWeakPeerEphemeralDHKey: raise_dh_params() if handshake_result == SecurityConst.errSSLPeerProtocolVersion: raise_protocol_version() if handshake_result in set([SecurityConst.errSSLRecordOverflow, SecurityConst.errSSLProtocol]): self._server_hello += _read_remaining(self._socket) raise_protocol_error(self._server_hello) if handshake_result in set([SecurityConst.errSSLClosedNoNotify, SecurityConst.errSSLClosedAbort]): if not self._done_handshake: self._server_hello += _read_remaining(self._socket) if detect_other_protocol(self._server_hello): raise_protocol_error(self._server_hello) raise_disconnection() if osx_version_info < (10, 10): dh_params_length = get_dh_params_length(self._server_hello) if dh_params_length is not None and dh_params_length < 1024: raise_dh_params() would_block = handshake_result == SecurityConst.errSSLWouldBlock server_auth_complete = handshake_result == SecurityConst.errSSLServerAuthCompleted manual_validation = self._session._manual_validation and server_auth_complete if not would_block and not manual_validation: handle_sec_error(handshake_result, TLSError) self._session_context = session_context protocol_const_pointer = new(Security, 'SSLProtocol *') result = Security.SSLGetNegotiatedProtocolVersion( session_context, protocol_const_pointer ) handle_sec_error(result) protocol_const = deref(protocol_const_pointer) self._protocol = _PROTOCOL_CONST_STRING_MAP[protocol_const] cipher_int_pointer = new(Security, 'SSLCipherSuite *') result = Security.SSLGetNegotiatedCipher( session_context, cipher_int_pointer ) handle_sec_error(result) cipher_int = deref(cipher_int_pointer) cipher_bytes = int_to_bytes(cipher_int, width=2) self._cipher_suite = CIPHER_SUITE_MAP.get(cipher_bytes, cipher_bytes) session_info = parse_session_info( self._server_hello, self._client_hello ) self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] except (OSError, socket_.error): if session_context: if osx_version_info < (10, 8): result = Security.SSLDisposeContext(session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(session_context) handle_cf_error(result) self._session_context = None self.close() raise finally: # Trying to release crl_search_ref or ocsp_search_ref results in # a segmentation fault, so we do not do that if ssl_policy_ref: result = CoreFoundation.CFRelease(ssl_policy_ref) handle_cf_error(result) ssl_policy_ref = None if crl_policy_ref: result = CoreFoundation.CFRelease(crl_policy_ref) handle_cf_error(result) crl_policy_ref = None if ocsp_policy_ref: result = CoreFoundation.CFRelease(ocsp_policy_ref) handle_cf_error(result) ocsp_policy_ref = None if policy_array_ref: result = CoreFoundation.CFRelease(policy_array_ref) handle_cf_error(result) policy_array_ref = None
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 oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection 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._session_context is None: # Even if the session is closed, we can use # buffered data to respond to read requests if self._decrypted_bytes != b'': output = self._decrypted_bytes self._decrypted_bytes = b'' return output self._raise_closed() 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 # 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 = max_length - len(self._decrypted_bytes) read_buffer = buffer_from_bytes(to_read) processed_pointer = new(Security, 'size_t *') result = Security.SSLRead( self._session_context, read_buffer, to_read, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception if result and result not in set([SecurityConst.errSSLWouldBlock, SecurityConst.errSSLClosedGraceful]): handle_sec_error(result, TLSError) if result and result == SecurityConst.errSSLClosedGraceful: self._gracefully_closed = True self._shutdown(False) self._raise_closed() bytes_read = deref(processed_pointer) output = self._decrypted_bytes + bytes_from_buffer(read_buffer, bytes_read) self._decrypted_bytes = output[max_length:] return output[0:max_length]
def read_until(self, marker): """ Reads data from the socket until a marker is found. Data read includes the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read, including the marker """ if not isinstance(marker, byte_cls) and not isinstance(marker, Pattern): raise TypeError(pretty_message( ''' marker must be a byte string or compiled regex object, not %s ''', type_name(marker) )) output = b'' is_regex = isinstance(marker, Pattern) while True: if len(self._decrypted_bytes) > 0: chunk = self._decrypted_bytes self._decrypted_bytes = b'' else: to_read = self._os_buffered_size() or 8192 chunk = self.read(to_read) offset = len(output) output += chunk if is_regex: match = marker.search(output) if match is not None: end = match.end() break else: # If the marker was not found last time, we have to start # at a position where the marker would have its final char # in the newly read chunk start = max(0, offset - len(marker) - 1) match = output.find(marker, start) if match != -1: end = match + len(marker) break self._decrypted_bytes = output[end:] + self._decrypted_bytes return output[0:end]
def _os_buffered_size(self): """ Returns the number of bytes of decrypted data stored in the Secure Transport read buffer. This amount of data can be read from SSLRead() without calling self._socket.recv(). :return: An integer - the number of available bytes """ num_bytes_pointer = new(Security, 'size_t *') result = Security.SSLGetBufferedReadSize( self._session_context, num_bytes_pointer ) handle_sec_error(result) return deref(num_bytes_pointer)
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 oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection 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._session_context is None: self._raise_closed() processed_pointer = new(Security, 'size_t *') data_len = len(data) while data_len: write_buffer = buffer_from_bytes(data) result = Security.SSLWrite( self._session_context, write_buffer, data_len, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception handle_sec_error(result, TLSError) bytes_written = deref(processed_pointer) data = data[bytes_written:] data_len = len(data) if data_len > 0: self.select_write()
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._session_context is None: return # Ignore error during close in case other end closed already result = Security.SSLClose(self._session_context) if osx_version_info < (10, 8): result = Security.SSLDisposeContext(self._session_context) handle_sec_error(result) else: result = CoreFoundation.CFRelease(self._session_context) handle_cf_error(result) self._session_context = None if manual: self._local_closed = True 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 if self._connection_id in _socket_refs: del _socket_refs[self._connection_id]
def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ trust_ref = None cf_data_ref = None result = None try: trust_ref_pointer = new(Security, 'SecTrustRef *') result = Security.SSLCopyPeerTrust( self._session_context, trust_ref_pointer ) handle_sec_error(result) trust_ref = unwrap(trust_ref_pointer) number_certs = Security.SecTrustGetCertificateCount(trust_ref) self._intermediates = [] for index in range(0, number_certs): sec_certificate_ref = Security.SecTrustGetCertificateAtIndex( trust_ref, index ) cf_data_ref = Security.SecCertificateCopyData(sec_certificate_ref) cert_data = CFHelpers.cf_data_to_bytes(cf_data_ref) result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result) cf_data_ref = None cert = x509.Certificate.load(cert_data) if index == 0: self._certificate = cert else: self._intermediates.append(cert) finally: if trust_ref: result = CoreFoundation.CFRelease(trust_ref) handle_cf_error(result) if cf_data_ref: result = CoreFoundation.CFRelease(cf_data_ref) handle_cf_error(result)
def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._session_context 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._session_context is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates
def get_path(temp_dir=None, cache_length=24, cert_callback=None): """ Get the filesystem path to a file that contains OpenSSL-compatible CA certs. On OS X and Windows, there are extracted from the system certificate store and cached in a file on the filesystem. This path should not be writable by other users, otherwise they could inject CA certs into the trust list. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :param cache_length: The number of hours to cache the CA certs on OS X and Windows :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. This is only called on Windows and OS X when passed to this function. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: The full filesystem path to a CA certs file """ ca_path, temp = _ca_path(temp_dir) # Windows and OS X if temp and _cached_path_needs_update(ca_path, cache_length): empty_set = set() any_purpose = '2.5.29.37.0' apple_ssl = '1.2.840.113635.100.1.3' win_server_auth = '1.3.6.1.5.5.7.3.1' with path_lock: if _cached_path_needs_update(ca_path, cache_length): with open(ca_path, 'wb') as f: for cert, trust_oids, reject_oids in extract_from_system(cert_callback, True): if sys.platform == 'darwin': if trust_oids != empty_set and any_purpose not in trust_oids \ and apple_ssl not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (apple_ssl in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue elif sys.platform == 'win32': if trust_oids != empty_set and any_purpose not in trust_oids \ and win_server_auth not in trust_oids: if cert_callback: cert_callback(Certificate.load(cert), 'implicitly distrusted for TLS') continue if reject_oids != empty_set and (win_server_auth in reject_oids or any_purpose in reject_oids): if cert_callback: cert_callback(Certificate.load(cert), 'explicitly distrusted for TLS') continue if cert_callback: cert_callback(Certificate.load(cert), None) f.write(armor('CERTIFICATE', cert)) if not ca_path: raise CACertsError('No CA certs found') return ca_path
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None): """ Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (OIDs) that are sourced from various RFCs and vendors (Apple and Microsoft). This trust information augments what is in the certificate itself. Any OID that is in the set of trusted purposes indicates the certificate has been explicitly trusted for a purpose beyond the extended key purpose extension. Any OID in the reject set is a purpose that the certificate should not be trusted for, even if present in the extended key purpose extension. *A list of common trust OIDs can be found as part of the `KeyPurposeId()` class in the `asn1crypto.x509` module of the `asn1crypto` package.* :param cache_length: The number of hours to cache the CA certs in memory before they are refreshed :param map_vendor_oids: A bool indicating if the following mapping of OIDs should happen for trust information from the OS trust list: - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :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. :raises: oscrypto.errors.CACertsError - when an error occurs exporting/locating certs :return: A (copied) list of 3-element tuples containing CA certs from the OS trust ilst: - 0: an asn1crypto.x509.Certificate object - 1: a set of unicode strings of OIDs of trusted purposes - 2: a set of unicode strings of OIDs of rejected purposes """ if not _in_memory_up_to_date(cache_length): with memory_lock: if not _in_memory_up_to_date(cache_length): certs = [] for cert_bytes, trust_oids, reject_oids in extract_from_system(cert_callback): if map_vendor_oids: trust_oids = _map_oids(trust_oids) reject_oids = _map_oids(reject_oids) certs.append((Certificate.load(cert_bytes), trust_oids, reject_oids)) _module_values['certs'] = certs _module_values['last_update'] = time.time() return list(_module_values['certs'])
def clear_cache(temp_dir=None): """ Clears any cached info that was exported from the OS trust store. This will ensure the latest changes are returned from calls to get_list() and get_path(), but at the expense of re-exporting and parsing all certificates. :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. Must be the same value passed to get_path(). """ with memory_lock: _module_values['last_update'] = None _module_values['certs'] = None ca_path, temp = _ca_path(temp_dir) if temp: with path_lock: if os.path.exists(ca_path): os.remove(ca_path)
def _ca_path(temp_dir=None): """ Returns the file path to the CA certs file :param temp_dir: The temporary directory to cache the CA certs in on OS X and Windows. Needs to have secure permissions so other users can not modify the contents. :return: A 2-element tuple: - 0: A unicode string of the file path - 1: A bool if the file is a temporary file """ ca_path = system_path() # Windows and OS X if ca_path is None: if temp_dir is None: temp_dir = tempfile.gettempdir() if not os.path.isdir(temp_dir): raise CACertsError(pretty_message( ''' The temp dir specified, "%s", is not a directory ''', temp_dir )) ca_path = os.path.join(temp_dir, 'oscrypto-ca-bundle.crt') return (ca_path, True) return (ca_path, False)
def _map_oids(oids): """ Takes a set of unicode string OIDs and converts vendor-specific OIDs into generics OIDs from RFCs. - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.1 (server_auth) - 1.2.840.113635.100.1.3 (apple_ssl) -> 1.3.6.1.5.5.7.3.2 (client_auth) - 1.2.840.113635.100.1.8 (apple_smime) -> 1.3.6.1.5.5.7.3.4 (email_protection) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.13 (eap_over_ppp) - 1.2.840.113635.100.1.9 (apple_eap) -> 1.3.6.1.5.5.7.3.14 (eap_over_lan) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.5 (ipsec_end_system) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.6 (ipsec_tunnel) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.7 (ipsec_user) - 1.2.840.113635.100.1.11 (apple_ipsec) -> 1.3.6.1.5.5.7.3.17 (ipsec_ike) - 1.2.840.113635.100.1.16 (apple_code_signing) -> 1.3.6.1.5.5.7.3.3 (code_signing) - 1.2.840.113635.100.1.20 (apple_time_stamping) -> 1.3.6.1.5.5.7.3.8 (time_stamping) - 1.3.6.1.4.1.311.10.3.2 (microsoft_time_stamp_signing) -> 1.3.6.1.5.5.7.3.8 (time_stamping) :param oids: A set of unicode strings :return: The original set of OIDs with any mapped OIDs added """ new_oids = set() for oid in oids: if oid in _oid_map: new_oids |= _oid_map[oid] return oids | new_oids
def _cached_path_needs_update(ca_path, cache_length): """ Checks to see if a cache file needs to be refreshed :param ca_path: A unicode string of the path to the cache file :param cache_length: An integer representing the number of hours the cache is valid for :return: A boolean - True if the cache needs to be updated, False if the file is up-to-date """ exists = os.path.exists(ca_path) if not exists: return True stats = os.stat(ca_path) if stats.st_mtime < time.time() - cache_length * 60 * 60: return True if stats.st_size == 0: return True return False
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 OpenSSL :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') return os.urandom(length)
def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ Implements PBKDF2 from PKCS#5 v2.2 in pure Python :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 :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) )) algo = getattr(hashlib, hash_algorithm) hash_length = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] blocks = int(math.ceil(key_length / hash_length)) original_hmac = hmac.new(password, None, algo) int_pack = struct.Struct(b'>I').pack output = b'' for block in range(1, blocks + 1): prf = original_hmac.copy() prf.update(salt + int_pack(block)) last = prf.digest() u = int_from_bytes(last) for _ in range(2, iterations + 1): prf = original_hmac.copy() prf.update(last) last = prf.digest() u ^= int_from_bytes(last) t = int_to_bytes(u) output += t return output[0:key_length]
def generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :param curve: A unicode string - used for "ec" keys. 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 OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm not in set(['rsa', 'dsa', 'ec']): raise ValueError(pretty_message( ''' algorithm must be one of "rsa", "dsa", "ec", not %s ''', repr(algorithm) )) if algorithm == 'rsa': if bit_size not in set([1024, 2048, 3072, 4096]): raise ValueError(pretty_message( ''' bit_size must be one of 1024, 2048, 3072, 4096, not %s ''', repr(bit_size) )) elif algorithm == 'dsa': if bit_size not in set([1024]): raise ValueError(pretty_message( ''' bit_size must be 1024, not %s ''', repr(bit_size) )) elif algorithm == 'ec': if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s ''', repr(curve) )) cf_dict = None public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[algorithm] if algorithm == 'ec': key_size = { 'secp256r1': 256, 'secp384r1': 384, 'secp521r1': 521, }[curve] else: key_size = bit_size private_key_pointer = new(Security, 'SecKeyRef *') public_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") # For some reason Apple decided that DSA keys were not a valid type of # key to be generated via SecKeyGeneratePair(), thus we have to use the # lower level, deprecated SecKeyCreatePair() if algorithm == 'dsa': sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DSA, key_size, 0, SecurityConst.CSSM_KEYUSE_VERIFY, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, SecurityConst.CSSM_KEYUSE_SIGN, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) else: cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeySizeInBits, CFHelpers.cf_number_from_integer(key_size)), (Security.kSecAttrLabel, cf_string) ]) result = Security.SecKeyGeneratePair(cf_dict, public_key_pointer, private_key_pointer) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_public_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(public_key_ref, 0, 0, null(), cf_data_public_pointer) handle_sec_error(result) cf_data_public = unwrap(cf_data_public_pointer) public_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_public) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref) return (load_public_key(public_key_bytes), load_private_key(private_key_bytes))
def generate_dh_parameters(bit_size): """ Generates DH parameters for use with Diffie-Hellman key exchange. Returns a structure in the format of DHParameter defined in PKCS#3, which is also used by the OpenSSL dhparam tool. THIS CAN BE VERY TIME CONSUMING! :param bit_size: The integer bit size of the parameters to generate. Must be between 512 and 4096, and divisible by 64. Recommended secure value as of early 2016 is 2048, with an absolute minimum of 1024. :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: An asn1crypto.algos.DHParameters object. Use oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with web servers. """ if not isinstance(bit_size, int_types): raise TypeError(pretty_message( ''' bit_size must be an integer, not %s ''', type_name(bit_size) )) if bit_size < 512: raise ValueError('bit_size must be greater than or equal to 512') if bit_size > 4096: raise ValueError('bit_size must be less than or equal to 4096') if bit_size % 64 != 0: raise ValueError('bit_size must be a multiple of 64') public_key_ref = None private_key_ref = None cf_data_public = None cf_data_private = None cf_string = None sec_access_ref = None try: public_key_pointer = new(Security, 'SecKeyRef *') private_key_pointer = new(Security, 'SecKeyRef *') cf_string = CFHelpers.cf_string_from_unicode("Temporary key from oscrypto python library - safe to delete") sec_access_ref_pointer = new(Security, 'SecAccessRef *') result = Security.SecAccessCreate(cf_string, null(), sec_access_ref_pointer) sec_access_ref = unwrap(sec_access_ref_pointer) result = Security.SecKeyCreatePair( null(), SecurityConst.CSSM_ALGID_DH, bit_size, 0, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, 0, SecurityConst.CSSM_KEYATTR_EXTRACTABLE | SecurityConst.CSSM_KEYATTR_PERMANENT, sec_access_ref, public_key_pointer, private_key_pointer ) handle_sec_error(result) public_key_ref = unwrap(public_key_pointer) private_key_ref = unwrap(private_key_pointer) cf_data_private_pointer = new(CoreFoundation, 'CFDataRef *') result = Security.SecItemExport(private_key_ref, 0, 0, null(), cf_data_private_pointer) handle_sec_error(result) cf_data_private = unwrap(cf_data_private_pointer) private_key_bytes = CFHelpers.cf_data_to_bytes(cf_data_private) # Clean the new keys out of the keychain result = Security.SecKeychainItemDelete(public_key_ref) handle_sec_error(result) result = Security.SecKeychainItemDelete(private_key_ref) handle_sec_error(result) return algos.KeyExchangeAlgorithm.load(private_key_bytes)['parameters'] finally: if public_key_ref: CoreFoundation.CFRelease(public_key_ref) if private_key_ref: CoreFoundation.CFRelease(private_key_ref) if cf_data_public: CoreFoundation.CFRelease(cf_data_public) if cf_data_private: CoreFoundation.CFRelease(cf_data_private) if cf_string: CoreFoundation.CFRelease(cf_string) if sec_access_ref: CoreFoundation.CFRelease(sec_access_ref)
def _load_x509(certificate): """ Loads an ASN.1 object of an x509 certificate into a Certificate object :param certificate: An asn1crypto.x509.Certificate object :return: A Certificate object """ source = certificate.dump() cf_source = None try: cf_source = CFHelpers.cf_data_from_bytes(source) sec_key_ref = Security.SecCertificateCreateWithData(CoreFoundation.kCFAllocatorDefault, cf_source) return Certificate(sec_key_ref, certificate) finally: if cf_source: CoreFoundation.CFRelease(cf_source)
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey or PrivateKey object """ if key_object.algorithm == 'ec': curve_type, details = key_object.curve if curve_type != 'named': raise AsymmetricKeyError('OS X only supports EC keys using named curves') if details not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise AsymmetricKeyError(pretty_message( ''' OS X only supports EC keys using the named curves secp256r1, secp384r1 and secp521r1 ''' )) elif key_object.algorithm == 'dsa' and key_object.hash_algo == 'sha2': raise AsymmetricKeyError(pretty_message( ''' OS X only supports DSA keys based on SHA1 (2048 bits or less) - this key is based on SHA2 and is %s bits ''', key_object.bit_size )) elif key_object.algorithm == 'dsa' and key_object.hash_algo is None: raise IncompleteAsymmetricKeyError(pretty_message( ''' The DSA key does not contain the necessary p, q and g parameters and can not be used ''' )) if isinstance(key_object, keys.PublicKeyInfo): source = key_object.dump() key_class = Security.kSecAttrKeyClassPublic else: source = key_object.unwrap().dump() key_class = Security.kSecAttrKeyClassPrivate cf_source = None cf_dict = None cf_output = None try: cf_source = CFHelpers.cf_data_from_bytes(source) key_type = { 'dsa': Security.kSecAttrKeyTypeDSA, 'ec': Security.kSecAttrKeyTypeECDSA, 'rsa': Security.kSecAttrKeyTypeRSA, }[key_object.algorithm] cf_dict = CFHelpers.cf_dictionary_from_pairs([ (Security.kSecAttrKeyType, key_type), (Security.kSecAttrKeyClass, key_class), (Security.kSecAttrCanSign, CoreFoundation.kCFBooleanTrue), (Security.kSecAttrCanVerify, CoreFoundation.kCFBooleanTrue), ]) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key_ref = Security.SecKeyCreateFromData(cf_dict, cf_source, error_pointer) handle_cf_error(error_pointer) if key_class == Security.kSecAttrKeyClassPublic: return PublicKey(sec_key_ref, key_object) if key_class == Security.kSecAttrKeyClassPrivate: return PrivateKey(sec_key_ref, key_object) finally: if cf_source: CoreFoundation.CFRelease(cf_source) if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_output: CoreFoundation.CFRelease(cf_output)
def rsa_pkcs1v15_encrypt(certificate_or_public_key, data): """ Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 v1.5 padding. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 11 bytes less than the key length (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: A byte string of the encrypted data """ 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) )) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
def rsa_pkcs1v15_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :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 original plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(ciphertext) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) if osx_version_info < (10, 8): padding = SecurityConst.kSecPaddingNone else: padding = SecurityConst.kSecPaddingPKCS1 result = Security.SecKeyDecrypt( private_key.sec_key_ref, padding, ciphertext, len(ciphertext), buffer, output_length ) handle_sec_error(result) output = bytes_from_buffer(buffer, deref(output_length)) if osx_version_info < (10, 8): output = remove_pkcs1v15_encryption_padding(key_length, output) return output
def _encrypt(certificate_or_public_key, data, padding): """ Encrypts plaintext using an RSA public key or certificate :param certificate_or_public_key: A Certificate or PublicKey object :param data: The plaintext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :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 padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecEncryptTransformCreate( certificate_or_public_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) if padding: Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def _decrypt(private_key, ciphertext, padding): """ Decrypts RSA ciphertext using a private key :param private_key: A PrivateKey object :param ciphertext: The ciphertext - a byte string :param padding: The padding mode to use, specified as a kSecPadding*Key value :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 padding: raise ValueError('padding must be specified') cf_data = None sec_transform = None try: cf_data = CFHelpers.cf_data_from_bytes(ciphertext) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecDecryptTransformCreate( private_key.sec_key_ref, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, padding, error_pointer ) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) plaintext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(plaintext) finally: if cf_data: CoreFoundation.CFRelease(cf_data) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :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", "sha224", "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 """ 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 certificate_or_public_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA public key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) key_length = certificate_or_public_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyEncrypt( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingNone, signature, len(signature), buffer, output_length ) handle_sec_error(result) plaintext = bytes_from_buffer(buffer, deref(output_length)) if not verify_pss_padding(hash_algorithm, hash_length, certificate_or_public_key.bit_size, data, plaintext): raise SignatureError('Signature is invalid')
def _verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSA, DSA or ECDSA signature :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", "sha224", "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 """ 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(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) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if certificate_or_public_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if certificate_or_public_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > certificate_or_public_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', certificate_or_public_key.byte_size, len(data) )) result = Security.SecKeyRawVerify( certificate_or_public_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), signature, len(signature) ) # errSSLCrypto is returned in some situations on macOS 10.12 if result == SecurityConst.errSecVerifyFailed or result == SecurityConst.errSSLCrypto: raise SignatureError('Signature is invalid') handle_sec_error(result) return cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') cf_signature = CFHelpers.cf_data_from_bytes(signature) sec_transform = Security.SecVerifyTransformCreate( certificate_or_public_key.sec_key_ref, cf_signature, error_pointer ) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if certificate_or_public_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) res = Security.SecTransformExecute(sec_transform, error_pointer) if not is_null(error_pointer): error = unwrap(error_pointer) if not is_null(error): raise SignatureError('Signature is invalid') res = bool(CoreFoundation.CFBooleanGetValue(res)) if not res: raise SignatureError('Signature is invalid') finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
def rsa_pss_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :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", "sha224", "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 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(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if private_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA private key') hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) encoded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyDecrypt( private_key.sec_key_ref, SecurityConst.kSecPaddingNone, encoded_data, len(encoded_data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length))
def _sign(private_key, data, hash_algorithm): """ Generates an RSA, DSA or ECDSA signature :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", "sha224", "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 isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of PrivateKey, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']) if private_key.algorithm == 'rsa': valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"' if private_key.algorithm == 'rsa': valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if private_key.algorithm == 'rsa' and hash_algorithm == 'raw': if len(data) > private_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', private_key.byte_size, len(data) )) key_length = private_key.byte_size buffer = buffer_from_bytes(key_length) output_length = new(Security, 'size_t *', key_length) result = Security.SecKeyRawSign( private_key.sec_key_ref, SecurityConst.kSecPaddingPKCS1, data, len(data), buffer, output_length ) handle_sec_error(result) return bytes_from_buffer(buffer, deref(output_length)) cf_signature = None cf_data = None cf_hash_length = None sec_transform = None try: error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_transform = Security.SecSignTransformCreate(private_key.sec_key_ref, error_pointer) handle_cf_error(error_pointer) hash_constant = { 'md5': Security.kSecDigestMD5, 'sha1': Security.kSecDigestSHA1, 'sha224': Security.kSecDigestSHA2, 'sha256': Security.kSecDigestSHA2, 'sha384': Security.kSecDigestSHA2, 'sha512': Security.kSecDigestSHA2 }[hash_algorithm] Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestTypeAttribute, hash_constant, error_pointer ) handle_cf_error(error_pointer) if hash_algorithm in set(['sha224', 'sha256', 'sha384', 'sha512']): hash_length = { 'sha224': 224, 'sha256': 256, 'sha384': 384, 'sha512': 512 }[hash_algorithm] cf_hash_length = CFHelpers.cf_number_from_integer(hash_length) Security.SecTransformSetAttribute( sec_transform, Security.kSecDigestLengthAttribute, cf_hash_length, error_pointer ) handle_cf_error(error_pointer) if private_key.algorithm == 'rsa': Security.SecTransformSetAttribute( sec_transform, Security.kSecPaddingKey, Security.kSecPaddingPKCS1Key, error_pointer ) handle_cf_error(error_pointer) cf_data = CFHelpers.cf_data_from_bytes(data) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) cf_signature = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(cf_signature) finally: if sec_transform: CoreFoundation.CFRelease(sec_transform) if cf_signature: CoreFoundation.CFRelease(cf_signature) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_hash_length: CoreFoundation.CFRelease(cf_hash_length)
def public_key(self): """ :return: The PublicKey object for the public key this certificate contains """ if not self._public_key and self.sec_certificate_ref: sec_public_key_ref_pointer = new(Security, 'SecKeyRef *') res = Security.SecCertificateCopyPublicKey(self.sec_certificate_ref, sec_public_key_ref_pointer) handle_sec_error(res) sec_public_key_ref = unwrap(sec_public_key_ref_pointer) self._public_key = PublicKey(sec_public_key_ref, self.asn1['tbs_certificate']['subject_public_key_info']) return self._public_key
def backend(): """ :return: A unicode string of the backend being used: "openssl", "osx", "win", "winlegacy" """ if _module_values['backend'] is not None: return _module_values['backend'] with _backend_lock: if _module_values['backend'] is not None: return _module_values['backend'] if sys.platform == 'win32': # Windows XP was major version 5, Vista was 6 if sys.getwindowsversion()[0] < 6: _module_values['backend'] = 'winlegacy' else: _module_values['backend'] = 'win' elif sys.platform == 'darwin': _module_values['backend'] = 'osx' else: _module_values['backend'] = 'openssl' return _module_values['backend']
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None): """ Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll), or using a specific dynamic library on Linux/BSD (.so). This can also be used to configure oscrypto to use LibreSSL dynamic libraries. This method must be called before any oscrypto submodules are imported. :param libcrypto_path: A unicode string of the file path to the OpenSSL/LibreSSL libcrypto dynamic library. :param libssl_path: A unicode string of the file path to the OpenSSL/LibreSSL libssl dynamic library. :param trust_list_path: An optional unicode string of the path to a file containing OpenSSL-compatible CA certificates in PEM format. If this is not provided and the platform is OS X or Windows, the system trust roots will be exported from the OS and used for all TLS connections. :raises: ValueError - when one of the paths is not a unicode string OSError - when the trust_list_path does not exist on the filesystem oscrypto.errors.LibraryNotFoundError - when one of the path does not exist on the filesystem RuntimeError - when this function is called after another part of oscrypto has been imported """ if not isinstance(libcrypto_path, str_cls): raise ValueError('libcrypto_path must be a unicode string, not %s' % type_name(libcrypto_path)) if not isinstance(libssl_path, str_cls): raise ValueError('libssl_path must be a unicode string, not %s' % type_name(libssl_path)) if not os.path.exists(libcrypto_path): raise LibraryNotFoundError('libcrypto does not exist at %s' % libcrypto_path) if not os.path.exists(libssl_path): raise LibraryNotFoundError('libssl does not exist at %s' % libssl_path) if trust_list_path is not None: if not isinstance(trust_list_path, str_cls): raise ValueError('trust_list_path must be a unicode string, not %s' % type_name(trust_list_path)) if not os.path.exists(trust_list_path): raise OSError('trust_list_path does not exist at %s' % trust_list_path) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError('Another part of oscrypto has already been imported, unable to force use of OpenSSL') _module_values['backend'] = 'openssl' _module_values['backend_config'] = { 'libcrypto_path': libcrypto_path, 'libssl_path': libssl_path, 'trust_list_path': trust_list_path, }
def use_winlegacy(): """ Forces use of the legacy Windows CryptoAPI. This should only be used on Windows XP or for testing. It is less full-featured than the Cryptography Next Generation (CNG) API, and as a result the elliptic curve and PSS padding features are implemented in pure Python. This isn't ideal, but it a shim for end-user client code. No one is going to run a server on Windows XP anyway, right?! :raises: EnvironmentError - when this function is called on an operating system other than Windows RuntimeError - when this function is called after another part of oscrypto has been imported """ if sys.platform != 'win32': plat = platform.system() or sys.platform if plat == 'Darwin': plat = 'OS X' raise EnvironmentError('The winlegacy backend can only be used on Windows, not %s' % plat) with _backend_lock: if _module_values['backend'] is not None: raise RuntimeError( 'Another part of oscrypto has already been imported, unable to force use of Windows legacy CryptoAPI' ) _module_values['backend'] = 'winlegacy'
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 :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' algo = getattr(hashlib, hash_algorithm) # u and v values are bytes (not bits as in the RFC) u = { 'md5': 16, 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] if hash_algorithm in ['sha384', 'sha512']: v = 128 else: v = 64 # Step 1 d = chr_cls(id_) * v # Step 2 s = b'' if salt != b'': s_len = v * int(math.ceil(float(len(salt)) / v)) while len(s) < s_len: s += salt s = s[0:s_len] # Step 3 p = b'' if utf16_password != b'': p_len = v * int(math.ceil(float(len(utf16_password)) / v)) while len(p) < p_len: p += utf16_password p = p[0:p_len] # Step 4 i = s + p # Step 5 c = int(math.ceil(float(key_length) / u)) a = b'\x00' * (c * u) for num in range(1, c + 1): # Step 6A a2 = algo(d + i).digest() for _ in range(2, iterations + 1): a2 = algo(a2).digest() if num < c: # Step 6B b = b'' while len(b) < v: b += a2 b = int_from_bytes(b[0:v]) + 1 # Step 6C for num2 in range(0, len(i) // v): start = num2 * v end = (num2 + 1) * v i_num2 = i[start:end] i_num2 = int_to_bytes(int_from_bytes(i_num2) + b) # Ensure the new slice is the right size i_num2_l = len(i_num2) if i_num2_l > v: i_num2 = i_num2[i_num2_l - v:] i = i[0:start] + i_num2 + i[end:] # Step 7 (one peice at a time) begin = (num - 1) * u to_copy = min(key_length, u) a = a[0:begin] + a2[0:to_copy] + a[begin + to_copy:] return a[0:key_length]
def pbkdf2_iteration_calculator(hash_algorithm, key_length, target_ms=100, quiet=False): """ Runs pbkdf2() twice to determine the approximate number of iterations to use to hit a desired time per run. Use this on a production machine to dynamically adjust the number of iterations as high as you can. :param hash_algorithm: The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512" :param key_length: The length of the desired key in bytes :param target_ms: The number of milliseconds the derivation should take :param quiet: If no output should be printed as attempts are made :return: An integer number of iterations of PBKDF2 using the specified hash that will take at least target_ms """ 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) )) 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 not isinstance(target_ms, int_types): raise TypeError(pretty_message( ''' target_ms must be an integer, not %s ''', type_name(target_ms) )) if target_ms < 1: raise ValueError(pretty_message( ''' target_ms must be greater than 0 - is %s ''', repr(target_ms) )) if pbkdf2.pure_python: raise OSError(pretty_message( ''' Only a very slow, pure-python version of PBKDF2 is available, making this function useless ''' )) iterations = 10000 password = 'this is a test'.encode('utf-8') salt = rand_bytes(key_length) def _measure(): start = _get_start() pbkdf2(hash_algorithm, password, salt, iterations, key_length) observed_ms = _get_elapsed(start) if not quiet: print('%s iterations in %sms' % (iterations, observed_ms)) return 1.0 / target_ms * observed_ms # Measure the initial guess, then estimate how many iterations it would # take to reach 1/2 of the target ms and try it to get a good final number fraction = _measure() iterations = int(iterations / fraction / 2.0) fraction = _measure() iterations = iterations / fraction # < 20,000 round to 1000 # 20,000-100,000 round to 5,000 # > 100,000 round to 10,000 round_factor = -3 if iterations < 100000 else -4 result = int(round(iterations, round_factor)) if result > 20000: result = (result // 5000) * 5000 return result
def pbkdf1(hash_algorithm, password, salt, iterations, key_length): """ An implementation of PBKDF1 - should only be used for interop with legacy systems, not new architectures :param hash_algorithm: The string name of the hash algorithm to use: "md2", "md5", "sha1" :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 :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(['md2', 'md5', 'sha1']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "md2", "md5", "sha1", not %s ''', repr(hash_algorithm) )) if key_length > 16 and hash_algorithm in set(['md2', 'md5']): raise ValueError(pretty_message( ''' key_length can not be longer than 16 for %s - is %s ''', (hash_algorithm, repr(key_length)) )) if key_length > 20 and hash_algorithm == 'sha1': raise ValueError(pretty_message( ''' key_length can not be longer than 20 for sha1 - is %s ''', repr(key_length) )) algo = getattr(hashlib, hash_algorithm) output = algo(password + salt).digest() for _ in range(2, iterations + 1): output = algo(output).digest() return output[:key_length]
def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return code, error_string = get_error() if code == Advapi32Const.NTE_BAD_SIGNATURE: raise SignatureError('Signature is invalid') if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string)
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(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey))
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(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingNoneKey)
def aes_cbc_pkcs7_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and PKCS#7 padding. :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) )) return (iv, _encrypt(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key))
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :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(Security.kSecAttrKeyTypeAES, key, data, iv, Security.kSecPaddingPKCS7Key)
def rc4_encrypt(key, data): """ Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :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 len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _encrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
def rc4_decrypt(key, data): """ Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :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) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _decrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None)
def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :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) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) 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) )) return (iv, _encrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key))
def rc2_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :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) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeRC2, key, data, iv, Security.kSecPaddingPKCS5Key)
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 - %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return (iv, _encrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key))
def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext 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 ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :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) != 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 len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) # Expand 2-key to actual 24 byte byte string used by cipher if len(key) == 16: key = key + key[0:8] return _decrypt(Security.kSecAttrKeyType3DES, key, data, iv, Security.kSecPaddingPKCS5Key)
def des_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :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) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) 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) )) return (iv, _encrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key))
def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :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) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt(Security.kSecAttrKeyTypeDES, key, data, iv, Security.kSecPaddingPKCS5Key)
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A kSecAttrKeyType* value that specifies the cipher to use :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: The padding mode to use, specified as a kSecPadding*Key value - 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 != Security.kSecAttrKeyTypeRC4 and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != Security.kSecAttrKeyTypeRC4 and not padding: raise ValueError('padding must be specified') cf_dict = None cf_key = None cf_data = None cf_iv = None sec_key = None sec_transform = None try: cf_dict = CFHelpers.cf_dictionary_from_pairs([(Security.kSecAttrKeyType, cipher)]) cf_key = CFHelpers.cf_data_from_bytes(key) cf_data = CFHelpers.cf_data_from_bytes(data) error_pointer = new(CoreFoundation, 'CFErrorRef *') sec_key = Security.SecKeyCreateFromData(cf_dict, cf_key, error_pointer) handle_cf_error(error_pointer) sec_transform = Security.SecEncryptTransformCreate(sec_key, error_pointer) handle_cf_error(error_pointer) if cipher != Security.kSecAttrKeyTypeRC4: Security.SecTransformSetAttribute(sec_transform, Security.kSecModeCBCKey, null(), error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute(sec_transform, Security.kSecPaddingKey, padding, error_pointer) handle_cf_error(error_pointer) cf_iv = CFHelpers.cf_data_from_bytes(iv) Security.SecTransformSetAttribute(sec_transform, Security.kSecIVKey, cf_iv, error_pointer) handle_cf_error(error_pointer) Security.SecTransformSetAttribute( sec_transform, Security.kSecTransformInputAttributeName, cf_data, error_pointer ) handle_cf_error(error_pointer) ciphertext = Security.SecTransformExecute(sec_transform, error_pointer) handle_cf_error(error_pointer) return CFHelpers.cf_data_to_bytes(ciphertext) finally: if cf_dict: CoreFoundation.CFRelease(cf_dict) if cf_key: CoreFoundation.CFRelease(cf_key) if cf_data: CoreFoundation.CFRelease(cf_data) if cf_iv: CoreFoundation.CFRelease(cf_iv) if sec_key: CoreFoundation.CFRelease(sec_key) if sec_transform: CoreFoundation.CFRelease(sec_transform)
def version(self): """ Create a new version under this service. """ ver = Version() ver.conn = self.conn ver.attrs = { # Parent params 'service_id': self.attrs['id'], } ver.save() return ver
def vcl(self, name, content): """ Create a new VCL under this version. """ vcl = VCL() vcl.conn = self.conn vcl.attrs = { # Parent params 'service_id': self.attrs['service_id'], 'version': self.attrs['number'], # New instance params 'name': name, 'content': content, } vcl.save() return vcl
def to_dict(self): """ Converts the column to a dictionary representation accepted by the Citrination server. :return: Dictionary with basic options, plus any column type specific options held under the "options" key :rtype: dict """ return { "type": self.type, "name": self.name, "group_by_key": self.group_by_key, "role": self.role, "units": self.units, "options": self.build_options() }
def add_descriptor(self, descriptor, role='ignore', group_by_key=False): """ Add a descriptor column. :param descriptor: A Descriptor instance (e.g., RealDescriptor, InorganicDescriptor, etc.) :param role: Specify a role (input, output, latentVariable, or ignore) :param group_by_key: Whether or not to group by this key during cross validation """ descriptor.validate() if descriptor.key in self.configuration["roles"]: raise ValueError("Cannot add a descriptor with the same name twice") self.configuration['descriptors'].append(descriptor.as_dict()) self.configuration["roles"][descriptor.key] = role if group_by_key: self.configuration["group_by"].append(descriptor.key)
def _get(self, route, headers=None, failure_message=None): """ Execute a post request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.get(self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _post(self, route, data, headers=None, failure_message=None): """ Execute a post request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.post( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _put(self, route, data, headers=None, failure_message=None): """ Execute a put request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.put( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _patch(self, route, data, headers=None, failure_message=None): """ Execute a patch request and return the result """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.patch( self._get_qualified_route(route), headers=headers, data=data, verify=False, proxies=self.proxies ) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _delete(self, route, headers=None, failure_message=None): """ Execute a delete request and return the result :param headers: :return: """ headers = self._get_headers(headers) response_lambda = (lambda: requests.delete( self._get_qualified_route(route), headers=headers, verify=False, proxies=self.proxies) ) response = check_for_rate_limiting(response_lambda(), response_lambda) return self._handle_response(response, failure_message)
def _validate_search_query(self, returning_query): """ Checks to see that the query will not exceed the max query depth :param returning_query: The PIF system or Dataset query to execute. :type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery` """ start_index = returning_query.from_index or 0 size = returning_query.size or 0 if start_index < 0: raise CitrinationClientError( "start_index cannot be negative. Please enter a value greater than or equal to zero") if size < 0: raise CitrinationClientError("Size cannot be negative. Please enter a value greater than or equal to zero") if start_index + size > MAX_QUERY_DEPTH: raise CitrinationClientError( "Citrination does not support pagination past the {0}th result. Please reduce either the from_index and/or size such that their sum is below {0}".format( MAX_QUERY_DEPTH))
def pif_search(self, pif_system_returning_query): """ Run a PIF query against Citrination. :param pif_system_returning_query: The PIF system query to execute. :type pif_system_returning_query: :class:`PifSystemReturningQuery` :return: :class:`PifSearchResult` object with the results of the query. :rtype: :class:`PifSearchResult` """ self._validate_search_query(pif_system_returning_query) return self._execute_search_query( pif_system_returning_query, PifSearchResult )
def dataset_search(self, dataset_returning_query): """ Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the results of the query. :rtype: :class:`DatasetSearchResult` """ self._validate_search_query(dataset_returning_query) return self._execute_search_query( dataset_returning_query, DatasetSearchResult )
def _execute_search_query(self, returning_query, result_class): """ Run a PIF query against Citrination. :param returning_query: :class:`BaseReturningQuery` to execute. :param result_class: The class of the result to return. :return: ``result_class`` object with the results of the query. """ if returning_query.from_index: from_index = returning_query.from_index else: from_index = 0 if returning_query.size != None: size = min(returning_query.size, client_config.max_query_size) else: size = client_config.max_query_size if (size == client_config.max_query_size and size != returning_query.size): self._warn("Query size greater than max system size - only {} results will be returned".format(size)) time = 0.0; hits = []; while True: sub_query = deepcopy(returning_query) sub_query.from_index = from_index + len(hits) partial_results = self._search_internal(sub_query, result_class) total = partial_results.total_num_hits time += partial_results.took if partial_results.hits is not None: hits.extend(partial_results.hits) if len(hits) >= size or len(hits) >= total or sub_query.from_index >= total: break return result_class(hits=hits, total_num_hits=total, took=time)
def pif_multi_search(self, multi_query): """ Run each in a list of PIF queries against Citrination. :param multi_query: :class:`MultiQuery` object to execute. :return: :class:`PifMultiSearchResult` object with the results of the query. """ failure_message = "Error while making PIF multi search request" response_dict = self._get_success_json( self._post(routes.pif_multi_search, data=json.dumps(multi_query, cls=QueryEncoder), failure_message=failure_message)) return PifMultiSearchResult(**keys_to_snake_case(response_dict['results']))
def generate_simple_chemical_query(self, name=None, chemical_formula=None, property_name=None, property_value=None, property_min=None, property_max=None, property_units=None, reference_doi=None, include_datasets=[], exclude_datasets=[], from_index=None, size=None): """ This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(name=['A', 'B']) will match records that have name equal to 'A' or 'B'. Results will be pulled into the extracted field of the :class:`PifSearchHit` objects that are returned. The name will appear under the key "name", chemical formula under "chemical_formula", property name under "property_name", value of the property under "property_value", units of the property under "property_units", and reference DOI under "reference_doi". This method is only meant for execution of very simple queries. More complex queries must use the search method that accepts a :class:`PifSystemReturningQuery` object. :param name: One or more strings with the names of the chemical system to match. :type name: str or list of str :param chemical_formula: One or more strings with the chemical formulas to match. :type chemical_formula: str or list of str :param property_name: One or more strings with the names of the property to match. :type property_name: str or list of str :param property_value: One or more strings or numbers with the exact values to match. :type property_value: str or int or float or list of str or int or float :param property_min: A single string or number with the minimum value to match. :type property_min: str or int or float :param property_max: A single string or number with the maximum value to match. :type property_max: str or int or float :param property_units: One or more strings with the property units to match. :type property_units: str or list of str :param reference_doi: One or more strings with the DOI to match. :type reference_doin: str or list of str :param include_datasets: One or more integers with dataset IDs to match. :type include_datasets: int or list of int :param exclude_datasets: One or more integers with dataset IDs that must not match. :type exclude_datasets: int or list of int :param from_index: Index of the first record to match. :type from_index: int :param size: Total number of records to return. :type size: int :return: A query to to be submitted with the pif_search method :rtype: :class:`PifSystemReturningQuery` """ pif_system_query = PifSystemQuery() pif_system_query.names = FieldQuery( extract_as='name', filter=[Filter(equal=i) for i in self._get_list(name)]) pif_system_query.chemical_formula = ChemicalFieldQuery( extract_as='chemical_formula', filter=[ChemicalFilter(equal=i) for i in self._get_list(chemical_formula)]) pif_system_query.references = ReferenceQuery(doi=FieldQuery( extract_as='reference_doi', filter=[Filter(equal=i) for i in self._get_list(reference_doi)])) # Generate the parts of the property query property_name_query = FieldQuery( extract_as='property_name', filter=[Filter(equal=i) for i in self._get_list(property_name)]) property_units_query = FieldQuery( extract_as='property_units', filter=[Filter(equal=i) for i in self._get_list(property_units)]) property_value_query = FieldQuery( extract_as='property_value', filter=[]) for i in self._get_list(property_value): property_value_query.filter.append(Filter(equal=i)) if property_min is not None or property_max is not None: property_value_query.filter.append(Filter(min=property_min, max=property_max)) # Generate the full property query pif_system_query.properties = PropertyQuery( name=property_name_query, value=property_value_query, units=property_units_query) # Generate the dataset query dataset_query = list() if include_datasets: dataset_query.append(DatasetQuery(logic='MUST', id=[Filter(equal=i) for i in include_datasets])) if exclude_datasets: dataset_query.append(DatasetQuery(logic='MUST_NOT', id=[Filter(equal=i) for i in exclude_datasets])) # Run the query pif_system_returning_query = PifSystemReturningQuery( query=DataQuery( system=pif_system_query, dataset=dataset_query), from_index=from_index, size=size, score_relevance=True) return pif_system_returning_query
def check_for_rate_limiting(response, response_lambda, timeout=1, attempts=0): """ Takes an initial response, and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered. If more than 3 attempts are made, a RateLimitingException is raised :param response: A response from Citrination :type response: requests.Response :param response_lambda: a callable that runs the request that returned the response :type response_lambda: function :param timeout: the time to wait before retrying :type timeout: int :param attempts: the number of the retry being executed :type attempts: int """ if attempts >= 3: raise RateLimitingException() if response.status_code == 429: sleep(timeout) new_timeout = timeout + 1 new_attempts = attempts + 1 return check_for_rate_limiting(response_lambda(timeout, attempts), response_lambda, timeout=new_timeout, attempts=new_attempts) return response
def create(self, configuration, name, description): """ Creates a data view from the search template and ml template given :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view :return: The data view id """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" result = self._get_success_json(self._post_json( 'v1/data_views', data, failure_message=failure_message)) data_view_id = result['data']['id'] return data_view_id
def update(self, id, configuration, name, description): """ Updates an existing data view from the search template and ml template given :param id: Identifier for the data view. This returned from the create method. :param configuration: Information to construct the data view from (eg descriptors, datasets etc) :param name: Name of the data view :param description: Description for the data view """ data = { "configuration": configuration, "name": name, "description": description } failure_message = "Dataview creation failed" self._patch_json( 'v1/data_views/' + id, data, failure_message=failure_message)
def get(self, data_view_id): """ Gets basic information about a view :param data_view_id: Identifier of the data view :return: Metadata about the view as JSON """ failure_message = "Dataview get failed" return self._get_success_json(self._get( 'v1/data_views/' + data_view_id, None, failure_message=failure_message))['data']['data_view']
def get_data_view_service_status(self, data_view_id): """ Retrieves the status for all of the services associated with a data view: - predict - experimental_design - data_reports - model_reports :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :return: A :class:`DataViewStatus` :rtype: DataViewStatus """ url = "data_views/{}/status".format(data_view_id) response = self._get(url).json() result = response["data"]["status"] return DataViewStatus( predict=ServiceStatus.from_response_dict(result["predict"]), experimental_design=ServiceStatus.from_response_dict(result["experimental_design"]), data_reports=ServiceStatus.from_response_dict(result["data_reports"]), model_reports=ServiceStatus.from_response_dict(result["model_reports"]) )
def create_ml_configuration_from_datasets(self, dataset_ids): """ Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ available_columns = self.search_template_client.get_available_columns(dataset_ids) # Create a search template from dataset ids search_template = self.search_template_client.create(dataset_ids, available_columns) return self.create_ml_configuration(search_template, available_columns, dataset_ids)
def create_ml_configuration(self, search_template, extract_as_keys, dataset_ids): """ This method will spawn a server job to create a default ML configuration based on a search template and the extract as keys. This function will submit the request to build, and wait for the configuration to finish before returning. :param search_template: A search template defining the query (properties, datasets etc) :param extract_as_keys: Array of extract-as keys defining the descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_configuration_status) """ data = { "search_template": search_template, "extract_as_keys": extract_as_keys } failure_message = "ML Configuration creation failed" config_job_id = self._get_success_json(self._post_json( 'v1/descriptors/builders/simple/default/trigger', data, failure_message=failure_message))['data'][ 'result']['uid'] while True: config_status = self.__get_ml_configuration_status(config_job_id) print('Configuration status: ', config_status) if config_status['status'] == 'Finished': ml_config = self.__convert_response_to_configuration(config_status['result'], dataset_ids) return ml_config time.sleep(5)
def __convert_response_to_configuration(self, result_blob, dataset_ids): """ Utility function to turn the result object from the configuration builder endpoint into something that can be used directly as a configuration. :param result_blob: Nested dicts representing the possible descriptors :param dataset_ids: Array of dataset identifiers to make search template from :return: An object suitable to be used as a parameter to data view create """ builder = DataViewBuilder() builder.dataset_ids(dataset_ids) for i, (k, v) in enumerate(result_blob['descriptors'].items()): try: descriptor = self.__snake_case(v[0]) print(json.dumps(descriptor)) descriptor['descriptor_key'] = k builder.add_raw_descriptor(descriptor) except IndexError: pass for i, (k, v) in enumerate(result_blob['types'].items()): builder.set_role(k, v.lower()) return builder.build()
def __snake_case(self, descriptor): """ Utility method to convert camelcase to snake :param descriptor: The dictionary to convert """ newdict = {} for i, (k, v) in enumerate(descriptor.items()): newkey = "" for j, c in enumerate(k): if c.isupper(): if len(newkey) != 0: newkey += '_' newkey += c.lower() else: newkey += c newdict[newkey] = v return newdict
def __get_ml_configuration_status(self, job_id): """ After invoking the create_ml_configuration async method, you can use this method to check on the status of the builder job. :param job_id: The identifier returned from create_ml_configuration :return: Job status """ failure_message = "Get status on ml configuration failed" response = self._get_success_json(self._get( 'v1/descriptors/builders/simple/default/' + job_id + '/status', None, failure_message=failure_message))[ 'data'] return response
def tsne(self, data_view_id): """ Get the t-SNE projection, including responses and tags. :param data_view_id: The ID of the data view to retrieve TSNE from :type data_view_id: int :return: The TSNE analysis :rtype: :class:`Tsne` """ analysis = self._data_analysis(data_view_id) projections = analysis['projections'] tsne = Tsne() for k, v in projections.items(): projection = Projection( xs=v['x'], ys=v['y'], responses=v['label'], tags=v['inputs'], uids=v['uid'] ) tsne.add_projection(k, projection) return tsne
def predict(self, data_view_id, candidates, method="scalar", use_prior=True): """ Predict endpoint. This simply wraps the async methods (submit and poll for status/results). :param data_view_id: The ID of the data view to use for prediction :type data_view_id: str :param candidates: A list of candidates to make predictions on :type candidates: list of dicts :param method: Method for propagating predictions through model graphs. "scalar" uses linearized uncertainty propagation, whereas "scalar_from_distribution" still returns scalar predictions but uses sampling to propagate uncertainty without a linear approximation. :type method: str ("scalar" or "scalar_from_distribution") :param use_prior: Whether to apply prior values implied by the property descriptors :type use_prior: bool :return: The results of the prediction :rtype: list of :class:`PredictionResult` """ uid = self.submit_predict_request(data_view_id, candidates, method, use_prior) while self.check_predict_status(data_view_id, uid)['status'] not in ["Finished", "Failed", "Killed"]: time.sleep(1) result = self.check_predict_status(data_view_id, uid) if result["status"] == "Finished": paired = zip(result["results"]["candidates"], result["results"]["loss"]) prediction_result_format = [{k: (p[0][k], p[1][k]) for k in p[0].keys()} for p in paired] return list(map( lambda c: _get_prediction_result_from_candidate(c), prediction_result_format )) else: raise RuntimeError( "Prediction failed: UID={}, result={}".format(uid, result["status"]) )
def retrain(self, dataview_id): """ Start a model retraining :param dataview_id: The ID of the views :return: """ url = 'data_views/{}/retrain'.format(dataview_id) response = self._post_json(url, data={}) if response.status_code != requests.codes.ok: raise RuntimeError('Retrain requested ' + str(response.status_code) + ' response: ' + str(response.message)) return True
def _data_analysis(self, data_view_id): """ Data analysis endpoint. :param data_view_id: The model identifier (id number for data views) :type data_view_id: str :return: dictionary containing information about the data, e.g. dCorr and tsne """ failure_message = "Error while retrieving data analysis for data view {}".format(data_view_id) return self._get_success_json(self._get(routes.data_analysis(data_view_id), failure_message=failure_message))
def submit_predict_request(self, data_view_id, candidates, prediction_source='scalar', use_prior=True): """ Submits an async prediction request. :param data_view_id: The id returned from create :param candidates: Array of candidates :param prediction_source: 'scalar' or 'scalar_from_distribution' :param use_prior: True to use prior prediction, otherwise False :return: Predict request Id (used to check status) """ data = { "prediction_source": prediction_source, "use_prior": use_prior, "candidates": candidates } failure_message = "Configuration creation failed" post_url = 'v1/data_views/' + str(data_view_id) + '/predict/submit' return self._get_success_json( self._post_json(post_url, data, failure_message=failure_message) )['data']['uid']
def check_predict_status(self, view_id, predict_request_id): """ Returns a string indicating the status of the prediction job :param view_id: The data view id returned from data view create :param predict_request_id: The id returned from predict :return: Status data, also includes results if state is finished """ failure_message = "Get status on predict failed" bare_response = self._get_success_json(self._get( 'v1/data_views/' + str(view_id) + '/predict/' + str(predict_request_id) + '/status', None, failure_message=failure_message)) result = bare_response["data"] # result.update({"message": bare_response["message"]}) return result
def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler="Default"): """ Submits a new experimental design run. :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param num_candidates: The number of candidates to return :type num_candidates: int :param target: An :class:``Target`` instance representing the design run optimization target :type target: :class:``Target`` :param constraints: An array of design constraints (instances of objects which extend :class:``BaseConstraint``) :type constraints: list of :class:``BaseConstraint`` :param sampler: The name of the sampler to use during the design run: either "Default" or "This view" :type sampler: str :return: A :class:`DesignRun` instance containing the UID of the new run """ if effort > 30: raise CitrinationClientError("Parameter effort must be less than 30 to trigger a design run") if target is not None: target = target.to_dict() constraint_dicts = [c.to_dict() for c in constraints] body = { "num_candidates": num_candidates, "target": target, "effort": effort, "constraints": constraint_dicts, "sampler": sampler } url = routes.submit_data_view_design(data_view_id) response = self._post_json(url, body).json() return DesignRun(response["data"]["design_run"]["uid"])
def get_design_run_status(self, data_view_id, run_uuid): """ Retrieves the status of an in progress or completed design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve status for :type run_uuid: str :return: A :class:`ProcessStatus` object """ url = routes.get_data_view_design_status(data_view_id, run_uuid) response = self._get(url).json() status = response["data"] return ProcessStatus( result=status.get("result"), progress=status.get("progress"), status=status.get("status"), messages=status.get("messages") )
def get_design_run_results(self, data_view_id, run_uuid): """ Retrieves the results of an existing designrun :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to retrieve results from :type run_uuid: str :return: A :class:`DesignResults` object """ url = routes.get_data_view_design_results(data_view_id, run_uuid) response = self._get(url).json() result = response["data"] return DesignResults( best_materials=result.get("best_material_results"), next_experiments=result.get("next_experiment_results") )
def get_data_view(self, data_view_id): """ Retrieves a summary of information for a given data view - view id - name - description - columns :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str """ url = routes.get_data_view(data_view_id) response = self._get(url).json() result = response["data"]["data_view"] datasets_list = [] for dataset in result["datasets"]: datasets_list.append(Dataset( name=dataset["name"], id=dataset["id"], description=dataset["description"] )) columns_list = [] for column in result["columns"]: columns_list.append(ColumnFactory.from_dict(column)) return DataView( view_id=data_view_id, name=result["name"], description=result["description"], datasets=datasets_list, columns=columns_list, )
def kill_design_run(self, data_view_id, run_uuid): """ Kills an in progress experimental design run :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str :param run_uuid: The UUID of the design run to kill :type run_uuid: str :return: The UUID of the design run """ url = routes.kill_data_view_design_run(data_view_id, run_uuid) response = self._delete(url).json() return response["data"]["uid"]
def load_file_as_yaml(path): """ Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file """ with open(path, "r") as f: raw_yaml = f.read() parsed_dict = yaml.load(raw_yaml) return parsed_dict
def get_credentials_from_file(filepath): """ Extracts credentials from the yaml formatted credential filepath passed in. Uses the default profile if the CITRINATION_PROFILE env var is not set, otherwise looks for a profile with that name in the credentials file. :param filepath: The path of the credentials file """ try: creds = load_file_as_yaml(filepath) except Exception: creds = {} profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE) if profile_name is None or len(profile_name) == 0: profile_name = DEFAULT_CITRINATION_PROFILE api_key = None site = None try: profile = creds[profile_name] api_key = profile[CREDENTIALS_API_KEY_KEY] site = profile[CREDENTIALS_SITE_KEY] except KeyError: pass return (api_key, site)
def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE): """ Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials. Specifically, this method ranks credential priority as follows: 1. Those passed in as the first two parameters to this method 2. Those found in the environment as variables 3. Those found in the credentials file at the profile specified by the profile environment variable 4. Those found in the default stanza in the credentials file :param api_key: A Citrination API Key or None :param site: A Citrination site URL or None :param cred_file: The path to a credentials file """ profile_api_key, profile_site = get_credentials_from_file(cred_file) if api_key is None: api_key = os.environ.get(citr_env_vars.CITRINATION_API_KEY) if api_key is None or len(api_key) == 0: api_key = profile_api_key if site is None: site = os.environ.get(citr_env_vars.CITRINATION_SITE) if site is None or len(site) == 0: site = profile_site if site is None: site = "https://citrination.com" return api_key, site
def upload(self, dataset_id, source_path, dest_path=None): """ Upload a file, specifying source and dest paths a file (acts as the scp command).asdfasdf :param source_path: The path to the file on the source host asdf :type source_path: str :param dest_path: The path to the file where the contents of the upload will be written (on the dest host) :type dest_path: str :return: The result of the upload process :rtype: :class:`UploadResult` """ upload_result = UploadResult() source_path = str(source_path) if not dest_path: dest_path = source_path else: dest_path = str(dest_path) if os.path.isdir(source_path): for path, subdirs, files in os.walk(source_path): relative_path = os.path.relpath(path, source_path) current_dest_prefix = dest_path if relative_path is not ".": current_dest_prefix = os.path.join(current_dest_prefix, relative_path) for name in files: current_dest_path = os.path.join(current_dest_prefix, name) current_source_path = os.path.join(path, name) try: if self.upload(dataset_id, current_source_path, current_dest_path).successful(): upload_result.add_success(current_source_path) else: upload_result.add_failure(current_source_path,"Upload failure") except (CitrinationClientError, ValueError) as e: upload_result.add_failure(current_source_path, str(e)) return upload_result elif os.path.isfile(source_path): file_data = { "dest_path": str(dest_path), "src_path": str(source_path)} j = self._get_success_json(self._post_json(routes.upload_to_dataset(dataset_id), data=file_data)) s3url = _get_s3_presigned_url(j) with open(source_path, 'rb') as f: if os.stat(source_path).st_size == 0: # Upload a null character as a placeholder for # the empty file since Citrination does not support # truly empty files data = "\0" else: data = f r = requests.put(s3url, data=data, headers=j["required_headers"]) if r.status_code == 200: data = {'s3object': j['url']['path'], 's3bucket': j['bucket']} self._post_json(routes.update_file(j['file_id']), data=data) upload_result.add_success(source_path) return upload_result else: raise CitrinationClientError("Failure to upload {} to Citrination".format(source_path)) else: raise ValueError("No file at specified path {}".format(source_path))
def list_files(self, dataset_id, glob=".", is_dir=False): """ List matched filenames in a dataset on Citrination. :param dataset_id: The ID of the dataset to search for files. :type dataset_id: int :param glob: A pattern which will be matched against files in the dataset. :type glob: str :param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset. :type is_dir: bool :return: A list of filepaths in the dataset matching the provided glob. :rtype: list of strings """ data = { "list": { "glob": glob, "isDir": is_dir } } return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message="Failed to list files for dataset {}".format(dataset_id)))['files']