_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q269700
OAuth2RequestValidator.authenticate_client_id
test
def authenticate_client_id(self, client_id, request, *args, **kwargs): """Authenticate a non-confidential client. :param client_id: Client ID of the non-confidential client :param request: The Request object passed by oauthlib """ if client_id is None: client_id, _ = self._get_client_creds_from_request(request) log.debug('Authenticate client %r.', client_id) client = request.client or self._clientgetter(client_id) if not client: log.debug('Authenticate failed, client not found.') return False # attach client on request for convenience request.client = client return True
python
{ "resource": "" }
q269701
OAuth2RequestValidator.get_original_scopes
test
def get_original_scopes(self, refresh_token, request, *args, **kwargs): """Get the list of scopes associated with the refresh token. This method is used in the refresh token grant flow. We return the scope of the token to be refreshed so it can be applied to the new access token. """ log.debug('Obtaining scope of refreshed token.') tok = self._tokengetter(refresh_token=refresh_token) return tok.scopes
python
{ "resource": "" }
q269702
OAuth2RequestValidator.confirm_scopes
test
def confirm_scopes(self, refresh_token, scopes, request, *args, **kwargs): """Ensures the requested scope matches the scope originally granted by the resource owner. If the scope is omitted it is treated as equal to the scope originally granted by the resource owner. DEPRECATION NOTE: This method will cease to be used in oauthlib>0.4.2, future versions of ``oauthlib`` use the validator method ``get_original_scopes`` to determine the scope of the refreshed token. """ if not scopes: log.debug('Scope omitted for refresh token %r', refresh_token) return True log.debug('Confirm scopes %r for refresh token %r', scopes, refresh_token) tok = self._tokengetter(refresh_token=refresh_token) return set(tok.scopes) == set(scopes)
python
{ "resource": "" }
q269703
OAuth2RequestValidator.get_default_redirect_uri
test
def get_default_redirect_uri(self, client_id, request, *args, **kwargs): """Default redirect_uri for the given client.""" request.client = request.client or self._clientgetter(client_id) redirect_uri = request.client.default_redirect_uri log.debug('Found default redirect uri %r', redirect_uri) return redirect_uri
python
{ "resource": "" }
q269704
OAuth2RequestValidator.get_default_scopes
test
def get_default_scopes(self, client_id, request, *args, **kwargs): """Default scopes for the given client.""" request.client = request.client or self._clientgetter(client_id) scopes = request.client.default_scopes log.debug('Found default scopes %r', scopes) return scopes
python
{ "resource": "" }
q269705
OAuth2RequestValidator.invalidate_authorization_code
test
def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): """Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself. """ log.debug('Destroy grant token for client %r, %r', client_id, code) grant = self._grantgetter(client_id=client_id, code=code) if grant: grant.delete()
python
{ "resource": "" }
q269706
OAuth2RequestValidator.save_authorization_code
test
def save_authorization_code(self, client_id, code, request, *args, **kwargs): """Persist the authorization code.""" log.debug( 'Persist authorization code %r for client %r', code, client_id ) request.client = request.client or self._clientgetter(client_id) self._grantsetter(client_id, code, request, *args, **kwargs) return request.client.default_redirect_uri
python
{ "resource": "" }
q269707
OAuth2RequestValidator.save_bearer_token
test
def save_bearer_token(self, token, request, *args, **kwargs): """Persist the Bearer token.""" log.debug('Save bearer token %r', token) self._tokensetter(token, request, *args, **kwargs) return request.client.default_redirect_uri
python
{ "resource": "" }
q269708
OAuth2RequestValidator.validate_bearer_token
test
def validate_bearer_token(self, token, scopes, request): """Validate access token. :param token: A string of random characters :param scopes: A list of scopes :param request: The Request object passed by oauthlib The validation validates: 1) if the token is available 2) if the token has expired 3) if the scopes are available """ log.debug('Validate bearer token %r', token) tok = self._tokengetter(access_token=token) if not tok: msg = 'Bearer token not found.' request.error_message = msg log.debug(msg) return False # validate expires if tok.expires is not None and \ datetime.datetime.utcnow() > tok.expires: msg = 'Bearer token is expired.' request.error_message = msg log.debug(msg) return False # validate scopes if scopes and not set(tok.scopes) & set(scopes): msg = 'Bearer token scope not valid.' request.error_message = msg log.debug(msg) return False request.access_token = tok request.user = tok.user request.scopes = scopes if hasattr(tok, 'client'): request.client = tok.client elif hasattr(tok, 'client_id'): request.client = self._clientgetter(tok.client_id) return True
python
{ "resource": "" }
q269709
OAuth2RequestValidator.validate_client_id
test
def validate_client_id(self, client_id, request, *args, **kwargs): """Ensure client_id belong to a valid and active client.""" log.debug('Validate client %r', client_id) client = request.client or self._clientgetter(client_id) if client: # attach client to request object request.client = client return True return False
python
{ "resource": "" }
q269710
OAuth2RequestValidator.validate_code
test
def validate_code(self, client_id, code, client, request, *args, **kwargs): """Ensure the grant code is valid.""" client = client or self._clientgetter(client_id) log.debug( 'Validate code for client %r and code %r', client.client_id, code ) grant = self._grantgetter(client_id=client.client_id, code=code) if not grant: log.debug('Grant not found.') return False if hasattr(grant, 'expires') and \ datetime.datetime.utcnow() > grant.expires: log.debug('Grant is expired.') return False request.state = kwargs.get('state') request.user = grant.user request.scopes = grant.scopes return True
python
{ "resource": "" }
q269711
OAuth2RequestValidator.validate_grant_type
test
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): """Ensure the client is authorized to use the grant type requested. It will allow any of the four grant types (`authorization_code`, `password`, `client_credentials`, `refresh_token`) by default. Implemented `allowed_grant_types` for client object to authorize the request. It is suggested that `allowed_grant_types` should contain at least `authorization_code` and `refresh_token`. """ if self._usergetter is None and grant_type == 'password': log.debug('Password credential authorization is disabled.') return False default_grant_types = ( 'authorization_code', 'password', 'client_credentials', 'refresh_token', ) # Grant type is allowed if it is part of the 'allowed_grant_types' # of the selected client or if it is one of the default grant types if hasattr(client, 'allowed_grant_types'): if grant_type not in client.allowed_grant_types: return False else: if grant_type not in default_grant_types: return False if grant_type == 'client_credentials': if not hasattr(client, 'user'): log.debug('Client should have a user property') return False request.user = client.user return True
python
{ "resource": "" }
q269712
OAuth2RequestValidator.validate_refresh_token
test
def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): """Ensure the token is valid and belongs to the client This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials grant (also indirectly) and the refresh token grant. """ token = self._tokengetter(refresh_token=refresh_token) if token and token.client_id == client.client_id: # Make sure the request object contains user and client_id request.client_id = token.client_id request.user = token.user return True return False
python
{ "resource": "" }
q269713
OAuth2RequestValidator.validate_response_type
test
def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): """Ensure client is authorized to use the response type requested. It will allow any of the two (`code`, `token`) response types by default. Implemented `allowed_response_types` for client object to authorize the request. """ if response_type not in ('code', 'token'): return False if hasattr(client, 'allowed_response_types'): return response_type in client.allowed_response_types return True
python
{ "resource": "" }
q269714
OAuth2RequestValidator.validate_scopes
test
def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): """Ensure the client is authorized access to requested scopes.""" if hasattr(client, 'validate_scopes'): return client.validate_scopes(scopes) return set(client.default_scopes).issuperset(set(scopes))
python
{ "resource": "" }
q269715
OAuth2RequestValidator.validate_user
test
def validate_user(self, username, password, client, request, *args, **kwargs): """Ensure the username and password is valid. Attach user object on request for later using. """ log.debug('Validating username %r and its password', username) if self._usergetter is not None: user = self._usergetter( username, password, client, request, *args, **kwargs ) if user: request.user = user return True return False log.debug('Password credential authorization is disabled.') return False
python
{ "resource": "" }
q269716
OAuth2RequestValidator.revoke_token
test
def revoke_token(self, token, token_type_hint, request, *args, **kwargs): """Revoke an access or refresh token. """ if token_type_hint: tok = self._tokengetter(**{token_type_hint: token}) else: tok = self._tokengetter(access_token=token) if not tok: tok = self._tokengetter(refresh_token=token) if tok: request.client_id = tok.client_id request.user = tok.user tok.delete() return True msg = 'Invalid token supplied.' log.debug(msg) request.error_message = msg return False
python
{ "resource": "" }
q269717
update_qq_api_request_data
test
def update_qq_api_request_data(data={}): '''Update some required parameters for OAuth2.0 API calls''' defaults = { 'openid': session.get('qq_openid'), 'access_token': session.get('qq_token')[0], 'oauth_consumer_key': QQ_APP_ID, } defaults.update(data) return defaults
python
{ "resource": "" }
q269718
convert_keys_to_string
test
def convert_keys_to_string(dictionary): '''Recursively converts dictionary keys to strings.''' if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items())
python
{ "resource": "" }
q269719
change_weibo_header
test
def change_weibo_header(uri, headers, body): """Since weibo is a rubbish server, it does not follow the standard, we need to change the authorization header for it.""" auth = headers.get('Authorization') if auth: auth = auth.replace('Bearer', 'OAuth2') headers['Authorization'] = auth return uri, headers, body
python
{ "resource": "" }
q269720
RemoteAppFactory.register_to
test
def register_to(self, oauth, name=None, **kwargs): """Creates a remote app and registers it.""" kwargs = self._process_kwargs( name=(name or self.default_name), **kwargs) return oauth.remote_app(**kwargs)
python
{ "resource": "" }
q269721
RemoteAppFactory.create
test
def create(self, oauth, **kwargs): """Creates a remote app only.""" kwargs = self._process_kwargs( name=self.default_name, register=False, **kwargs) return oauth.remote_app(**kwargs)
python
{ "resource": "" }
q269722
extract_params
test
def extract_params(): """Extract request params.""" uri = _get_uri_from_request(request) http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] # Werkzeug, and subsequently Flask provide a safe Authorization header # parsing, so we just replace the Authorization header with the extraced # info if it was successfully parsed. if request.authorization: headers['Authorization'] = request.authorization body = request.form.to_dict() return uri, http_method, body, headers
python
{ "resource": "" }
q269723
to_bytes
test
def to_bytes(text, encoding='utf-8'): """Make sure text is bytes type.""" if not text: return text if not isinstance(text, bytes_type): text = text.encode(encoding) return text
python
{ "resource": "" }
q269724
decode_base64
test
def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
python
{ "resource": "" }
q269725
create_response
test
def create_response(headers, body, status): """Create response class for Flask.""" response = Response(body or '') for k, v in headers.items(): response.headers[str(k)] = v response.status_code = status return response
python
{ "resource": "" }
q269726
get_cached_clients
test
def get_cached_clients(): """Gets the cached clients dictionary in current context.""" if OAuth.state_key not in current_app.extensions: raise RuntimeError('%r is not initialized.' % current_app) state = current_app.extensions[OAuth.state_key] return state.cached_clients
python
{ "resource": "" }
q269727
OAuth.add_remote_app
test
def add_remote_app(self, remote_app, name=None, **kwargs): """Adds remote application and applies custom attributes on it. If the application instance's name is different from the argument provided name, or the keyword arguments is not empty, then the application instance will not be modified but be copied as a prototype. :param remote_app: the remote application instance. :type remote_app: the subclasses of :class:`BaseApplication` :params kwargs: the overriding attributes for the application instance. """ if name is None: name = remote_app.name if name != remote_app.name or kwargs: remote_app = copy.copy(remote_app) remote_app.name = name vars(remote_app).update(kwargs) if not hasattr(remote_app, 'clients'): remote_app.clients = cached_clients self.remote_apps[name] = remote_app return remote_app
python
{ "resource": "" }
q269728
OAuth.remote_app
test
def remote_app(self, name, version=None, **kwargs): """Creates and adds new remote application. :param name: the remote application's name. :param version: '1' or '2', the version code of OAuth protocol. :param kwargs: the attributes of remote application. """ if version is None: if 'request_token_url' in kwargs: version = '1' else: version = '2' if version == '1': remote_app = OAuth1Application(name, clients=cached_clients) elif version == '2': remote_app = OAuth2Application(name, clients=cached_clients) else: raise ValueError('unkonwn version %r' % version) return self.add_remote_app(remote_app, **kwargs)
python
{ "resource": "" }
q269729
Checker_X509_get_pubkey.check_exception
test
def check_exception(self): """ Call the method repeatedly such that it will raise an exception. """ for i in xrange(self.iterations): cert = X509() try: cert.get_pubkey() except Error: pass
python
{ "resource": "" }
q269730
Checker_X509_get_pubkey.check_success
test
def check_success(self): """ Call the method repeatedly such that it will return a PKey object. """ small = xrange(3) for i in xrange(self.iterations): key = PKey() key.generate_key(TYPE_DSA, 256) for i in small: cert = X509() cert.set_pubkey(key) for i in small: cert.get_pubkey()
python
{ "resource": "" }
q269731
Checker_load_privatekey.check_load_privatekey_callback
test
def check_load_privatekey_callback(self): """ Call the function with an encrypted PEM and a passphrase callback. """ for i in xrange(self.iterations * 10): load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "hello, secret")
python
{ "resource": "" }
q269732
Checker_load_privatekey.check_load_privatekey_callback_incorrect
test
def check_load_privatekey_callback_incorrect(self): """ Call the function with an encrypted PEM and a passphrase callback which returns the wrong passphrase. """ for i in xrange(self.iterations * 10): try: load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "hello, public") except Error: pass
python
{ "resource": "" }
q269733
Checker_load_privatekey.check_load_privatekey_callback_wrong_type
test
def check_load_privatekey_callback_wrong_type(self): """ Call the function with an encrypted PEM and a passphrase callback which returns a non-string. """ for i in xrange(self.iterations * 10): try: load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: {}) except ValueError: pass
python
{ "resource": "" }
q269734
Checker_CRL.check_get_revoked
test
def check_get_revoked(self): """ Create a CRL object with 100 Revoked objects, then call the get_revoked method repeatedly. """ crl = CRL() for i in xrange(100): crl.add_revoked(Revoked()) for i in xrange(self.iterations): crl.get_revoked()
python
{ "resource": "" }
q269735
Checker_X509_REVOKED_dup.check_X509_REVOKED_dup
test
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)
python
{ "resource": "" }
q269736
createCertRequest
test
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
python
{ "resource": "" }
q269737
createCertificate
test
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
python
{ "resource": "" }
q269738
_make_requires
test
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
python
{ "resource": "" }
q269739
Context.load_verify_locations
test
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()
python
{ "resource": "" }
q269740
Context.set_passwd_cb
test
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
python
{ "resource": "" }
q269741
Context.use_certificate_chain_file
test
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()
python
{ "resource": "" }
q269742
Context.use_certificate_file
test
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()
python
{ "resource": "" }
q269743
Context.use_certificate
test
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()
python
{ "resource": "" }
q269744
Context.add_extra_chain_cert
test
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()
python
{ "resource": "" }
q269745
Context.use_privatekey_file
test
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()
python
{ "resource": "" }
q269746
Context.use_privatekey
test
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()
python
{ "resource": "" }
q269747
Context.load_client_ca
test
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)
python
{ "resource": "" }
q269748
Context.set_verify_depth
test
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)
python
{ "resource": "" }
q269749
Context.load_tmp_dh
test
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)
python
{ "resource": "" }
q269750
Context.set_cipher_list
test
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', ), ], )
python
{ "resource": "" }
q269751
Context.set_client_ca_list
test
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)
python
{ "resource": "" }
q269752
Context.add_client_ca
test
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)
python
{ "resource": "" }
q269753
Context.set_tlsext_servername_callback
test
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)
python
{ "resource": "" }
q269754
Context.set_tlsext_use_srtp
test
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 )
python
{ "resource": "" }
q269755
Context.set_npn_select_callback
test
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)
python
{ "resource": "" }
q269756
Context.set_alpn_protos
test
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))
python
{ "resource": "" }
q269757
Context.set_alpn_select_callback
test
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)
python
{ "resource": "" }
q269758
Context._set_ocsp_callback
test
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)
python
{ "resource": "" }
q269759
Context.set_ocsp_server_callback
test
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)
python
{ "resource": "" }
q269760
Context.set_ocsp_client_callback
test
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)
python
{ "resource": "" }
q269761
Connection.set_context
test
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
python
{ "resource": "" }
q269762
Connection.get_servername
test
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)
python
{ "resource": "" }
q269763
Connection.set_tlsext_host_name
test
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)
python
{ "resource": "" }
q269764
Connection.recv
test
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)[:]
python
{ "resource": "" }
q269765
Connection.recv_into
test
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
python
{ "resource": "" }
q269766
Connection.bio_read
test
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)[:]
python
{ "resource": "" }
q269767
Connection.renegotiate
test
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
python
{ "resource": "" }
q269768
Connection.shutdown
test
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
python
{ "resource": "" }
q269769
Connection.get_cipher_list
test
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
python
{ "resource": "" }
q269770
Connection.get_client_ca_list
test
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
python
{ "resource": "" }
q269771
Connection.set_shutdown
test
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)
python
{ "resource": "" }
q269772
Connection.server_random
test
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)[:]
python
{ "resource": "" }
q269773
Connection.client_random
test
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)[:]
python
{ "resource": "" }
q269774
Connection.master_key
test
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)[:]
python
{ "resource": "" }
q269775
Connection.export_keying_material
test
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)[:]
python
{ "resource": "" }
q269776
Connection.get_session
test
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
python
{ "resource": "" }
q269777
Connection.get_cipher_name
test
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")
python
{ "resource": "" }
q269778
Connection.get_cipher_bits
test
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)
python
{ "resource": "" }
q269779
Connection.get_cipher_version
test
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")
python
{ "resource": "" }
q269780
Connection.get_protocol_version_name
test
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")
python
{ "resource": "" }
q269781
Connection.get_next_proto_negotiated
test
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])[:]
python
{ "resource": "" }
q269782
Connection.set_alpn_protos
test
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))
python
{ "resource": "" }
q269783
Connection.get_alpn_proto_negotiated
test
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])[:]
python
{ "resource": "" }
q269784
_new_mem_buf
test
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
python
{ "resource": "" }
q269785
_bio_to_string
test
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)[:]
python
{ "resource": "" }
q269786
_set_asn1_time
test
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")
python
{ "resource": "" }
q269787
_get_asn1_time
test
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
python
{ "resource": "" }
q269788
get_elliptic_curve
test
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)
python
{ "resource": "" }
q269789
dump_publickey
test
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)
python
{ "resource": "" }
q269790
load_publickey
test
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
python
{ "resource": "" }
q269791
sign
test
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])[:]
python
{ "resource": "" }
q269792
verify
test
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()
python
{ "resource": "" }
q269793
dump_crl
test
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)
python
{ "resource": "" }
q269794
PKey.to_cryptography_key
test
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)
python
{ "resource": "" }
q269795
PKey.generate_key
test
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
python
{ "resource": "" }
q269796
PKey.check
test
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()
python
{ "resource": "" }
q269797
_EllipticCurve._load_elliptic_curves
test
def _load_elliptic_curves(cls, lib): """ Get the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. """ num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0) builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves) # The return value on this call should be num_curves again. We # could check it to make sure but if it *isn't* then.. what could # we do? Abort the whole process, I suppose...? -exarkun lib.EC_get_builtin_curves(builtin_curves, num_curves) return set( cls.from_nid(lib, c.nid) for c in builtin_curves)
python
{ "resource": "" }
q269798
_EllipticCurve._get_elliptic_curves
test
def _get_elliptic_curves(cls, lib): """ Get, cache, and return the curves supported by OpenSSL. :param lib: The OpenSSL library binding object. :return: A :py:type:`set` of ``cls`` instances giving the names of the elliptic curves the underlying library supports. """ if cls._curves is None: cls._curves = cls._load_elliptic_curves(lib) return cls._curves
python
{ "resource": "" }
q269799
_EllipticCurve._to_EC_KEY
test
def _to_EC_KEY(self): """ Create a new OpenSSL EC_KEY structure initialized to use this curve. The structure is automatically garbage collected when the Python object is garbage collected. """ key = self._lib.EC_KEY_new_by_curve_name(self._nid) return _ffi.gc(key, _lib.EC_KEY_free)
python
{ "resource": "" }