forked from ProtonMail/proton-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert_pinning.py
185 lines (165 loc) · 5.45 KB
/
cert_pinning.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import base64
import hashlib
from ssl import DER_cert_to_PEM_cert
from OpenSSL import crypto
from requests.adapters import HTTPAdapter
from urllib3.connectionpool import HTTPSConnectionPool
from urllib3.poolmanager import PoolManager
from urllib3.util.timeout import Timeout
from .exceptions import TLSPinningError
from .constants import PUBKEY_HASH_DICT
class TLSPinningHTTPSConnectionPool(HTTPSConnectionPool):
"""Verify the certificate upon each connection"""
def __init__(
self,
host,
hash_dict,
port=None,
strict=False,
timeout=Timeout.DEFAULT_TIMEOUT,
maxsize=1,
block=False,
headers=None,
retries=None,
_proxy=None,
_proxy_headers=None,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
ssl_version=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
**conn_kw
):
self.hash_dict = hash_dict
# try/except is needed for multi-version compatibility,
# as number of args chane from version 16/18 to 20.
try:
super(TLSPinningHTTPSConnectionPool, self).__init__(
host,
port,
strict,
timeout,
maxsize,
block,
headers,
retries,
_proxy,
_proxy_headers,
key_file,
cert_file,
cert_reqs,
key_password,
ca_certs,
ssl_version,
assert_hostname,
assert_fingerprint,
ca_cert_dir,
**conn_kw
)
except TypeError:
super(TLSPinningHTTPSConnectionPool, self).__init__(
host,
port,
strict,
timeout,
maxsize,
block,
headers,
retries,
_proxy,
_proxy_headers,
key_file,
cert_file,
cert_reqs,
ca_certs,
ssl_version,
assert_hostname,
assert_fingerprint,
ca_cert_dir,
**conn_kw
)
def _validate_conn(self, conn):
super(TLSPinningHTTPSConnectionPool, self)._validate_conn(conn)
pem_certificate = self.__get_certificate(conn.sock)
self.ensure_session_is_secure(pem_certificate, conn)
def ensure_session_is_secure(self, cert, conn):
"""Check if connection is secure"""
cert_hash = self.__extract_hash(cert)
if not self.__is_hash_valid(cert_hash):
# Also generate a report
conn.close()
raise TLSPinningError("Insecure connection")
def __extract_hash(self, cert):
"""Extract encrypted hash from the certificate."""
cert_obj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
pubkey_obj = cert_obj.get_pubkey()
pubkey = crypto.dump_publickey(crypto.FILETYPE_ASN1, pubkey_obj)
spki_hash = hashlib.sha256(pubkey).digest()
cert_hash = base64.b64encode(spki_hash).decode('utf-8')
return cert_hash
def __is_hash_valid(self, cert_hash):
"""Validate the hash against a known list of hashes/pins.
Returns:
bool: False if hash is not valid
True if hash is valid
"""
# host is passed in __init__
try:
self.hash_dict[self.host].index(cert_hash)
except (ValueError, KeyError, TypeError):
pass
else:
return True
# try alt routing
try:
self.hash_dict["backup"].index(cert_hash)
except (ValueError, KeyError, TypeError):
return False
else:
return True
def __get_certificate(self, sock):
"""Extract and convert certificate to PEM format"""
certificate_binary_form = sock.getpeercert(True)
return DER_cert_to_PEM_cert(certificate_binary_form)
class TLSPinningPoolManager(PoolManager):
"""Attach TLSPinningHTTPSConnectionPool to TLSPinningPoolManager"""
def __init__(
self,
hash_dict,
num_pools=10,
headers=None,
**connection_pool_kw
):
self.hash_dict = hash_dict
super(TLSPinningPoolManager, self).__init__(
num_pools=10, headers=headers, **connection_pool_kw
)
def _new_pool(self, scheme, host, port, request_context):
if scheme != 'https':
return super(TLSPinningPoolManager, self)._new_pool(
scheme, host, port, request_context
)
return TLSPinningHTTPSConnectionPool(
host=host, port=port,
hash_dict=self.hash_dict, **self.connection_pool_kw
)
class TLSPinningAdapter(HTTPAdapter):
"""Attach TLSPinningPoolManager to TLSPinningAdapter"""
def __init__(self, hash_dict=PUBKEY_HASH_DICT):
self.hash_dict = hash_dict
super(TLSPinningAdapter, self).__init__()
def init_poolmanager(
self,
connections,
maxsize,
block=False,
**pool_kwargs
):
self.poolmanager = TLSPinningPoolManager(
num_pools=connections, maxsize=maxsize, block=block,
strict=True, hash_dict=self.hash_dict, **pool_kwargs
)