How to select specific the cipher while sending request via python request module

2024/11/16 10:11:06

Usecase: I want to find out how many ciphers are supported by the hostname with python request module.

I am not able to find a way to provide the cipher name to request module hook. Can anyone suggest the way to provide the way to specify cipher.

import sslfrom requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManagerclass Ssl3HttpAdapter(HTTPAdapter):""""Transport adapter" that allows us to use SSLv3."""def init_poolmanager(self, connections, maxsize, block=False):self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,block=block, ssl_version=ssl.PROTOCOL_SSLv3)
Answer

If you are using requests version 2.12.0+, there is a blog post on Configuring TLS With Requests, which describes new functionality to allow you to configure the SSLContext (note that this blog post was written after the OP asked the question):

The feature added in Requests v2.12.0 is that urllib3 now accepts anSSLContext object in the constructors for ConnectionPool objects. ThisSSLContext will be used as the factory for the underlying TLSconnection, and so all settings applied to it will also be applied tothose low-level connections.

The best way to do this is to use the SSLContext factory functionrequests.packages.urllib3.util.ssl_.create_urllib3_context. This isanalogous to Python’s ssl.create_default_context function but appliesthe more-strict default TLS configuration that Requests and urllib3both use. This function will return an SSLContext object that can thenhave further configuration applied. On top of that, the function alsotakes a few arguments to allow overriding default configuration.

To provide the new SSLContext object, you will need to write aTransportAdapter that is appropriate for the given host.

The following sample code is given as an example of how to re-enable 3DES in Requests using this method.

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.ssl_ import create_urllib3_context# This is the 2.11 Requests cipher string, containing 3DES.
CIPHERS = ('ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:''DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:''!eNULL:!MD5'
)class DESAdapter(HTTPAdapter):"""A TransportAdapter that re-enables 3DES support in Requests."""def init_poolmanager(self, *args, **kwargs):context = create_urllib3_context(ciphers=CIPHERS)kwargs['ssl_context'] = contextreturn super(DESAdapter, self).init_poolmanager(*args, **kwargs)def proxy_manager_for(self, *args, **kwargs):context = create_urllib3_context(ciphers=CIPHERS)kwargs['ssl_context'] = contextreturn super(DESAdapter, self).proxy_manager_for(*args, **kwargs)s = requests.Session()
s.mount('https://some-3des-only-host.com', DESAdapter())
r = s.get('https://some-3des-only-host.com/some-path')

There is also a hack possible, which you can read on the github pages for the requests module, or at https://stackoverflow.com/a/32651967/2364215 but it modifies the underlying library code, I don't recommend it (neither do the authors of the requests module, as you will find on that page). On the other hand, if you are on an older requests package and you can't upgrade, it may be your best option. It amounts to overriding the urllib3 module's DEFAULT_CIPHERS:

requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':RC4-SHA' 

If you have other code that will use the requests module after doing the modification, but doesn't need the modification, you may want to restore DEFAULT_CIPHERS to its previous value.

https://en.xdnf.cn/q/71354.html

Related Q&A

Different classes made by type with the same name in Python?

I was playing around with metaclasses in Python and found something very curious. I can create two classes with the same name, but that are actually different objects. See:>>> def create_class…

Installing python server for emacs-jedi

I am trying to install Jedi for emacs using marmalade package manager by following instructions here -- http://tkf.github.io/emacs-jedi/latest/. The package manger installs Jedi along with its dependen…

Multi-feature causal CNN - Keras implementation

Im currently using a basic LSTM to make regression predictions and I would like to implement a causal CNN as it should be computationally more efficient.Im struggling to figure out how to reshape my cu…

Adding a join to an SQL Alchemy expression that already has a select_from()

Note: this is a question about SQL Alchemys expression language not the ORMSQL Alchemy is fine for adding WHERE or HAVING clauses to an existing query:q = select([bmt_gene.c.id]).select_from(bmt_gene) …

How should I move blobs from BlobStore over to Google Cloud Storage?

Our application has been running on App Engine using the Blobstore for years. We would like to move our video files over to Google Cloud Storage. What is the best practice for migrating large blobs f…

Python: Find `sys.argv` before the `sys` module is loaded

I want to find the command line arguments that my program was called with, i.e. sys.argv, but I want to do that before Python makes sys.argv available. This is because Im running code in usercustomize.…

Dotted lines instead of a missing value in matplotlib

I have an array of some data, where some of the values are missingy = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23])When I plot it, I have these NANs missing (which is expected)f…

How to change the creation date of file using python on a mac?

I need to update the creation time of a .mp4 file so that it will appear at the top of a list of media files sorted by creation date. I am able to easily update both the accessed and modified date of …

Classification tree in sklearn giving inconsistent answers

I am using a classification tree from sklearn and when I have the the model train twice using the same data, and predict with the same test data, I am getting different results. I tried reproducing on…

Modifying binary file with Python

i am trying to patch a hex file. i have two patch files (hex) named "patch 1" and "patch 2"the file to be patched is a 16 MB file named "file.bin".i have tried many differ…