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 #6893

Closed
suaveolent opened this issue Feb 12, 2025 · 2 comments
Closed
Labels
actions/autoclose-qa Used for automation to auto-close an issue

Comments

@suaveolent
Copy link

suaveolent commented Feb 12, 2025

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

Expected Result

The connection should be established.

Actual Result

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)')))

Reproduction Steps

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}")

System Information

$ python -m requests.help
{
  "chardet": {
    "version": null
  },
  "charset_normalizer": {
    "version": "3.4.0"
  },
  "cryptography": {
    "version": ""
  },
  "idna": {
    "version": "3.10"
  },
  "implementation": {
    "name": "CPython",
    "version": "3.13.0"
  },
  "platform": {
    "release": "24.3.0",
    "system": "Darwin"
  },
  "pyOpenSSL": {
    "openssl_version": "",
    "version": null
  },
  "requests": {
    "version": "2.32.3"
  },
  "system_ssl": {
    "version": "30400000"
  },
  "urllib3": {
    "version": "2.2.3"
  },
  "using_charset_normalizer": true,
  "using_pyopenssl": false
}
@sigmavirus24
Copy link
Contributor

Duplicate of #6892

@sigmavirus24 sigmavirus24 marked this as a duplicate of #6892 Feb 12, 2025
@sigmavirus24 sigmavirus24 added the actions/autoclose-qa Used for automation to auto-close an issue label 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
Projects
None yet
Development

No branches or pull requests

2 participants