Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with SSL verification using self-signed certificate in version 2.32.3 #6892

Closed
suaveolent opened this issue Feb 12, 2025 · 1 comment
Closed
Labels
actions/autoclose-qa Used for automation to auto-close an issue Question/Not a bug

Comments

@suaveolent
Copy link

I am experiencing an issue with version 2.32.3 of the library when using build_connection_pool_key_attributes with a self-signed certificate. I need a custom SSL context because the connection fails due to weak certificate strength.

See also #6715

Here is the code I am using:

Code kopieren
import ssl
import requests
from requests.adapters import HTTPAdapter

class SSLAdapter(HTTPAdapter):
    """An HTTPAdapter that uses an arbitrary SSL context."""

    def __init__(self, ssl_context: ssl.SSLContext = None, **kwargs):
        """Initialize the SSLAdapter."""
        super().__init__(**kwargs)
        self.ssl_context = ssl_context

    def build_connection_pool_key_attributes(
        self,
        request: requests.PreparedRequest,
        verify: bool | str,
        cert: str | tuple[str, str] | None = None,
    ) -> tuple[dict, dict]:
        host_params, ssl_params = super().build_connection_pool_key_attributes(
            request, verify, cert
        )
        if verify is True and self.ssl_context:
            ssl_params["ssl_context"] = self.ssl_context

        return host_params, ssl_params

if __name__ == "__main__":
    # Create a custom SSL context
    ssl_context = ssl._create_unverified_context()
    ssl_context.set_ciphers("DEFAULT@SECLEVEL=2")  # Adjusting the security level to support 2048 bit keys

    # Example API call setup
    username = "<admin>"
    password = "<password>"
    protocol = "https"
    api_url = f"{protocol}://<host>/"
    action = "<action>"
    headers = {"Content-Type": "application/json"}

    # Create a session with the SSLAdapter
    session = requests.Session()
    session.auth = (username, password)
    session.mount(f"{protocol}://", SSLAdapter(ssl_context=ssl_context))

    try:
        response = session.get(api_url + action, timeout=15, headers=headers)
        response.raise_for_status()  # Raise an exception for HTTP errors
        print("Response:", response.json())
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

When I run this code, I encounter the following error:

An error occurred: HTTPSConnectionPool(host='<host>', port=443): Max retries exceeded with url: /<action>/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1000)')))

I expected that using _create_unverified_context would allow for self-signed certificates, but it seems that is not the case. What am I doing wrong?

Any guidance on how to resolve this issue would be greatly appreciated!

@suaveolent suaveolent added actions/autoclose-qa Used for automation to auto-close an issue Question/Not a bug labels Feb 12, 2025
Copy link

As described in the template, we won't be able to answer questions on this issue tracker. Please use Stack Overflow

@github-actions github-actions bot locked as off-topic and limited conversation to collaborators Feb 12, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
actions/autoclose-qa Used for automation to auto-close an issue Question/Not a bug
Projects
None yet
Development

No branches or pull requests

1 participant