Bug fix relaxed SSL.
This commit is contained in:
parent
ca308e311e
commit
03d33c08c9
1 changed files with 39 additions and 10 deletions
|
|
@ -1,25 +1,54 @@
|
|||
"""Enable Python requests that ignores bad HTTPS certificates."""
|
||||
|
||||
import typing
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from requests.packages.urllib3.util.ssl_ import create_urllib3_context
|
||||
|
||||
from urllib3.util.ssl_ import create_urllib3_context
|
||||
|
||||
CIPHERS = "DEFAULT@SECLEVEL=1"
|
||||
|
||||
|
||||
class HTTPSAdapter(HTTPAdapter):
|
||||
"""HTTPS Adapter subclass."""
|
||||
"""HTTPS adapter that relaxes TLS settings for problematic servers."""
|
||||
|
||||
def init_poolmanager(self, *args: typing.Any, **kwargs: typing.Any) -> None:
|
||||
"""Init pool manager."""
|
||||
def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:
|
||||
"""Initialise the pool manager with a relaxed SSLContext."""
|
||||
context = create_urllib3_context(ciphers=CIPHERS)
|
||||
|
||||
# Critical bit for Python 3.13+: CERT_NONE must not have hostname checks on.
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
|
||||
kwargs["ssl_context"] = context
|
||||
return super().init_poolmanager(*args, **kwargs) # type: ignore
|
||||
super().init_poolmanager(*args, **kwargs)
|
||||
|
||||
def proxy_manager_for(self, *args: Any, **kwargs: Any):
|
||||
"""Ensure the same SSLContext is used for proxy connections too."""
|
||||
proxy_kwargs = kwargs.get("proxy_kwargs") or {}
|
||||
context = create_urllib3_context(ciphers=CIPHERS)
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
proxy_kwargs["ssl_context"] = context
|
||||
kwargs["proxy_kwargs"] = proxy_kwargs
|
||||
return super().proxy_manager_for(*args, **kwargs)
|
||||
|
||||
|
||||
def get(*args: typing.Any, **kwargs: typing.Any) -> requests.Response:
|
||||
s = requests.Session()
|
||||
s.mount("https://", HTTPSAdapter())
|
||||
return s.get(*args, **kwargs, verify=False)
|
||||
_session: requests.Session | None = None
|
||||
|
||||
|
||||
def get(*args: Any, **kwargs: Any) -> requests.Response:
|
||||
"""GET a URL using a session that ignores bad TLS certificates."""
|
||||
global _session
|
||||
if _session is None:
|
||||
_session = requests.Session()
|
||||
_session.mount("https://", HTTPSAdapter())
|
||||
|
||||
# Keep this for requests' own handling, but the SSLContext is now consistent.
|
||||
kwargs.setdefault("verify", False)
|
||||
|
||||
return _session.get(*args, **kwargs)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue