Azza Worsley
Azza Worsley

Reputation: 21

How to set default ciphers for Python Requests library when using urllib3 ver > 2.0.0

urllib3 removed the ability to change DEFAULT_CIPHER in the major version 2.0.0. This was the main way to get around the error:

requests.exceptions.SSLError: [SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:600) 

on the client side.

Is there anyway to change the default cipher now in urllib3 ver > 2.0.0. or another way to get around this error?

Previously I had been receiving the error:

requests.exceptions.SSLError: [SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:600)

when using the requests library, which I eventually was able to get around using the line:

requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=1'

However, after getting a new laptop and reinstalling my packages, I began to get the original error again. After doing a bunch of research, I believe the issue is that on my new laptop, I've installed urllib3 2.0.3 which removed the "DEFAULT_CIPHERS" as seen in the changelog for version 2.0.0: Removed DEFAULT_CIPHERS, HAS_SNI, USE_DEFAULT_SSLCONTEXT_CIPHERS, from the private module urllib3.util.ssl_

Preferably without having to downgrade my urllib3 to an older version, does anyone know how to change the default ciphers again so I can get around the dh key too small error?

Thanks

Upvotes: 2

Views: 1113

Answers (1)

dontsov
dontsov

Reputation: 109

For urllib3 ver > 2.0.0 i use:

import requests
import ssl
from requests.adapters import HTTPAdapter

class CustomSSLAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        ssl_context = ssl.create_default_context()
        ssl_context.set_ciphers('DEFAULT@SECLEVEL=1')

        # See urllib3.poolmanager.SSL_KEYWORDS for all available keys.
        kwargs["ssl_context"] = ssl_context

        return super().init_poolmanager(*args, **kwargs)


sess = requests.Session()
sess.mount('https://', CustomSSLAdapter())

I solved requests.exceptions.SSLError:

Caused by SSLError(SSLError(1, '[SSL: DH_KEY_TOO_SMALL] dh key too small (_ssl.c:997)'))

Environment:

Python 3.10.6
urllib3            2.3.0
requests           2.32.3
OpenSSL 1.1.1n  15 Mar 2022 (print(ssl.OPENSSL_VERSION))

P.S. https://stackoverflow.com/a/72518559/3270632 said, that "Obviously, in general THIS SHOULD NOT BE USED. This will allow for man-in-the-middle attacks and other nasty things. Be careful and mindful when changing these settings."

Upvotes: 0

Related Questions