This repository has been archived by the owner on Nov 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
tlsutil.py
58 lines (41 loc) · 1.63 KB
/
tlsutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import requests
import requests.adapters
import ssl
class TLSLowerAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
kwargs['ssl_context'] = ssl.SSLContext(self.ssl_version)
return super().init_poolmanager(*args, **kwargs)
def proxy_manager_for(self, *args, **kwargs):
kwargs['ssl_context'] = ssl.SSLContext(self.ssl_version)
return super().proxy_manager_for(*args, **kwargs)
class TLSv1Adapter(TLSLowerAdapter):
ssl_version = ssl.PROTOCOL_TLSv1
class TLSv1_1Adapter(TLSLowerAdapter):
ssl_version = ssl.PROTOCOL_TLSv1_1
class TLSv1_2Adapter(TLSLowerAdapter):
ssl_version = ssl.PROTOCOL_TLSv1_2
def method_tls_fallback(url, method, *args, **kwargs):
"""
Try to perform a method on an url using requests.
If the get request fails due to an SSLError, we try to lower
the TLS version until it finally succeeds.
"""
# Try to get as-is
try:
session = requests.Session()
return getattr(session, method)(url, *args, **kwargs)
except requests.exceptions.SSLError:
pass
err = None
for adapter in [TLSv1_2Adapter, TLSv1_1Adapter, TLSv1Adapter]:
try:
session = requests.Session()
session.mount("https://", adapter())
return getattr(session, method)(url, *args, **kwargs)
except requests.exceptions.SSLError as e:
err = e
raise err
def get_tls_fallback(url, *args, **kwargs):
return method_tls_fallback(url, "get", *args, **kwargs)
def post_tls_fallback(url, *args, **kwargs):
return method_tls_fallback(url, "post", *args, **kwargs)