INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Copy an empty Revoked object repeatedly. The copy is not garbage collected therefore it needs to be manually freed.
def check_X509_REVOKED_dup(self): """ Copy an empty Revoked object repeatedly. The copy is not garbage collected, therefore it needs to be manually freed. """ for i in xrange(self.iterations * 100): revoked_copy = _X509_REVOKED_dup(Revoked()._revoked) _lib.X509_REVOKED_free(revoked_copy)
Repeatedly create an EC_KEY * from an: py: obj: _EllipticCurve. The structure should be automatically garbage collected.
def check_to_EC_KEY(self): """ Repeatedly create an EC_KEY* from an :py:obj:`_EllipticCurve`. The structure should be automatically garbage collected. """ curves = get_elliptic_curves() if curves: curve = next(iter(curves)) for i in xrange(self.iterations * 1000): curve._to_EC_KEY()
Connect to an SNI - enabled server and request a specific hostname specified by argv [ 1 ] of it.
def main(): """ Connect to an SNI-enabled server and request a specific hostname, specified by argv[1], of it. """ if len(argv) < 2: print('Usage: %s <hostname>' % (argv[0],)) return 1 client = socket() print('Connecting...', end="") stdout.flush() client.connect(('127.0.0.1', 8443)) print('connected', client.getpeername()) client_ssl = Connection(Context(TLSv1_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name(argv[1]) client_ssl.do_handshake() print('Server subject is', client_ssl.get_peer_certificate().get_subject()) client_ssl.close()
Create a public/ private key pair.
def createKeyPair(type, bits): """ Create a public/private key pair. Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA bits - Number of bits to use in the key Returns: The public/private key pair in a PKey object """ pkey = crypto.PKey() pkey.generate_key(type, bits) return pkey
Create a certificate request.
def createCertRequest(pkey, digest="sha256", **name): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object """ req = crypto.X509Req() subj = req.get_subject() for key, value in name.items(): setattr(subj, key, value) req.set_pubkey(pkey) req.sign(pkey, digest) return req
Generate a certificate given a certificate request.
def createCertificate(req, issuerCertKey, serial, validityPeriod, digest="sha256"): """ Generate a certificate given a certificate request. Arguments: req - Certificate request to use issuerCert - The certificate of the issuer issuerKey - The private key of the issuer serial - Serial number for the certificate notBefore - Timestamp (relative to now) when the certificate starts being valid notAfter - Timestamp (relative to now) when the certificate stops being valid digest - Digest method to use for signing, default is sha256 Returns: The signed certificate in an X509 object """ issuerCert, issuerKey = issuerCertKey notBefore, notAfter = validityPeriod cert = crypto.X509() cert.set_serial_number(serial) cert.gmtime_adj_notBefore(notBefore) cert.gmtime_adj_notAfter(notAfter) cert.set_issuer(issuerCert.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(issuerKey, digest) return cert
Builds a decorator that ensures that functions that rely on OpenSSL functions that are not present in this build raise NotImplementedError rather than AttributeError coming out of cryptography.
def _make_requires(flag, error): """ Builds a decorator that ensures that functions that rely on OpenSSL functions that are not present in this build raise NotImplementedError, rather than AttributeError coming out of cryptography. :param flag: A cryptography flag that guards the functions, e.g. ``Cryptography_HAS_NEXTPROTONEG``. :param error: The string to be used in the exception if the flag is false. """ def _requires_decorator(func): if not flag: @wraps(func) def explode(*args, **kwargs): raise NotImplementedError(error) return explode else: return func return _requires_decorator
Let SSL know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format.
def load_verify_locations(self, cafile, capath=None): """ Let SSL know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format. If capath is passed, it must be a directory prepared using the ``c_rehash`` tool included with OpenSSL. Either, but not both, of *pemfile* or *capath* may be :data:`None`. :param cafile: In which file we can find the certificates (``bytes`` or ``unicode``). :param capath: In which directory we can find the certificates (``bytes`` or ``unicode``). :return: None """ if cafile is None: cafile = _ffi.NULL else: cafile = _path_string(cafile) if capath is None: capath = _ffi.NULL else: capath = _path_string(capath) load_result = _lib.SSL_CTX_load_verify_locations( self._context, cafile, capath ) if not load_result: _raise_current_error()
Set the passphrase callback. This function will be called when a private key with a passphrase is loaded.
def set_passwd_cb(self, callback, userdata=None): """ Set the passphrase callback. This function will be called when a private key with a passphrase is loaded. :param callback: The Python callback to use. This must accept three positional arguments. First, an integer giving the maximum length of the passphrase it may return. If the returned passphrase is longer than this, it will be truncated. Second, a boolean value which will be true if the user should be prompted for the passphrase twice and the callback should verify that the two values supplied are equal. Third, the value given as the *userdata* parameter to :meth:`set_passwd_cb`. The *callback* must return a byte string. If an error occurs, *callback* should return a false value (e.g. an empty string). :param userdata: (optional) A Python object which will be given as argument to the callback :return: None """ if not callable(callback): raise TypeError("callback must be callable") self._passphrase_helper = self._wrap_callback(callback) self._passphrase_callback = self._passphrase_helper.callback _lib.SSL_CTX_set_default_passwd_cb( self._context, self._passphrase_callback) self._passphrase_userdata = userdata
Specify that the platform provided CA certificates are to be used for verification purposes. This method has some caveats related to the binary wheels that cryptography ( pyOpenSSL s primary dependency ) ships:
def set_default_verify_paths(self): """ Specify that the platform provided CA certificates are to be used for verification purposes. This method has some caveats related to the binary wheels that cryptography (pyOpenSSL's primary dependency) ships: * macOS will only load certificates using this method if the user has the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed in the default location. * Windows will not work. * manylinux1 cryptography wheels will work on most common Linux distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the manylinux1 wheel and attempts to load roots via a fallback path. :return: None """ # SSL_CTX_set_default_verify_paths will attempt to load certs from # both a cafile and capath that are set at compile time. However, # it will first check environment variables and, if present, load # those paths instead set_result = _lib.SSL_CTX_set_default_verify_paths(self._context) _openssl_assert(set_result == 1) # After attempting to set default_verify_paths we need to know whether # to go down the fallback path. # First we'll check to see if any env vars have been set. If so, # we won't try to do anything else because the user has set the path # themselves. dir_env_var = _ffi.string( _lib.X509_get_default_cert_dir_env() ).decode("ascii") file_env_var = _ffi.string( _lib.X509_get_default_cert_file_env() ).decode("ascii") if not self._check_env_vars_set(dir_env_var, file_env_var): default_dir = _ffi.string(_lib.X509_get_default_cert_dir()) default_file = _ffi.string(_lib.X509_get_default_cert_file()) # Now we check to see if the default_dir and default_file are set # to the exact values we use in our manylinux1 builds. If they are # then we know to load the fallbacks if ( default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE ): # This is manylinux1, let's load our fallback paths self._fallback_default_verify_paths( _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS )
Check to see if the default cert dir/ file environment vars are present.
def _check_env_vars_set(self, dir_env_var, file_env_var): """ Check to see if the default cert dir/file environment vars are present. :return: bool """ return ( os.environ.get(file_env_var) is not None or os.environ.get(dir_env_var) is not None )
Default verify paths are based on the compiled version of OpenSSL. However when pyca/ cryptography is compiled as a manylinux1 wheel that compiled location can potentially be wrong. So like Go we will try a predefined set of paths and attempt to load roots from there.
def _fallback_default_verify_paths(self, file_path, dir_path): """ Default verify paths are based on the compiled version of OpenSSL. However, when pyca/cryptography is compiled as a manylinux1 wheel that compiled location can potentially be wrong. So, like Go, we will try a predefined set of paths and attempt to load roots from there. :return: None """ for cafile in file_path: if os.path.isfile(cafile): self.load_verify_locations(cafile) break for capath in dir_path: if os.path.isdir(capath): self.load_verify_locations(None, capath) break
Load a certificate chain from a file.
def use_certificate_chain_file(self, certfile): """ Load a certificate chain from a file. :param certfile: The name of the certificate chain file (``bytes`` or ``unicode``). Must be PEM encoded. :return: None """ certfile = _path_string(certfile) result = _lib.SSL_CTX_use_certificate_chain_file( self._context, certfile ) if not result: _raise_current_error()
Load a certificate from a file
def use_certificate_file(self, certfile, filetype=FILETYPE_PEM): """ Load a certificate from a file :param certfile: The name of the certificate file (``bytes`` or ``unicode``). :param filetype: (optional) The encoding of the file, which is either :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is :const:`FILETYPE_PEM`. :return: None """ certfile = _path_string(certfile) if not isinstance(filetype, integer_types): raise TypeError("filetype must be an integer") use_result = _lib.SSL_CTX_use_certificate_file( self._context, certfile, filetype ) if not use_result: _raise_current_error()
Load a certificate from a X509 object
def use_certificate(self, cert): """ Load a certificate from a X509 object :param cert: The X509 object :return: None """ if not isinstance(cert, X509): raise TypeError("cert must be an X509 instance") use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509) if not use_result: _raise_current_error()
Add certificate to chain
def add_extra_chain_cert(self, certobj): """ Add certificate to chain :param certobj: The X509 certificate object to add to the chain :return: None """ if not isinstance(certobj, X509): raise TypeError("certobj must be an X509 instance") copy = _lib.X509_dup(certobj._x509) add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy) if not add_result: # TODO: This is untested. _lib.X509_free(copy) _raise_current_error()
Load a private key from a file
def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED): """ Load a private key from a file :param keyfile: The name of the key file (``bytes`` or ``unicode``) :param filetype: (optional) The encoding of the file, which is either :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is :const:`FILETYPE_PEM`. :return: None """ keyfile = _path_string(keyfile) if filetype is _UNSPECIFIED: filetype = FILETYPE_PEM elif not isinstance(filetype, integer_types): raise TypeError("filetype must be an integer") use_result = _lib.SSL_CTX_use_PrivateKey_file( self._context, keyfile, filetype) if not use_result: self._raise_passphrase_exception()
Load a private key from a PKey object
def use_privatekey(self, pkey): """ Load a private key from a PKey object :param pkey: The PKey object :return: None """ if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey instance") use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey) if not use_result: self._raise_passphrase_exception()
Load the trusted certificates that will be sent to the client. Does not actually imply any of the certificates are trusted ; that must be configured separately.
def load_client_ca(self, cafile): """ Load the trusted certificates that will be sent to the client. Does not actually imply any of the certificates are trusted; that must be configured separately. :param bytes cafile: The path to a certificates file in PEM format. :return: None """ ca_list = _lib.SSL_load_client_CA_file( _text_to_bytes_and_warn("cafile", cafile) ) _openssl_assert(ca_list != _ffi.NULL) _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Set the session id to * buf * within which a session can be reused for this Context object. This is needed when doing session resumption because there is no way for a stored session to know which Context object it is associated with.
def set_session_id(self, buf): """ Set the session id to *buf* within which a session can be reused for this Context object. This is needed when doing session resumption, because there is no way for a stored session to know which Context object it is associated with. :param bytes buf: The session id. :returns: None """ buf = _text_to_bytes_and_warn("buf", buf) _openssl_assert( _lib.SSL_CTX_set_session_id_context( self._context, buf, len(buf), ) == 1 )
Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See: const: SESS_CACHE_ * for details about particular modes.
def set_session_cache_mode(self, mode): """ Set the behavior of the session cache used by all connections using this Context. The previously set mode is returned. See :const:`SESS_CACHE_*` for details about particular modes. :param mode: One or more of the SESS_CACHE_* flags (combine using bitwise or) :returns: The previously set caching mode. .. versionadded:: 0.14 """ if not isinstance(mode, integer_types): raise TypeError("mode must be an integer") return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
et the verification flags for this Context object to * mode * and specify that * callback * should be used for verification callbacks.
def set_verify(self, mode, callback): """ et the verification flags for this Context object to *mode* and specify that *callback* should be used for verification callbacks. :param mode: The verify mode, this should be one of :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If :const:`VERIFY_PEER` is used, *mode* can be OR:ed with :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and :const:`VERIFY_CLIENT_ONCE` to further control the behaviour. :param callback: The Python callback to use. This should take five arguments: A Connection object, an X509 object, and three integer variables, which are in turn potential error number, error depth and return code. *callback* should return True if verification passes and False otherwise. :return: None See SSL_CTX_set_verify(3SSL) for further details. """ if not isinstance(mode, integer_types): raise TypeError("mode must be an integer") if not callable(callback): raise TypeError("callback must be callable") self._verify_helper = _VerifyHelper(callback) self._verify_callback = self._verify_helper.callback _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Set the maximum depth for the certificate chain verification that shall be allowed for this Context object.
def set_verify_depth(self, depth): """ Set the maximum depth for the certificate chain verification that shall be allowed for this Context object. :param depth: An integer specifying the verify depth :return: None """ if not isinstance(depth, integer_types): raise TypeError("depth must be an integer") _lib.SSL_CTX_set_verify_depth(self._context, depth)
Load parameters for Ephemeral Diffie - Hellman
def load_tmp_dh(self, dhfile): """ Load parameters for Ephemeral Diffie-Hellman :param dhfile: The file to load EDH parameters from (``bytes`` or ``unicode``). :return: None """ dhfile = _path_string(dhfile) bio = _lib.BIO_new_file(dhfile, b"r") if bio == _ffi.NULL: _raise_current_error() bio = _ffi.gc(bio, _lib.BIO_free) dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) dh = _ffi.gc(dh, _lib.DH_free) _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Set the list of ciphers to be used in this context.
def set_cipher_list(self, cipher_list): """ Set the list of ciphers to be used in this context. See the OpenSSL manual for more information (e.g. :manpage:`ciphers(1)`). :param bytes cipher_list: An OpenSSL cipher string. :return: None """ cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list) if not isinstance(cipher_list, bytes): raise TypeError("cipher_list must be a byte string.") _openssl_assert( _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1 ) # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3 # ciphers even if you pass an invalid cipher. Applications (like # Twisted) have tests that depend on an error being raised if an # invalid cipher string is passed, but without the following check # for the TLS 1.3 specific cipher suites it would never error. tmpconn = Connection(self, None) if ( tmpconn.get_cipher_list() == [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256' ] ): raise Error( [ ( 'SSL routines', 'SSL_CTX_set_cipher_list', 'no cipher match', ), ], )
Set the list of preferred client certificate signers for this server context.
def set_client_ca_list(self, certificate_authorities): """ Set the list of preferred client certificate signers for this server context. This list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authorities: a sequence of X509Names. :return: None .. versionadded:: 0.10 """ name_stack = _lib.sk_X509_NAME_new_null() _openssl_assert(name_stack != _ffi.NULL) try: for ca_name in certificate_authorities: if not isinstance(ca_name, X509Name): raise TypeError( "client CAs must be X509Name objects, not %s " "objects" % ( type(ca_name).__name__, ) ) copy = _lib.X509_NAME_dup(ca_name._name) _openssl_assert(copy != _ffi.NULL) push_result = _lib.sk_X509_NAME_push(name_stack, copy) if not push_result: _lib.X509_NAME_free(copy) _raise_current_error() except Exception: _lib.sk_X509_NAME_free(name_stack) raise _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Add the CA certificate to the list of preferred signers for this context.
def add_client_ca(self, certificate_authority): """ Add the CA certificate to the list of preferred signers for this context. The list of certificate authorities will be sent to the client when the server requests a client certificate. :param certificate_authority: certificate authority's X509 certificate. :return: None .. versionadded:: 0.10 """ if not isinstance(certificate_authority, X509): raise TypeError("certificate_authority must be an X509 instance") add_result = _lib.SSL_CTX_add_client_CA( self._context, certificate_authority._x509) _openssl_assert(add_result == 1)
Set the timeout for newly created sessions for this Context object to * timeout *. The default value is 300 seconds. See the OpenSSL manual for more information ( e. g.: manpage: SSL_CTX_set_timeout ( 3 ) ).
def set_timeout(self, timeout): """ Set the timeout for newly created sessions for this Context object to *timeout*. The default value is 300 seconds. See the OpenSSL manual for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`). :param timeout: The timeout in (whole) seconds :return: The previous session timeout """ if not isinstance(timeout, integer_types): raise TypeError("timeout must be an integer") return _lib.SSL_CTX_set_timeout(self._context, timeout)
Set the information callback to * callback *. This function will be called from time to time during SSL handshakes.
def set_info_callback(self, callback): """ Set the information callback to *callback*. This function will be called from time to time during SSL handshakes. :param callback: The Python callback to use. This should take three arguments: a Connection object and two integers. The first integer specifies where in the SSL handshake the function was called, and the other the return code from a (possibly failed) internal function call. :return: None """ @wraps(callback) def wrapper(ssl, where, return_code): callback(Connection._reverse_mapping[ssl], where, return_code) self._info_callback = _ffi.callback( "void (*)(const SSL *, int, int)", wrapper) _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Get the certificate store for the context. This can be used to add trusted certificates without using the: meth: load_verify_locations method.
def get_cert_store(self): """ Get the certificate store for the context. This can be used to add "trusted" certificates without using the :meth:`load_verify_locations` method. :return: A X509Store object or None if it does not have one. """ store = _lib.SSL_CTX_get_cert_store(self._context) if store == _ffi.NULL: # TODO: This is untested. return None pystore = X509Store.__new__(X509Store) pystore._store = store return pystore
Add options. Options set before are not cleared! This method should be used with the: const: OP_ * constants.
def set_options(self, options): """ Add options. Options set before are not cleared! This method should be used with the :const:`OP_*` constants. :param options: The options to add. :return: The new option bitmask. """ if not isinstance(options, integer_types): raise TypeError("options must be an integer") return _lib.SSL_CTX_set_options(self._context, options)
Add modes via bitmask. Modes set before are not cleared! This method should be used with the: const: MODE_ * constants.
def set_mode(self, mode): """ Add modes via bitmask. Modes set before are not cleared! This method should be used with the :const:`MODE_*` constants. :param mode: The mode to add. :return: The new mode bitmask. """ if not isinstance(mode, integer_types): raise TypeError("mode must be an integer") return _lib.SSL_CTX_set_mode(self._context, mode)
Specify a callback function to be called when clients specify a server name.
def set_tlsext_servername_callback(self, callback): """ Specify a callback function to be called when clients specify a server name. :param callback: The callback function. It will be invoked with one argument, the Connection instance. .. versionadded:: 0.13 """ @wraps(callback) def wrapper(ssl, alert, arg): callback(Connection._reverse_mapping[ssl]) return 0 self._tlsext_servername_callback = _ffi.callback( "int (*)(SSL *, int *, void *)", wrapper) _lib.SSL_CTX_set_tlsext_servername_callback( self._context, self._tlsext_servername_callback)
Enable support for negotiating SRTP keying material.
def set_tlsext_use_srtp(self, profiles): """ Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None """ if not isinstance(profiles, bytes): raise TypeError("profiles must be a byte string.") _openssl_assert( _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0 )
Specify a callback function that will be called when offering Next Protocol Negotiation <https:// technotes. googlecode. com/ git/ nextprotoneg. html > _ as a server.
def set_npn_advertise_callback(self, callback): """ Specify a callback function that will be called when offering `Next Protocol Negotiation <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server. :param callback: The callback function. It will be invoked with one argument, the :class:`Connection` instance. It should return a list of bytestrings representing the advertised protocols, like ``[b'http/1.1', b'spdy/2']``. .. versionadded:: 0.15 """ _warn_npn() self._npn_advertise_helper = _NpnAdvertiseHelper(callback) self._npn_advertise_callback = self._npn_advertise_helper.callback _lib.SSL_CTX_set_next_protos_advertised_cb( self._context, self._npn_advertise_callback, _ffi.NULL)
Specify a callback function that will be called when a server offers Next Protocol Negotiation options.
def set_npn_select_callback(self, callback): """ Specify a callback function that will be called when a server offers Next Protocol Negotiation options. :param callback: The callback function. It will be invoked with two arguments: the Connection, and a list of offered protocols as bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return one of those bytestrings, the chosen protocol. .. versionadded:: 0.15 """ _warn_npn() self._npn_select_helper = _NpnSelectHelper(callback) self._npn_select_callback = self._npn_select_helper.callback _lib.SSL_CTX_set_next_proto_select_cb( self._context, self._npn_select_callback, _ffi.NULL)
Specify the protocols that the client is prepared to speak after the TLS connection has been negotiated using Application Layer Protocol Negotiation.
def set_alpn_protos(self, protos): """ Specify the protocols that the client is prepared to speak after the TLS connection has been negotiated using Application Layer Protocol Negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. """ # Take the list of protocols and join them together, prefixing them # with their lengths. protostr = b''.join( chain.from_iterable((int2byte(len(p)), p) for p in protos) ) # Build a C string from the list. We don't need to save this off # because OpenSSL immediately copies the data out. input_str = _ffi.new("unsigned char[]", protostr) _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Specify a callback function that will be called on the server when a client offers protocols using ALPN.
def set_alpn_select_callback(self, callback): """ Specify a callback function that will be called on the server when a client offers protocols using ALPN. :param callback: The callback function. It will be invoked with two arguments: the Connection, and a list of offered protocols as bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return one of those bytestrings, the chosen protocol. """ self._alpn_select_helper = _ALPNSelectHelper(callback) self._alpn_select_callback = self._alpn_select_helper.callback _lib.SSL_CTX_set_alpn_select_cb( self._context, self._alpn_select_callback, _ffi.NULL)
This internal helper does the common work for set_ocsp_server_callback and set_ocsp_client_callback which is almost all of it.
def _set_ocsp_callback(self, helper, data): """ This internal helper does the common work for ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is almost all of it. """ self._ocsp_helper = helper self._ocsp_callback = helper.callback if data is None: self._ocsp_data = _ffi.NULL else: self._ocsp_data = _ffi.new_handle(data) rc = _lib.SSL_CTX_set_tlsext_status_cb( self._context, self._ocsp_callback ) _openssl_assert(rc == 1) rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data) _openssl_assert(rc == 1)
Set a callback to provide OCSP data to be stapled to the TLS handshake on the server side.
def set_ocsp_server_callback(self, callback, data=None): """ Set a callback to provide OCSP data to be stapled to the TLS handshake on the server side. :param callback: The callback function. It will be invoked with two arguments: the Connection, and the optional arbitrary data you have provided. The callback must return a bytestring that contains the OCSP data to staple to the handshake. If no OCSP data is available for this connection, return the empty bytestring. :param data: Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional. """ helper = _OCSPServerCallbackHelper(callback) self._set_ocsp_callback(helper, data)
Set a callback to validate OCSP data stapled to the TLS handshake on the client side.
def set_ocsp_client_callback(self, callback, data=None): """ Set a callback to validate OCSP data stapled to the TLS handshake on the client side. :param callback: The callback function. It will be invoked with three arguments: the Connection, a bytestring containing the stapled OCSP assertion, and the optional arbitrary data you have provided. The callback must return a boolean that indicates the result of validating the OCSP data: ``True`` if the OCSP data is valid and the certificate can be trusted, or ``False`` if either the OCSP data is invalid or the certificate has been revoked. :param data: Some opaque data that will be passed into the callback function when called. This can be used to avoid needing to do complex data lookups or to keep track of what context is being used. This parameter is optional. """ helper = _OCSPClientCallbackHelper(callback) self._set_ocsp_callback(helper, data)
Switch this connection to a new session context.
def set_context(self, context): """ Switch this connection to a new session context. :param context: A :class:`Context` instance giving the new session context to use. """ if not isinstance(context, Context): raise TypeError("context must be a Context instance") _lib.SSL_set_SSL_CTX(self._ssl, context._context) self._context = context
Retrieve the servername extension value if provided in the client hello message or None if there wasn t one.
def get_servername(self): """ Retrieve the servername extension value if provided in the client hello message, or None if there wasn't one. :return: A byte string giving the server name or :data:`None`. .. versionadded:: 0.13 """ name = _lib.SSL_get_servername( self._ssl, _lib.TLSEXT_NAMETYPE_host_name ) if name == _ffi.NULL: return None return _ffi.string(name)
Set the value of the servername extension to send in the client hello.
def set_tlsext_host_name(self, name): """ Set the value of the servername extension to send in the client hello. :param name: A byte string giving the name. .. versionadded:: 0.13 """ if not isinstance(name, bytes): raise TypeError("name must be a byte string") elif b"\0" in name: raise TypeError("name must not contain NUL byte") # XXX I guess this can fail sometimes? _lib.SSL_set_tlsext_host_name(self._ssl, name)
Send data on the connection. NOTE: If you get one of the WantRead WantWrite or WantX509Lookup exceptions on this you have to call the method again with the SAME buffer.
def send(self, buf, flags=0): """ Send data on the connection. NOTE: If you get one of the WantRead, WantWrite or WantX509Lookup exceptions on this, you have to call the method again with the SAME buffer. :param buf: The string, buffer or memoryview to send :param flags: (optional) Included for compatibility with the socket API, the value is ignored :return: The number of bytes written """ # Backward compatibility buf = _text_to_bytes_and_warn("buf", buf) if isinstance(buf, memoryview): buf = buf.tobytes() if isinstance(buf, _buffer): buf = str(buf) if not isinstance(buf, bytes): raise TypeError("data must be a memoryview, buffer or byte string") if len(buf) > 2147483647: raise ValueError("Cannot send more than 2**31-1 bytes at once.") result = _lib.SSL_write(self._ssl, buf, len(buf)) self._raise_ssl_error(self._ssl, result) return result
Send all data on the connection. This calls send () repeatedly until all data is sent. If an error occurs it s impossible to tell how much data has been sent.
def sendall(self, buf, flags=0): """ Send "all" data on the connection. This calls send() repeatedly until all data is sent. If an error occurs, it's impossible to tell how much data has been sent. :param buf: The string, buffer or memoryview to send :param flags: (optional) Included for compatibility with the socket API, the value is ignored :return: The number of bytes written """ buf = _text_to_bytes_and_warn("buf", buf) if isinstance(buf, memoryview): buf = buf.tobytes() if isinstance(buf, _buffer): buf = str(buf) if not isinstance(buf, bytes): raise TypeError("buf must be a memoryview, buffer or byte string") left_to_send = len(buf) total_sent = 0 data = _ffi.new("char[]", buf) while left_to_send: # SSL_write's num arg is an int, # so we cannot send more than 2**31-1 bytes at once. result = _lib.SSL_write( self._ssl, data + total_sent, min(left_to_send, 2147483647) ) self._raise_ssl_error(self._ssl, result) total_sent += result left_to_send -= result
Receive data on the connection.
def recv(self, bufsiz, flags=None): """ Receive data on the connection. :param bufsiz: The maximum number of bytes to read :param flags: (optional) The only supported flag is ``MSG_PEEK``, all other flags are ignored. :return: The string read from the Connection """ buf = _no_zero_allocator("char[]", bufsiz) if flags is not None and flags & socket.MSG_PEEK: result = _lib.SSL_peek(self._ssl, buf, bufsiz) else: result = _lib.SSL_read(self._ssl, buf, bufsiz) self._raise_ssl_error(self._ssl, result) return _ffi.buffer(buf, result)[:]
Receive data on the connection and copy it directly into the provided buffer rather than creating a new string.
def recv_into(self, buffer, nbytes=None, flags=None): """ Receive data on the connection and copy it directly into the provided buffer, rather than creating a new string. :param buffer: The buffer to copy into. :param nbytes: (optional) The maximum number of bytes to read into the buffer. If not present, defaults to the size of the buffer. If larger than the size of the buffer, is reduced to the size of the buffer. :param flags: (optional) The only supported flag is ``MSG_PEEK``, all other flags are ignored. :return: The number of bytes read into the buffer. """ if nbytes is None: nbytes = len(buffer) else: nbytes = min(nbytes, len(buffer)) # We need to create a temporary buffer. This is annoying, it would be # better if we could pass memoryviews straight into the SSL_read call, # but right now we can't. Revisit this if CFFI gets that ability. buf = _no_zero_allocator("char[]", nbytes) if flags is not None and flags & socket.MSG_PEEK: result = _lib.SSL_peek(self._ssl, buf, nbytes) else: result = _lib.SSL_read(self._ssl, buf, nbytes) self._raise_ssl_error(self._ssl, result) # This strange line is all to avoid a memory copy. The buffer protocol # should allow us to assign a CFFI buffer to the LHS of this line, but # on CPython 3.3+ that segfaults. As a workaround, we can temporarily # wrap it in a memoryview. buffer[:result] = memoryview(_ffi.buffer(buf, result)) return result
If the Connection was created with a memory BIO this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions.
def bio_read(self, bufsiz): """ If the Connection was created with a memory BIO, this method can be used to read bytes from the write end of that memory BIO. Many Connection methods will add bytes which must be read in this manner or the buffer will eventually fill up and the Connection will be able to take no further actions. :param bufsiz: The maximum number of bytes to read :return: The string read. """ if self._from_ssl is None: raise TypeError("Connection sock was not None") if not isinstance(bufsiz, integer_types): raise TypeError("bufsiz must be an integer") buf = _no_zero_allocator("char[]", bufsiz) result = _lib.BIO_read(self._from_ssl, buf, bufsiz) if result <= 0: self._handle_bio_errors(self._from_ssl, result) return _ffi.buffer(buf, result)[:]
If the Connection was created with a memory BIO this method can be used to add bytes to the read end of that memory BIO. The Connection can then read the bytes ( for example in response to a call to: meth: recv ).
def bio_write(self, buf): """ If the Connection was created with a memory BIO, this method can be used to add bytes to the read end of that memory BIO. The Connection can then read the bytes (for example, in response to a call to :meth:`recv`). :param buf: The string to put into the memory BIO. :return: The number of bytes written """ buf = _text_to_bytes_and_warn("buf", buf) if self._into_ssl is None: raise TypeError("Connection sock was not None") result = _lib.BIO_write(self._into_ssl, buf, len(buf)) if result <= 0: self._handle_bio_errors(self._into_ssl, result) return result
Renegotiate the session.
def renegotiate(self): """ Renegotiate the session. :return: True if the renegotiation can be started, False otherwise :rtype: bool """ if not self.renegotiate_pending(): _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1) return True return False
Perform an SSL handshake ( usually called after: meth: renegotiate or one of: meth: set_accept_state or: meth: set_accept_state ). This can raise the same exceptions as: meth: send and: meth: recv.
def do_handshake(self): """ Perform an SSL handshake (usually called after :meth:`renegotiate` or one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can raise the same exceptions as :meth:`send` and :meth:`recv`. :return: None. """ result = _lib.SSL_do_handshake(self._ssl) self._raise_ssl_error(self._ssl, result)
Call the: meth: connect method of the underlying socket and set up SSL on the socket using the: class: Context object supplied to this: class: Connection object at creation.
def connect(self, addr): """ Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: What the socket's connect method returns """ _lib.SSL_set_connect_state(self._ssl) return self._socket.connect(addr)
Call the: meth: connect_ex method of the underlying socket and set up SSL on the socket using the Context object supplied to this Connection object at creation. Note that if the: meth: connect_ex method of the socket doesn t return 0 SSL won t be initialized.
def connect_ex(self, addr): """ Call the :meth:`connect_ex` method of the underlying socket and set up SSL on the socket, using the Context object supplied to this Connection object at creation. Note that if the :meth:`connect_ex` method of the socket doesn't return 0, SSL won't be initialized. :param addr: A remove address :return: What the socket's connect_ex method returns """ connect_ex = self._socket.connect_ex self.set_connect_state() return connect_ex(addr)
Call the: meth: accept method of the underlying socket and set up SSL on the returned socket using the Context object supplied to this: class: Connection object at creation.
def accept(self): """ Call the :meth:`accept` method of the underlying socket and set up SSL on the returned socket, using the Context object supplied to this :class:`Connection` object at creation. :return: A *(conn, addr)* pair where *conn* is the new :class:`Connection` object created, and *address* is as returned by the socket's :meth:`accept`. """ client, addr = self._socket.accept() conn = Connection(self._context, client) conn.set_accept_state() return (conn, addr)
Send the shutdown message to the Connection.
def shutdown(self): """ Send the shutdown message to the Connection. :return: True if the shutdown completed successfully (i.e. both sides have sent closure alerts), False otherwise (in which case you call :meth:`recv` or :meth:`send` when the connection becomes readable/writeable). """ result = _lib.SSL_shutdown(self._ssl) if result < 0: self._raise_ssl_error(self._ssl, result) elif result > 0: return True else: return False
Retrieve the list of ciphers used by the Connection object.
def get_cipher_list(self): """ Retrieve the list of ciphers used by the Connection object. :return: A list of native cipher strings. """ ciphers = [] for i in count(): result = _lib.SSL_get_cipher_list(self._ssl, i) if result == _ffi.NULL: break ciphers.append(_native(_ffi.string(result))) return ciphers
Get CAs whose certificates are suggested for client authentication.
def get_client_ca_list(self): """ Get CAs whose certificates are suggested for client authentication. :return: If this is a server connection, the list of certificate authorities that will be sent or has been sent to the client, as controlled by this :class:`Connection`'s :class:`Context`. If this is a client connection, the list will be empty until the connection with the server is established. .. versionadded:: 0.10 """ ca_names = _lib.SSL_get_client_CA_list(self._ssl) if ca_names == _ffi.NULL: # TODO: This is untested. return [] result = [] for i in range(_lib.sk_X509_NAME_num(ca_names)): name = _lib.sk_X509_NAME_value(ca_names, i) copy = _lib.X509_NAME_dup(name) _openssl_assert(copy != _ffi.NULL) pyname = X509Name.__new__(X509Name) pyname._name = _ffi.gc(copy, _lib.X509_NAME_free) result.append(pyname) return result
Set the shutdown state of the Connection.
def set_shutdown(self, state): """ Set the shutdown state of the Connection. :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN. :return: None """ if not isinstance(state, integer_types): raise TypeError("state must be an integer") _lib.SSL_set_shutdown(self._ssl, state)
Retrieve the random value used with the server hello message.
def server_random(self): """ Retrieve the random value used with the server hello message. :return: A string representing the state """ session = _lib.SSL_get_session(self._ssl) if session == _ffi.NULL: return None length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0) assert length > 0 outp = _no_zero_allocator("unsigned char[]", length) _lib.SSL_get_server_random(self._ssl, outp, length) return _ffi.buffer(outp, length)[:]
Retrieve the random value used with the client hello message.
def client_random(self): """ Retrieve the random value used with the client hello message. :return: A string representing the state """ session = _lib.SSL_get_session(self._ssl) if session == _ffi.NULL: return None length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0) assert length > 0 outp = _no_zero_allocator("unsigned char[]", length) _lib.SSL_get_client_random(self._ssl, outp, length) return _ffi.buffer(outp, length)[:]
Retrieve the value of the master key for this session.
def master_key(self): """ Retrieve the value of the master key for this session. :return: A string representing the state """ session = _lib.SSL_get_session(self._ssl) if session == _ffi.NULL: return None length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0) assert length > 0 outp = _no_zero_allocator("unsigned char[]", length) _lib.SSL_SESSION_get_master_key(session, outp, length) return _ffi.buffer(outp, length)[:]
Obtain keying material for application use.
def export_keying_material(self, label, olen, context=None): """ Obtain keying material for application use. :param: label - a disambiguating label string as described in RFC 5705 :param: olen - the length of the exported key material in bytes :param: context - a per-association context value :return: the exported key material bytes or None """ outp = _no_zero_allocator("unsigned char[]", olen) context_buf = _ffi.NULL context_len = 0 use_context = 0 if context is not None: context_buf = context context_len = len(context) use_context = 1 success = _lib.SSL_export_keying_material(self._ssl, outp, olen, label, len(label), context_buf, context_len, use_context) _openssl_assert(success == 1) return _ffi.buffer(outp, olen)[:]
Retrieve the local certificate ( if any )
def get_certificate(self): """ Retrieve the local certificate (if any) :return: The local certificate """ cert = _lib.SSL_get_certificate(self._ssl) if cert != _ffi.NULL: _lib.X509_up_ref(cert) return X509._from_raw_x509_ptr(cert) return None
Retrieve the other side s certificate ( if any )
def get_peer_certificate(self): """ Retrieve the other side's certificate (if any) :return: The peer's certificate """ cert = _lib.SSL_get_peer_certificate(self._ssl) if cert != _ffi.NULL: return X509._from_raw_x509_ptr(cert) return None
Retrieve the other side s certificate ( if any )
def get_peer_cert_chain(self): """ Retrieve the other side's certificate (if any) :return: A list of X509 instances giving the peer's certificate chain, or None if it does not have one. """ cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl) if cert_stack == _ffi.NULL: return None result = [] for i in range(_lib.sk_X509_num(cert_stack)): # TODO could incref instead of dup here cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i)) pycert = X509._from_raw_x509_ptr(cert) result.append(pycert) return result
Returns the Session currently used.
def get_session(self): """ Returns the Session currently used. :return: An instance of :class:`OpenSSL.SSL.Session` or :obj:`None` if no session exists. .. versionadded:: 0.14 """ session = _lib.SSL_get1_session(self._ssl) if session == _ffi.NULL: return None pysession = Session.__new__(Session) pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free) return pysession
Set the session to be used when the TLS/ SSL connection is established.
def set_session(self, session): """ Set the session to be used when the TLS/SSL connection is established. :param session: A Session instance representing the session to use. :returns: None .. versionadded:: 0.14 """ if not isinstance(session, Session): raise TypeError("session must be a Session instance") result = _lib.SSL_set_session(self._ssl, session._session) if not result: _raise_current_error()
Helper to implement: meth: get_finished and: meth: get_peer_finished.
def _get_finished_message(self, function): """ Helper to implement :meth:`get_finished` and :meth:`get_peer_finished`. :param function: Either :data:`SSL_get_finished`: or :data:`SSL_get_peer_finished`. :return: :data:`None` if the desired message has not yet been received, otherwise the contents of the message. :rtype: :class:`bytes` or :class:`NoneType` """ # The OpenSSL documentation says nothing about what might happen if the # count argument given is zero. Specifically, it doesn't say whether # the output buffer may be NULL in that case or not. Inspection of the # implementation reveals that it calls memcpy() unconditionally. # Section 7.1.4, paragraph 1 of the C standard suggests that # memcpy(NULL, source, 0) is not guaranteed to produce defined (let # alone desirable) behavior (though it probably does on just about # every implementation...) # # Allocate a tiny buffer to pass in (instead of just passing NULL as # one might expect) for the initial call so as to be safe against this # potentially undefined behavior. empty = _ffi.new("char[]", 0) size = function(self._ssl, empty, 0) if size == 0: # No Finished message so far. return None buf = _no_zero_allocator("char[]", size) function(self._ssl, buf, size) return _ffi.buffer(buf, size)[:]
Obtain the name of the currently used cipher.
def get_cipher_name(self): """ Obtain the name of the currently used cipher. :returns: The name of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`unicode` or :class:`NoneType` .. versionadded:: 0.15 """ cipher = _lib.SSL_get_current_cipher(self._ssl) if cipher == _ffi.NULL: return None else: name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher)) return name.decode("utf-8")
Obtain the number of secret bits of the currently used cipher.
def get_cipher_bits(self): """ Obtain the number of secret bits of the currently used cipher. :returns: The number of secret bits of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`int` or :class:`NoneType` .. versionadded:: 0.15 """ cipher = _lib.SSL_get_current_cipher(self._ssl) if cipher == _ffi.NULL: return None else: return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
Obtain the protocol version of the currently used cipher.
def get_cipher_version(self): """ Obtain the protocol version of the currently used cipher. :returns: The protocol name of the currently used cipher or :obj:`None` if no connection has been established. :rtype: :class:`unicode` or :class:`NoneType` .. versionadded:: 0.15 """ cipher = _lib.SSL_get_current_cipher(self._ssl) if cipher == _ffi.NULL: return None else: version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher)) return version.decode("utf-8")
Retrieve the protocol version of the current connection.
def get_protocol_version_name(self): """ Retrieve the protocol version of the current connection. :returns: The TLS version of the current connection, for example the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown`` for connections that were not successfully established. :rtype: :class:`unicode` """ version = _ffi.string(_lib.SSL_get_version(self._ssl)) return version.decode("utf-8")
Get the protocol that was negotiated by NPN.
def get_next_proto_negotiated(self): """ Get the protocol that was negotiated by NPN. :returns: A bytestring of the protocol name. If no protocol has been negotiated yet, returns an empty string. .. versionadded:: 0.15 """ _warn_npn() data = _ffi.new("unsigned char **") data_len = _ffi.new("unsigned int *") _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len) return _ffi.buffer(data[0], data_len[0])[:]
Specify the client s ALPN protocol list.
def set_alpn_protos(self, protos): """ Specify the client's ALPN protocol list. These protocols are offered to the server during protocol negotiation. :param protos: A list of the protocols to be offered to the server. This list should be a Python list of bytestrings representing the protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``. """ # Take the list of protocols and join them together, prefixing them # with their lengths. protostr = b''.join( chain.from_iterable((int2byte(len(p)), p) for p in protos) ) # Build a C string from the list. We don't need to save this off # because OpenSSL immediately copies the data out. input_str = _ffi.new("unsigned char[]", protostr) _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Get the protocol that was negotiated by ALPN.
def get_alpn_proto_negotiated(self): """ Get the protocol that was negotiated by ALPN. :returns: A bytestring of the protocol name. If no protocol has been negotiated yet, returns an empty string. """ data = _ffi.new("unsigned char **") data_len = _ffi.new("unsigned int *") _lib.SSL_get0_alpn_selected(self._ssl, data, data_len) if not data_len: return b'' return _ffi.buffer(data[0], data_len[0])[:]
Called to request that the server sends stapled OCSP data if available. If this is not called on the client side then the server will not send OCSP data. Should be used in conjunction with: meth: Context. set_ocsp_client_callback.
def request_ocsp(self): """ Called to request that the server sends stapled OCSP data, if available. If this is not called on the client side then the server will not send OCSP data. Should be used in conjunction with :meth:`Context.set_ocsp_client_callback`. """ rc = _lib.SSL_set_tlsext_status_type( self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp ) _openssl_assert(rc == 1)
Allocate a new OpenSSL memory BIO.
def _new_mem_buf(buffer=None): """ Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out. """ if buffer is None: bio = _lib.BIO_new(_lib.BIO_s_mem()) free = _lib.BIO_free else: data = _ffi.new("char[]", buffer) bio = _lib.BIO_new_mem_buf(data, len(buffer)) # Keep the memory alive as long as the bio is alive! def free(bio, ref=data): return _lib.BIO_free(bio) _openssl_assert(bio != _ffi.NULL) bio = _ffi.gc(bio, free) return bio
Copy the contents of an OpenSSL BIO object into a Python byte string.
def _bio_to_string(bio): """ Copy the contents of an OpenSSL BIO object into a Python byte string. """ result_buffer = _ffi.new('char**') buffer_length = _lib.BIO_get_mem_data(bio, result_buffer) return _ffi.buffer(result_buffer[0], buffer_length)[:]
The the time value of an ASN1 time object.
def _set_asn1_time(boundary, when): """ The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason. """ if not isinstance(when, bytes): raise TypeError("when must be a byte string") set_result = _lib.ASN1_TIME_set_string(boundary, when) if set_result == 0: raise ValueError("Invalid string")
Retrieve the time value of an ASN1 time object.
def _get_asn1_time(timestamp): """ Retrieve the time value of an ASN1 time object. @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to that type) from which the time value will be retrieved. @return: The time value from C{timestamp} as a L{bytes} string in a certain format. Or C{None} if the object contains no time value. """ string_timestamp = _ffi.cast('ASN1_STRING*', timestamp) if _lib.ASN1_STRING_length(string_timestamp) == 0: return None elif ( _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME ): return _ffi.string(_lib.ASN1_STRING_data(string_timestamp)) else: generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**") _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp) if generalized_timestamp[0] == _ffi.NULL: # This may happen: # - if timestamp was not an ASN1_TIME # - if allocating memory for the ASN1_GENERALIZEDTIME failed # - if a copy of the time data from timestamp cannot be made for # the newly allocated ASN1_GENERALIZEDTIME # # These are difficult to test. cffi enforces the ASN1_TIME type. # Memory allocation failures are a pain to trigger # deterministically. _untested_error("ASN1_TIME_to_generalizedtime") else: string_timestamp = _ffi.cast( "ASN1_STRING*", generalized_timestamp[0]) string_data = _lib.ASN1_STRING_data(string_timestamp) string_result = _ffi.string(string_data) _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0]) return string_result
Return a single curve object selected by name.
def get_elliptic_curve(name): """ Return a single curve object selected by name. See :py:func:`get_elliptic_curves` for information about curve objects. :param name: The OpenSSL short name identifying the curve object to retrieve. :type name: :py:class:`unicode` If the named curve is not supported then :py:class:`ValueError` is raised. """ for curve in get_elliptic_curves(): if curve.name == name: return curve raise ValueError("unknown curve name", name)
Load a certificate ( X509 ) from the string * buffer * encoded with the type * type *.
def load_certificate(type, buffer): """ Load a certificate (X509) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param bytes buffer: The buffer the certificate is stored in :return: The X509 object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: x509 = _lib.d2i_X509_bio(bio, _ffi.NULL) else: raise ValueError( "type argument must be FILETYPE_PEM or FILETYPE_ASN1") if x509 == _ffi.NULL: _raise_current_error() return X509._from_raw_x509_ptr(x509)
Dump the certificate * cert * into a buffer string encoded with the type * type *.
def dump_certificate(type, cert): """ Dump the certificate *cert* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT) :param cert: The certificate to dump :return: The buffer with the dumped certificate in """ bio = _new_mem_buf() if type == FILETYPE_PEM: result_code = _lib.PEM_write_bio_X509(bio, cert._x509) elif type == FILETYPE_ASN1: result_code = _lib.i2d_X509_bio(bio, cert._x509) elif type == FILETYPE_TEXT: result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0) else: raise ValueError( "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or " "FILETYPE_TEXT") assert result_code == 1 return _bio_to_string(bio)
Dump a public key to a buffer.
def dump_publickey(type, pkey): """ Dump a public key to a buffer. :param type: The file type (one of :data:`FILETYPE_PEM` or :data:`FILETYPE_ASN1`). :param PKey pkey: The public key to dump :return: The buffer with the dumped key in it. :rtype: bytes """ bio = _new_mem_buf() if type == FILETYPE_PEM: write_bio = _lib.PEM_write_bio_PUBKEY elif type == FILETYPE_ASN1: write_bio = _lib.i2d_PUBKEY_bio else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") result_code = write_bio(bio, pkey._pkey) if result_code != 1: # pragma: no cover _raise_current_error() return _bio_to_string(bio)
Dump the private key * pkey * into a buffer string encoded with the type * type *. Optionally ( if * type * is: const: FILETYPE_PEM ) encrypting it using * cipher * and * passphrase *.
def dump_privatekey(type, pkey, cipher=None, passphrase=None): """ Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`, :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`) :param PKey pkey: The PKey to dump :param cipher: (optional) if encrypted PEM format, the cipher to use :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The buffer with the dumped key in :rtype: bytes """ bio = _new_mem_buf() if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey") if cipher is not None: if passphrase is None: raise TypeError( "if a value is given for cipher " "one must also be given for passphrase") cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher)) if cipher_obj == _ffi.NULL: raise ValueError("Invalid cipher name") else: cipher_obj = _ffi.NULL helper = _PassphraseHelper(type, passphrase) if type == FILETYPE_PEM: result_code = _lib.PEM_write_bio_PrivateKey( bio, pkey._pkey, cipher_obj, _ffi.NULL, 0, helper.callback, helper.callback_args) helper.raise_if_problem() elif type == FILETYPE_ASN1: result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey) elif type == FILETYPE_TEXT: if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA: raise TypeError("Only RSA keys are supported for FILETYPE_TEXT") rsa = _ffi.gc( _lib.EVP_PKEY_get1_RSA(pkey._pkey), _lib.RSA_free ) result_code = _lib.RSA_print(bio, rsa, 0) else: raise ValueError( "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or " "FILETYPE_TEXT") _openssl_assert(result_code != 0) return _bio_to_string(bio)
Load a public key from a buffer.
def load_publickey(type, buffer): """ Load a public key from a buffer. :param type: The file type (one of :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`). :param buffer: The buffer the key is stored in. :type buffer: A Python string object, either unicode or bytestring. :return: The PKey object. :rtype: :class:`PKey` """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: evp_pkey = _lib.PEM_read_bio_PUBKEY( bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if evp_pkey == _ffi.NULL: _raise_current_error() pkey = PKey.__new__(PKey) pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free) pkey._only_public = True return pkey
Load a private key ( PKey ) from the string * buffer * encoded with the type * type *.
def load_privatekey(type, buffer, passphrase=None): """ Load a private key (PKey) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the key is stored in :param passphrase: (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase. :return: The PKey object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) helper = _PassphraseHelper(type, passphrase) if type == FILETYPE_PEM: evp_pkey = _lib.PEM_read_bio_PrivateKey( bio, _ffi.NULL, helper.callback, helper.callback_args) helper.raise_if_problem() elif type == FILETYPE_ASN1: evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if evp_pkey == _ffi.NULL: _raise_current_error() pkey = PKey.__new__(PKey) pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free) return pkey
Dump the certificate request * req * into a buffer string encoded with the type * type *.
def dump_certificate_request(type, req): """ Dump the certificate request *req* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request in """ bio = _new_mem_buf() if type == FILETYPE_PEM: result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req) elif type == FILETYPE_ASN1: result_code = _lib.i2d_X509_REQ_bio(bio, req._req) elif type == FILETYPE_TEXT: result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0) else: raise ValueError( "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or " "FILETYPE_TEXT" ) _openssl_assert(result_code != 0) return _bio_to_string(bio)
Load a certificate request ( X509Req ) from the string * buffer * encoded with the type * type *.
def load_certificate_request(type, buffer): """ Load a certificate request (X509Req) from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the certificate request is stored in :return: The X509Req object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") _openssl_assert(req != _ffi.NULL) x509req = X509Req.__new__(X509Req) x509req._req = _ffi.gc(req, _lib.X509_REQ_free) return x509req
Sign a data string using the given key and message digest.
def sign(pkey, data, digest): """ Sign a data string using the given key and message digest. :param pkey: PKey to sign with :param data: data to be signed :param digest: message digest to use :return: signature .. versionadded:: 0.11 """ data = _text_to_bytes_and_warn("data", data) digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") md_ctx = _lib.Cryptography_EVP_MD_CTX_new() md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free) _lib.EVP_SignInit(md_ctx, digest_obj) _lib.EVP_SignUpdate(md_ctx, data, len(data)) length = _lib.EVP_PKEY_size(pkey._pkey) _openssl_assert(length > 0) signature_buffer = _ffi.new("unsigned char[]", length) signature_length = _ffi.new("unsigned int *") final_result = _lib.EVP_SignFinal( md_ctx, signature_buffer, signature_length, pkey._pkey) _openssl_assert(final_result == 1) return _ffi.buffer(signature_buffer, signature_length[0])[:]
Verify the signature for a data string.
def verify(cert, signature, data, digest): """ Verify the signature for a data string. :param cert: signing certificate (X509 object) corresponding to the private key which generated the signature. :param signature: signature returned by sign function :param data: data to be verified :param digest: message digest to use :return: ``None`` if the signature is correct, raise exception otherwise. .. versionadded:: 0.11 """ data = _text_to_bytes_and_warn("data", data) digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") pkey = _lib.X509_get_pubkey(cert._x509) _openssl_assert(pkey != _ffi.NULL) pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free) md_ctx = _lib.Cryptography_EVP_MD_CTX_new() md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free) _lib.EVP_VerifyInit(md_ctx, digest_obj) _lib.EVP_VerifyUpdate(md_ctx, data, len(data)) verify_result = _lib.EVP_VerifyFinal( md_ctx, signature, len(signature), pkey ) if verify_result != 1: _raise_current_error()
Dump a certificate revocation list to a buffer.
def dump_crl(type, crl): """ Dump a certificate revocation list to a buffer. :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or ``FILETYPE_TEXT``). :param CRL crl: The CRL to dump. :return: The buffer with the CRL. :rtype: bytes """ bio = _new_mem_buf() if type == FILETYPE_PEM: ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl) elif type == FILETYPE_ASN1: ret = _lib.i2d_X509_CRL_bio(bio, crl._crl) elif type == FILETYPE_TEXT: ret = _lib.X509_CRL_print(bio, crl._crl) else: raise ValueError( "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or " "FILETYPE_TEXT") assert ret == 1 return _bio_to_string(bio)
Load Certificate Revocation List ( CRL ) data from a string * buffer *. * buffer * encoded with the type * type *.
def load_crl(type, buffer): """ Load Certificate Revocation List (CRL) data from a string *buffer*. *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param buffer: The buffer the CRL is stored in :return: The PKey object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if crl == _ffi.NULL: _raise_current_error() result = CRL.__new__(CRL) result._crl = _ffi.gc(crl, _lib.X509_CRL_free) return result
Load pkcs7 data from the string * buffer * encoded with the type * type *.
def load_pkcs7_data(type, buffer): """ Load pkcs7 data from the string *buffer* encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1) :param buffer: The buffer with the pkcs7 data. :return: The PKCS7 object """ if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) if type == FILETYPE_PEM: pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL) elif type == FILETYPE_ASN1: pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL) else: raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1") if pkcs7 == _ffi.NULL: _raise_current_error() pypkcs7 = PKCS7.__new__(PKCS7) pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free) return pypkcs7
Load pkcs12 data from the string * buffer *. If the pkcs12 structure is encrypted a * passphrase * must be included. The MAC is always checked and thus required.
def load_pkcs12(buffer, passphrase=None): """ Load pkcs12 data from the string *buffer*. If the pkcs12 structure is encrypted, a *passphrase* must be included. The MAC is always checked and thus required. See also the man page for the C function :py:func:`PKCS12_parse`. :param buffer: The buffer the certificate is stored in :param passphrase: (Optional) The password to decrypt the PKCS12 lump :returns: The PKCS12 object """ passphrase = _text_to_bytes_and_warn("passphrase", passphrase) if isinstance(buffer, _text_type): buffer = buffer.encode("ascii") bio = _new_mem_buf(buffer) # Use null passphrase if passphrase is None or empty string. With PKCS#12 # password based encryption no password and a zero length password are two # different things, but OpenSSL implementation will try both to figure out # which one works. if not passphrase: passphrase = _ffi.NULL p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL) if p12 == _ffi.NULL: _raise_current_error() p12 = _ffi.gc(p12, _lib.PKCS12_free) pkey = _ffi.new("EVP_PKEY**") cert = _ffi.new("X509**") cacerts = _ffi.new("Cryptography_STACK_OF_X509**") parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts) if not parse_result: _raise_current_error() cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free) # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the # queue for no particular reason. This error isn't interesting to anyone # outside this function. It's not even interesting to us. Get rid of it. try: _raise_current_error() except Error: pass if pkey[0] == _ffi.NULL: pykey = None else: pykey = PKey.__new__(PKey) pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free) if cert[0] == _ffi.NULL: pycert = None friendlyname = None else: pycert = X509._from_raw_x509_ptr(cert[0]) friendlyname_length = _ffi.new("int*") friendlyname_buffer = _lib.X509_alias_get0( cert[0], friendlyname_length ) friendlyname = _ffi.buffer( friendlyname_buffer, friendlyname_length[0] )[:] if friendlyname_buffer == _ffi.NULL: friendlyname = None pycacerts = [] for i in range(_lib.sk_X509_num(cacerts)): x509 = _lib.sk_X509_value(cacerts, i) pycacert = X509._from_raw_x509_ptr(x509) pycacerts.append(pycacert) if not pycacerts: pycacerts = None pkcs12 = PKCS12.__new__(PKCS12) pkcs12._pkey = pykey pkcs12._cert = pycert pkcs12._cacerts = pycacerts pkcs12._friendlyname = friendlyname return pkcs12
Export as a cryptography key.
def to_cryptography_key(self): """ Export as a ``cryptography`` key. :rtype: One of ``cryptography``'s `key interfaces`_. .. _key interfaces: https://cryptography.io/en/latest/hazmat/\ primitives/asymmetric/rsa/#key-interfaces .. versionadded:: 16.1.0 """ backend = _get_backend() if self._only_public: return backend._evp_pkey_to_public_key(self._pkey) else: return backend._evp_pkey_to_private_key(self._pkey)
Construct based on a cryptography * crypto_key *.
def from_cryptography_key(cls, crypto_key): """ Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0 """ pkey = cls() if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, dsa.DSAPublicKey, dsa.DSAPrivateKey)): raise TypeError("Unsupported key type") pkey._pkey = crypto_key._evp_pkey if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)): pkey._only_public = True pkey._initialized = True return pkey
Generate a key pair of the given type with the given number of bits.
def generate_key(self, type, bits): """ Generate a key pair of the given type, with the given number of bits. This generates a key "into" the this object. :param type: The key type. :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA` :param bits: The number of bits. :type bits: :py:data:`int` ``>= 0`` :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't of the appropriate type. :raises ValueError: If the number of bits isn't an integer of the appropriate size. :return: ``None`` """ if not isinstance(type, int): raise TypeError("type must be an integer") if not isinstance(bits, int): raise TypeError("bits must be an integer") if type == TYPE_RSA: if bits <= 0: raise ValueError("Invalid number of bits") # TODO Check error return exponent = _lib.BN_new() exponent = _ffi.gc(exponent, _lib.BN_free) _lib.BN_set_word(exponent, _lib.RSA_F4) rsa = _lib.RSA_new() result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL) _openssl_assert(result == 1) result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa) _openssl_assert(result == 1) elif type == TYPE_DSA: dsa = _lib.DSA_new() _openssl_assert(dsa != _ffi.NULL) dsa = _ffi.gc(dsa, _lib.DSA_free) res = _lib.DSA_generate_parameters_ex( dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL ) _openssl_assert(res == 1) _openssl_assert(_lib.DSA_generate_key(dsa) == 1) _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1) else: raise Error("No such key type") self._initialized = True
Check the consistency of an RSA private key.
def check(self): """ Check the consistency of an RSA private key. This is the Python equivalent of OpenSSL's ``RSA_check_key``. :return: ``True`` if key is consistent. :raise OpenSSL.crypto.Error: if the key is inconsistent. :raise TypeError: if the key is of a type which cannot be checked. Only RSA keys can currently be checked. """ if self._only_public: raise TypeError("public key only") if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA: raise TypeError("key type unsupported") rsa = _lib.EVP_PKEY_get1_RSA(self._pkey) rsa = _ffi.gc(rsa, _lib.RSA_free) result = _lib.RSA_check_key(rsa) if result: return True _raise_current_error()