1 | n/a | # Wrapper module for _ssl, providing some additional facilities |
---|
2 | n/a | # implemented in Python. Written by Bill Janssen. |
---|
3 | n/a | |
---|
4 | n/a | """This module provides some more Pythonic support for SSL. |
---|
5 | n/a | |
---|
6 | n/a | Object types: |
---|
7 | n/a | |
---|
8 | n/a | SSLSocket -- subtype of socket.socket which does SSL over the socket |
---|
9 | n/a | |
---|
10 | n/a | Exceptions: |
---|
11 | n/a | |
---|
12 | n/a | SSLError -- exception raised for I/O errors |
---|
13 | n/a | |
---|
14 | n/a | Functions: |
---|
15 | n/a | |
---|
16 | n/a | cert_time_to_seconds -- convert time string used for certificate |
---|
17 | n/a | notBefore and notAfter functions to integer |
---|
18 | n/a | seconds past the Epoch (the time values |
---|
19 | n/a | returned from time.time()) |
---|
20 | n/a | |
---|
21 | n/a | fetch_server_certificate (HOST, PORT) -- fetch the certificate provided |
---|
22 | n/a | by the server running on HOST at port PORT. No |
---|
23 | n/a | validation of the certificate is performed. |
---|
24 | n/a | |
---|
25 | n/a | Integer constants: |
---|
26 | n/a | |
---|
27 | n/a | SSL_ERROR_ZERO_RETURN |
---|
28 | n/a | SSL_ERROR_WANT_READ |
---|
29 | n/a | SSL_ERROR_WANT_WRITE |
---|
30 | n/a | SSL_ERROR_WANT_X509_LOOKUP |
---|
31 | n/a | SSL_ERROR_SYSCALL |
---|
32 | n/a | SSL_ERROR_SSL |
---|
33 | n/a | SSL_ERROR_WANT_CONNECT |
---|
34 | n/a | |
---|
35 | n/a | SSL_ERROR_EOF |
---|
36 | n/a | SSL_ERROR_INVALID_ERROR_CODE |
---|
37 | n/a | |
---|
38 | n/a | The following group define certificate requirements that one side is |
---|
39 | n/a | allowing/requiring from the other side: |
---|
40 | n/a | |
---|
41 | n/a | CERT_NONE - no certificates from the other side are required (or will |
---|
42 | n/a | be looked at if provided) |
---|
43 | n/a | CERT_OPTIONAL - certificates are not required, but if provided will be |
---|
44 | n/a | validated, and if validation fails, the connection will |
---|
45 | n/a | also fail |
---|
46 | n/a | CERT_REQUIRED - certificates are required, and will be validated, and |
---|
47 | n/a | if validation fails, the connection will also fail |
---|
48 | n/a | |
---|
49 | n/a | The following constants identify various SSL protocol variants: |
---|
50 | n/a | |
---|
51 | n/a | PROTOCOL_SSLv2 |
---|
52 | n/a | PROTOCOL_SSLv3 |
---|
53 | n/a | PROTOCOL_SSLv23 |
---|
54 | n/a | PROTOCOL_TLS |
---|
55 | n/a | PROTOCOL_TLS_CLIENT |
---|
56 | n/a | PROTOCOL_TLS_SERVER |
---|
57 | n/a | PROTOCOL_TLSv1 |
---|
58 | n/a | PROTOCOL_TLSv1_1 |
---|
59 | n/a | PROTOCOL_TLSv1_2 |
---|
60 | n/a | |
---|
61 | n/a | The following constants identify various SSL alert message descriptions as per |
---|
62 | n/a | http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 |
---|
63 | n/a | |
---|
64 | n/a | ALERT_DESCRIPTION_CLOSE_NOTIFY |
---|
65 | n/a | ALERT_DESCRIPTION_UNEXPECTED_MESSAGE |
---|
66 | n/a | ALERT_DESCRIPTION_BAD_RECORD_MAC |
---|
67 | n/a | ALERT_DESCRIPTION_RECORD_OVERFLOW |
---|
68 | n/a | ALERT_DESCRIPTION_DECOMPRESSION_FAILURE |
---|
69 | n/a | ALERT_DESCRIPTION_HANDSHAKE_FAILURE |
---|
70 | n/a | ALERT_DESCRIPTION_BAD_CERTIFICATE |
---|
71 | n/a | ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE |
---|
72 | n/a | ALERT_DESCRIPTION_CERTIFICATE_REVOKED |
---|
73 | n/a | ALERT_DESCRIPTION_CERTIFICATE_EXPIRED |
---|
74 | n/a | ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN |
---|
75 | n/a | ALERT_DESCRIPTION_ILLEGAL_PARAMETER |
---|
76 | n/a | ALERT_DESCRIPTION_UNKNOWN_CA |
---|
77 | n/a | ALERT_DESCRIPTION_ACCESS_DENIED |
---|
78 | n/a | ALERT_DESCRIPTION_DECODE_ERROR |
---|
79 | n/a | ALERT_DESCRIPTION_DECRYPT_ERROR |
---|
80 | n/a | ALERT_DESCRIPTION_PROTOCOL_VERSION |
---|
81 | n/a | ALERT_DESCRIPTION_INSUFFICIENT_SECURITY |
---|
82 | n/a | ALERT_DESCRIPTION_INTERNAL_ERROR |
---|
83 | n/a | ALERT_DESCRIPTION_USER_CANCELLED |
---|
84 | n/a | ALERT_DESCRIPTION_NO_RENEGOTIATION |
---|
85 | n/a | ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION |
---|
86 | n/a | ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE |
---|
87 | n/a | ALERT_DESCRIPTION_UNRECOGNIZED_NAME |
---|
88 | n/a | ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE |
---|
89 | n/a | ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE |
---|
90 | n/a | ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY |
---|
91 | n/a | """ |
---|
92 | n/a | |
---|
93 | n/a | import ipaddress |
---|
94 | n/a | import textwrap |
---|
95 | n/a | import re |
---|
96 | n/a | import sys |
---|
97 | n/a | import os |
---|
98 | n/a | from collections import namedtuple |
---|
99 | n/a | from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag |
---|
100 | n/a | |
---|
101 | n/a | import _ssl # if we can't import it, let the error propagate |
---|
102 | n/a | |
---|
103 | n/a | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
---|
104 | n/a | from _ssl import _SSLContext, MemoryBIO, SSLSession |
---|
105 | n/a | from _ssl import ( |
---|
106 | n/a | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
---|
107 | n/a | SSLSyscallError, SSLEOFError, |
---|
108 | n/a | ) |
---|
109 | n/a | from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj |
---|
110 | n/a | from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes |
---|
111 | n/a | try: |
---|
112 | n/a | from _ssl import RAND_egd |
---|
113 | n/a | except ImportError: |
---|
114 | n/a | # LibreSSL does not provide RAND_egd |
---|
115 | n/a | pass |
---|
116 | n/a | |
---|
117 | n/a | |
---|
118 | n/a | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN |
---|
119 | n/a | from _ssl import _OPENSSL_API_VERSION |
---|
120 | n/a | |
---|
121 | n/a | |
---|
122 | n/a | _IntEnum._convert( |
---|
123 | n/a | '_SSLMethod', __name__, |
---|
124 | n/a | lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23', |
---|
125 | n/a | source=_ssl) |
---|
126 | n/a | |
---|
127 | n/a | _IntFlag._convert( |
---|
128 | n/a | 'Options', __name__, |
---|
129 | n/a | lambda name: name.startswith('OP_'), |
---|
130 | n/a | source=_ssl) |
---|
131 | n/a | |
---|
132 | n/a | _IntEnum._convert( |
---|
133 | n/a | 'AlertDescription', __name__, |
---|
134 | n/a | lambda name: name.startswith('ALERT_DESCRIPTION_'), |
---|
135 | n/a | source=_ssl) |
---|
136 | n/a | |
---|
137 | n/a | _IntEnum._convert( |
---|
138 | n/a | 'SSLErrorNumber', __name__, |
---|
139 | n/a | lambda name: name.startswith('SSL_ERROR_'), |
---|
140 | n/a | source=_ssl) |
---|
141 | n/a | |
---|
142 | n/a | _IntFlag._convert( |
---|
143 | n/a | 'VerifyFlags', __name__, |
---|
144 | n/a | lambda name: name.startswith('VERIFY_'), |
---|
145 | n/a | source=_ssl) |
---|
146 | n/a | |
---|
147 | n/a | _IntEnum._convert( |
---|
148 | n/a | 'VerifyMode', __name__, |
---|
149 | n/a | lambda name: name.startswith('CERT_'), |
---|
150 | n/a | source=_ssl) |
---|
151 | n/a | |
---|
152 | n/a | |
---|
153 | n/a | PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS |
---|
154 | n/a | _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()} |
---|
155 | n/a | |
---|
156 | n/a | _SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None) |
---|
157 | n/a | |
---|
158 | n/a | |
---|
159 | n/a | if sys.platform == "win32": |
---|
160 | n/a | from _ssl import enum_certificates, enum_crls |
---|
161 | n/a | |
---|
162 | n/a | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
---|
163 | n/a | from socket import SOL_SOCKET, SO_TYPE |
---|
164 | n/a | import base64 # for DER-to-PEM translation |
---|
165 | n/a | import errno |
---|
166 | n/a | import warnings |
---|
167 | n/a | |
---|
168 | n/a | |
---|
169 | n/a | socket_error = OSError # keep that public name in module namespace |
---|
170 | n/a | |
---|
171 | n/a | if _ssl.HAS_TLS_UNIQUE: |
---|
172 | n/a | CHANNEL_BINDING_TYPES = ['tls-unique'] |
---|
173 | n/a | else: |
---|
174 | n/a | CHANNEL_BINDING_TYPES = [] |
---|
175 | n/a | |
---|
176 | n/a | |
---|
177 | n/a | # Disable weak or insecure ciphers by default |
---|
178 | n/a | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
---|
179 | n/a | # Enable a better set of ciphers by default |
---|
180 | n/a | # This list has been explicitly chosen to: |
---|
181 | n/a | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
---|
182 | n/a | # * Prefer ECDHE over DHE for better performance |
---|
183 | n/a | # * Prefer AEAD over CBC for better performance and security |
---|
184 | n/a | # * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI |
---|
185 | n/a | # (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2) |
---|
186 | n/a | # * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better |
---|
187 | n/a | # performance and security |
---|
188 | n/a | # * Then Use HIGH cipher suites as a fallback |
---|
189 | n/a | # * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs |
---|
190 | n/a | # for security reasons |
---|
191 | n/a | _DEFAULT_CIPHERS = ( |
---|
192 | n/a | 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:' |
---|
193 | n/a | 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:' |
---|
194 | n/a | '!aNULL:!eNULL:!MD5:!3DES' |
---|
195 | n/a | ) |
---|
196 | n/a | |
---|
197 | n/a | # Restricted and more secure ciphers for the server side |
---|
198 | n/a | # This list has been explicitly chosen to: |
---|
199 | n/a | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
---|
200 | n/a | # * Prefer ECDHE over DHE for better performance |
---|
201 | n/a | # * Prefer AEAD over CBC for better performance and security |
---|
202 | n/a | # * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI |
---|
203 | n/a | # * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better |
---|
204 | n/a | # performance and security |
---|
205 | n/a | # * Then Use HIGH cipher suites as a fallback |
---|
206 | n/a | # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and |
---|
207 | n/a | # 3DES for security reasons |
---|
208 | n/a | _RESTRICTED_SERVER_CIPHERS = ( |
---|
209 | n/a | 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:' |
---|
210 | n/a | 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:' |
---|
211 | n/a | '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES' |
---|
212 | n/a | ) |
---|
213 | n/a | |
---|
214 | n/a | |
---|
215 | n/a | class CertificateError(ValueError): |
---|
216 | n/a | pass |
---|
217 | n/a | |
---|
218 | n/a | |
---|
219 | n/a | def _dnsname_match(dn, hostname, max_wildcards=1): |
---|
220 | n/a | """Matching according to RFC 6125, section 6.4.3 |
---|
221 | n/a | |
---|
222 | n/a | http://tools.ietf.org/html/rfc6125#section-6.4.3 |
---|
223 | n/a | """ |
---|
224 | n/a | pats = [] |
---|
225 | n/a | if not dn: |
---|
226 | n/a | return False |
---|
227 | n/a | |
---|
228 | n/a | leftmost, *remainder = dn.split(r'.') |
---|
229 | n/a | |
---|
230 | n/a | wildcards = leftmost.count('*') |
---|
231 | n/a | if wildcards > max_wildcards: |
---|
232 | n/a | # Issue #17980: avoid denials of service by refusing more |
---|
233 | n/a | # than one wildcard per fragment. A survey of established |
---|
234 | n/a | # policy among SSL implementations showed it to be a |
---|
235 | n/a | # reasonable choice. |
---|
236 | n/a | raise CertificateError( |
---|
237 | n/a | "too many wildcards in certificate DNS name: " + repr(dn)) |
---|
238 | n/a | |
---|
239 | n/a | # speed up common case w/o wildcards |
---|
240 | n/a | if not wildcards: |
---|
241 | n/a | return dn.lower() == hostname.lower() |
---|
242 | n/a | |
---|
243 | n/a | # RFC 6125, section 6.4.3, subitem 1. |
---|
244 | n/a | # The client SHOULD NOT attempt to match a presented identifier in which |
---|
245 | n/a | # the wildcard character comprises a label other than the left-most label. |
---|
246 | n/a | if leftmost == '*': |
---|
247 | n/a | # When '*' is a fragment by itself, it matches a non-empty dotless |
---|
248 | n/a | # fragment. |
---|
249 | n/a | pats.append('[^.]+') |
---|
250 | n/a | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
---|
251 | n/a | # RFC 6125, section 6.4.3, subitem 3. |
---|
252 | n/a | # The client SHOULD NOT attempt to match a presented identifier |
---|
253 | n/a | # where the wildcard character is embedded within an A-label or |
---|
254 | n/a | # U-label of an internationalized domain name. |
---|
255 | n/a | pats.append(re.escape(leftmost)) |
---|
256 | n/a | else: |
---|
257 | n/a | # Otherwise, '*' matches any dotless string, e.g. www* |
---|
258 | n/a | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
---|
259 | n/a | |
---|
260 | n/a | # add the remaining fragments, ignore any wildcards |
---|
261 | n/a | for frag in remainder: |
---|
262 | n/a | pats.append(re.escape(frag)) |
---|
263 | n/a | |
---|
264 | n/a | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
---|
265 | n/a | return pat.match(hostname) |
---|
266 | n/a | |
---|
267 | n/a | |
---|
268 | n/a | def _ipaddress_match(ipname, host_ip): |
---|
269 | n/a | """Exact matching of IP addresses. |
---|
270 | n/a | |
---|
271 | n/a | RFC 6125 explicitly doesn't define an algorithm for this |
---|
272 | n/a | (section 1.7.2 - "Out of Scope"). |
---|
273 | n/a | """ |
---|
274 | n/a | # OpenSSL may add a trailing newline to a subjectAltName's IP address |
---|
275 | n/a | ip = ipaddress.ip_address(ipname.rstrip()) |
---|
276 | n/a | return ip == host_ip |
---|
277 | n/a | |
---|
278 | n/a | |
---|
279 | n/a | def match_hostname(cert, hostname): |
---|
280 | n/a | """Verify that *cert* (in decoded format as returned by |
---|
281 | n/a | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
---|
282 | n/a | rules are followed, but IP addresses are not accepted for *hostname*. |
---|
283 | n/a | |
---|
284 | n/a | CertificateError is raised on failure. On success, the function |
---|
285 | n/a | returns nothing. |
---|
286 | n/a | """ |
---|
287 | n/a | if not cert: |
---|
288 | n/a | raise ValueError("empty or no certificate, match_hostname needs a " |
---|
289 | n/a | "SSL socket or SSL context with either " |
---|
290 | n/a | "CERT_OPTIONAL or CERT_REQUIRED") |
---|
291 | n/a | try: |
---|
292 | n/a | host_ip = ipaddress.ip_address(hostname) |
---|
293 | n/a | except ValueError: |
---|
294 | n/a | # Not an IP address (common case) |
---|
295 | n/a | host_ip = None |
---|
296 | n/a | dnsnames = [] |
---|
297 | n/a | san = cert.get('subjectAltName', ()) |
---|
298 | n/a | for key, value in san: |
---|
299 | n/a | if key == 'DNS': |
---|
300 | n/a | if host_ip is None and _dnsname_match(value, hostname): |
---|
301 | n/a | return |
---|
302 | n/a | dnsnames.append(value) |
---|
303 | n/a | elif key == 'IP Address': |
---|
304 | n/a | if host_ip is not None and _ipaddress_match(value, host_ip): |
---|
305 | n/a | return |
---|
306 | n/a | dnsnames.append(value) |
---|
307 | n/a | if not dnsnames: |
---|
308 | n/a | # The subject is only checked when there is no dNSName entry |
---|
309 | n/a | # in subjectAltName |
---|
310 | n/a | for sub in cert.get('subject', ()): |
---|
311 | n/a | for key, value in sub: |
---|
312 | n/a | # XXX according to RFC 2818, the most specific Common Name |
---|
313 | n/a | # must be used. |
---|
314 | n/a | if key == 'commonName': |
---|
315 | n/a | if _dnsname_match(value, hostname): |
---|
316 | n/a | return |
---|
317 | n/a | dnsnames.append(value) |
---|
318 | n/a | if len(dnsnames) > 1: |
---|
319 | n/a | raise CertificateError("hostname %r " |
---|
320 | n/a | "doesn't match either of %s" |
---|
321 | n/a | % (hostname, ', '.join(map(repr, dnsnames)))) |
---|
322 | n/a | elif len(dnsnames) == 1: |
---|
323 | n/a | raise CertificateError("hostname %r " |
---|
324 | n/a | "doesn't match %r" |
---|
325 | n/a | % (hostname, dnsnames[0])) |
---|
326 | n/a | else: |
---|
327 | n/a | raise CertificateError("no appropriate commonName or " |
---|
328 | n/a | "subjectAltName fields were found") |
---|
329 | n/a | |
---|
330 | n/a | |
---|
331 | n/a | DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", |
---|
332 | n/a | "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " |
---|
333 | n/a | "openssl_capath") |
---|
334 | n/a | |
---|
335 | n/a | def get_default_verify_paths(): |
---|
336 | n/a | """Return paths to default cafile and capath. |
---|
337 | n/a | """ |
---|
338 | n/a | parts = _ssl.get_default_verify_paths() |
---|
339 | n/a | |
---|
340 | n/a | # environment vars shadow paths |
---|
341 | n/a | cafile = os.environ.get(parts[0], parts[1]) |
---|
342 | n/a | capath = os.environ.get(parts[2], parts[3]) |
---|
343 | n/a | |
---|
344 | n/a | return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, |
---|
345 | n/a | capath if os.path.isdir(capath) else None, |
---|
346 | n/a | *parts) |
---|
347 | n/a | |
---|
348 | n/a | |
---|
349 | n/a | class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")): |
---|
350 | n/a | """ASN.1 object identifier lookup |
---|
351 | n/a | """ |
---|
352 | n/a | __slots__ = () |
---|
353 | n/a | |
---|
354 | n/a | def __new__(cls, oid): |
---|
355 | n/a | return super().__new__(cls, *_txt2obj(oid, name=False)) |
---|
356 | n/a | |
---|
357 | n/a | @classmethod |
---|
358 | n/a | def fromnid(cls, nid): |
---|
359 | n/a | """Create _ASN1Object from OpenSSL numeric ID |
---|
360 | n/a | """ |
---|
361 | n/a | return super().__new__(cls, *_nid2obj(nid)) |
---|
362 | n/a | |
---|
363 | n/a | @classmethod |
---|
364 | n/a | def fromname(cls, name): |
---|
365 | n/a | """Create _ASN1Object from short name, long name or OID |
---|
366 | n/a | """ |
---|
367 | n/a | return super().__new__(cls, *_txt2obj(name, name=True)) |
---|
368 | n/a | |
---|
369 | n/a | |
---|
370 | n/a | class Purpose(_ASN1Object, _Enum): |
---|
371 | n/a | """SSLContext purpose flags with X509v3 Extended Key Usage objects |
---|
372 | n/a | """ |
---|
373 | n/a | SERVER_AUTH = '1.3.6.1.5.5.7.3.1' |
---|
374 | n/a | CLIENT_AUTH = '1.3.6.1.5.5.7.3.2' |
---|
375 | n/a | |
---|
376 | n/a | |
---|
377 | n/a | class SSLContext(_SSLContext): |
---|
378 | n/a | """An SSLContext holds various SSL-related configuration options and |
---|
379 | n/a | data, such as certificates and possibly a private key.""" |
---|
380 | n/a | |
---|
381 | n/a | __slots__ = ('protocol', '__weakref__') |
---|
382 | n/a | _windows_cert_stores = ("CA", "ROOT") |
---|
383 | n/a | |
---|
384 | n/a | def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs): |
---|
385 | n/a | self = _SSLContext.__new__(cls, protocol) |
---|
386 | n/a | if protocol != _SSLv2_IF_EXISTS: |
---|
387 | n/a | self.set_ciphers(_DEFAULT_CIPHERS) |
---|
388 | n/a | return self |
---|
389 | n/a | |
---|
390 | n/a | def __init__(self, protocol=PROTOCOL_TLS): |
---|
391 | n/a | self.protocol = protocol |
---|
392 | n/a | |
---|
393 | n/a | def wrap_socket(self, sock, server_side=False, |
---|
394 | n/a | do_handshake_on_connect=True, |
---|
395 | n/a | suppress_ragged_eofs=True, |
---|
396 | n/a | server_hostname=None, session=None): |
---|
397 | n/a | return SSLSocket(sock=sock, server_side=server_side, |
---|
398 | n/a | do_handshake_on_connect=do_handshake_on_connect, |
---|
399 | n/a | suppress_ragged_eofs=suppress_ragged_eofs, |
---|
400 | n/a | server_hostname=server_hostname, |
---|
401 | n/a | _context=self, _session=session) |
---|
402 | n/a | |
---|
403 | n/a | def wrap_bio(self, incoming, outgoing, server_side=False, |
---|
404 | n/a | server_hostname=None, session=None): |
---|
405 | n/a | sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side, |
---|
406 | n/a | server_hostname=server_hostname) |
---|
407 | n/a | return SSLObject(sslobj, session=session) |
---|
408 | n/a | |
---|
409 | n/a | def set_npn_protocols(self, npn_protocols): |
---|
410 | n/a | protos = bytearray() |
---|
411 | n/a | for protocol in npn_protocols: |
---|
412 | n/a | b = bytes(protocol, 'ascii') |
---|
413 | n/a | if len(b) == 0 or len(b) > 255: |
---|
414 | n/a | raise SSLError('NPN protocols must be 1 to 255 in length') |
---|
415 | n/a | protos.append(len(b)) |
---|
416 | n/a | protos.extend(b) |
---|
417 | n/a | |
---|
418 | n/a | self._set_npn_protocols(protos) |
---|
419 | n/a | |
---|
420 | n/a | def set_alpn_protocols(self, alpn_protocols): |
---|
421 | n/a | protos = bytearray() |
---|
422 | n/a | for protocol in alpn_protocols: |
---|
423 | n/a | b = bytes(protocol, 'ascii') |
---|
424 | n/a | if len(b) == 0 or len(b) > 255: |
---|
425 | n/a | raise SSLError('ALPN protocols must be 1 to 255 in length') |
---|
426 | n/a | protos.append(len(b)) |
---|
427 | n/a | protos.extend(b) |
---|
428 | n/a | |
---|
429 | n/a | self._set_alpn_protocols(protos) |
---|
430 | n/a | |
---|
431 | n/a | def _load_windows_store_certs(self, storename, purpose): |
---|
432 | n/a | certs = bytearray() |
---|
433 | n/a | try: |
---|
434 | n/a | for cert, encoding, trust in enum_certificates(storename): |
---|
435 | n/a | # CA certs are never PKCS#7 encoded |
---|
436 | n/a | if encoding == "x509_asn": |
---|
437 | n/a | if trust is True or purpose.oid in trust: |
---|
438 | n/a | certs.extend(cert) |
---|
439 | n/a | except PermissionError: |
---|
440 | n/a | warnings.warn("unable to enumerate Windows certificate store") |
---|
441 | n/a | if certs: |
---|
442 | n/a | self.load_verify_locations(cadata=certs) |
---|
443 | n/a | return certs |
---|
444 | n/a | |
---|
445 | n/a | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
---|
446 | n/a | if not isinstance(purpose, _ASN1Object): |
---|
447 | n/a | raise TypeError(purpose) |
---|
448 | n/a | if sys.platform == "win32": |
---|
449 | n/a | for storename in self._windows_cert_stores: |
---|
450 | n/a | self._load_windows_store_certs(storename, purpose) |
---|
451 | n/a | self.set_default_verify_paths() |
---|
452 | n/a | |
---|
453 | n/a | @property |
---|
454 | n/a | def options(self): |
---|
455 | n/a | return Options(super().options) |
---|
456 | n/a | |
---|
457 | n/a | @options.setter |
---|
458 | n/a | def options(self, value): |
---|
459 | n/a | super(SSLContext, SSLContext).options.__set__(self, value) |
---|
460 | n/a | |
---|
461 | n/a | @property |
---|
462 | n/a | def verify_flags(self): |
---|
463 | n/a | return VerifyFlags(super().verify_flags) |
---|
464 | n/a | |
---|
465 | n/a | @verify_flags.setter |
---|
466 | n/a | def verify_flags(self, value): |
---|
467 | n/a | super(SSLContext, SSLContext).verify_flags.__set__(self, value) |
---|
468 | n/a | |
---|
469 | n/a | @property |
---|
470 | n/a | def verify_mode(self): |
---|
471 | n/a | value = super().verify_mode |
---|
472 | n/a | try: |
---|
473 | n/a | return VerifyMode(value) |
---|
474 | n/a | except ValueError: |
---|
475 | n/a | return value |
---|
476 | n/a | |
---|
477 | n/a | @verify_mode.setter |
---|
478 | n/a | def verify_mode(self, value): |
---|
479 | n/a | super(SSLContext, SSLContext).verify_mode.__set__(self, value) |
---|
480 | n/a | |
---|
481 | n/a | |
---|
482 | n/a | def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, |
---|
483 | n/a | capath=None, cadata=None): |
---|
484 | n/a | """Create a SSLContext object with default settings. |
---|
485 | n/a | |
---|
486 | n/a | NOTE: The protocol and settings may change anytime without prior |
---|
487 | n/a | deprecation. The values represent a fair balance between maximum |
---|
488 | n/a | compatibility and security. |
---|
489 | n/a | """ |
---|
490 | n/a | if not isinstance(purpose, _ASN1Object): |
---|
491 | n/a | raise TypeError(purpose) |
---|
492 | n/a | |
---|
493 | n/a | # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, |
---|
494 | n/a | # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE |
---|
495 | n/a | # by default. |
---|
496 | n/a | context = SSLContext(PROTOCOL_TLS) |
---|
497 | n/a | |
---|
498 | n/a | if purpose == Purpose.SERVER_AUTH: |
---|
499 | n/a | # verify certs and host name in client mode |
---|
500 | n/a | context.verify_mode = CERT_REQUIRED |
---|
501 | n/a | context.check_hostname = True |
---|
502 | n/a | elif purpose == Purpose.CLIENT_AUTH: |
---|
503 | n/a | context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) |
---|
504 | n/a | |
---|
505 | n/a | if cafile or capath or cadata: |
---|
506 | n/a | context.load_verify_locations(cafile, capath, cadata) |
---|
507 | n/a | elif context.verify_mode != CERT_NONE: |
---|
508 | n/a | # no explicit cafile, capath or cadata but the verify mode is |
---|
509 | n/a | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
---|
510 | n/a | # root CA certificates for the given purpose. This may fail silently. |
---|
511 | n/a | context.load_default_certs(purpose) |
---|
512 | n/a | return context |
---|
513 | n/a | |
---|
514 | n/a | def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None, |
---|
515 | n/a | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
---|
516 | n/a | certfile=None, keyfile=None, |
---|
517 | n/a | cafile=None, capath=None, cadata=None): |
---|
518 | n/a | """Create a SSLContext object for Python stdlib modules |
---|
519 | n/a | |
---|
520 | n/a | All Python stdlib modules shall use this function to create SSLContext |
---|
521 | n/a | objects in order to keep common settings in one place. The configuration |
---|
522 | n/a | is less restrict than create_default_context()'s to increase backward |
---|
523 | n/a | compatibility. |
---|
524 | n/a | """ |
---|
525 | n/a | if not isinstance(purpose, _ASN1Object): |
---|
526 | n/a | raise TypeError(purpose) |
---|
527 | n/a | |
---|
528 | n/a | # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, |
---|
529 | n/a | # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE |
---|
530 | n/a | # by default. |
---|
531 | n/a | context = SSLContext(protocol) |
---|
532 | n/a | |
---|
533 | n/a | if cert_reqs is not None: |
---|
534 | n/a | context.verify_mode = cert_reqs |
---|
535 | n/a | context.check_hostname = check_hostname |
---|
536 | n/a | |
---|
537 | n/a | if keyfile and not certfile: |
---|
538 | n/a | raise ValueError("certfile must be specified") |
---|
539 | n/a | if certfile or keyfile: |
---|
540 | n/a | context.load_cert_chain(certfile, keyfile) |
---|
541 | n/a | |
---|
542 | n/a | # load CA root certs |
---|
543 | n/a | if cafile or capath or cadata: |
---|
544 | n/a | context.load_verify_locations(cafile, capath, cadata) |
---|
545 | n/a | elif context.verify_mode != CERT_NONE: |
---|
546 | n/a | # no explicit cafile, capath or cadata but the verify mode is |
---|
547 | n/a | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
---|
548 | n/a | # root CA certificates for the given purpose. This may fail silently. |
---|
549 | n/a | context.load_default_certs(purpose) |
---|
550 | n/a | |
---|
551 | n/a | return context |
---|
552 | n/a | |
---|
553 | n/a | # Used by http.client if no context is explicitly passed. |
---|
554 | n/a | _create_default_https_context = create_default_context |
---|
555 | n/a | |
---|
556 | n/a | |
---|
557 | n/a | # Backwards compatibility alias, even though it's not a public name. |
---|
558 | n/a | _create_stdlib_context = _create_unverified_context |
---|
559 | n/a | |
---|
560 | n/a | |
---|
561 | n/a | class SSLObject: |
---|
562 | n/a | """This class implements an interface on top of a low-level SSL object as |
---|
563 | n/a | implemented by OpenSSL. This object captures the state of an SSL connection |
---|
564 | n/a | but does not provide any network IO itself. IO needs to be performed |
---|
565 | n/a | through separate "BIO" objects which are OpenSSL's IO abstraction layer. |
---|
566 | n/a | |
---|
567 | n/a | This class does not have a public constructor. Instances are returned by |
---|
568 | n/a | ``SSLContext.wrap_bio``. This class is typically used by framework authors |
---|
569 | n/a | that want to implement asynchronous IO for SSL through memory buffers. |
---|
570 | n/a | |
---|
571 | n/a | When compared to ``SSLSocket``, this object lacks the following features: |
---|
572 | n/a | |
---|
573 | n/a | * Any form of network IO incluging methods such as ``recv`` and ``send``. |
---|
574 | n/a | * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. |
---|
575 | n/a | """ |
---|
576 | n/a | |
---|
577 | n/a | def __init__(self, sslobj, owner=None, session=None): |
---|
578 | n/a | self._sslobj = sslobj |
---|
579 | n/a | # Note: _sslobj takes a weak reference to owner |
---|
580 | n/a | self._sslobj.owner = owner or self |
---|
581 | n/a | if session is not None: |
---|
582 | n/a | self._sslobj.session = session |
---|
583 | n/a | |
---|
584 | n/a | @property |
---|
585 | n/a | def context(self): |
---|
586 | n/a | """The SSLContext that is currently in use.""" |
---|
587 | n/a | return self._sslobj.context |
---|
588 | n/a | |
---|
589 | n/a | @context.setter |
---|
590 | n/a | def context(self, ctx): |
---|
591 | n/a | self._sslobj.context = ctx |
---|
592 | n/a | |
---|
593 | n/a | @property |
---|
594 | n/a | def session(self): |
---|
595 | n/a | """The SSLSession for client socket.""" |
---|
596 | n/a | return self._sslobj.session |
---|
597 | n/a | |
---|
598 | n/a | @session.setter |
---|
599 | n/a | def session(self, session): |
---|
600 | n/a | self._sslobj.session = session |
---|
601 | n/a | |
---|
602 | n/a | @property |
---|
603 | n/a | def session_reused(self): |
---|
604 | n/a | """Was the client session reused during handshake""" |
---|
605 | n/a | return self._sslobj.session_reused |
---|
606 | n/a | |
---|
607 | n/a | @property |
---|
608 | n/a | def server_side(self): |
---|
609 | n/a | """Whether this is a server-side socket.""" |
---|
610 | n/a | return self._sslobj.server_side |
---|
611 | n/a | |
---|
612 | n/a | @property |
---|
613 | n/a | def server_hostname(self): |
---|
614 | n/a | """The currently set server hostname (for SNI), or ``None`` if no |
---|
615 | n/a | server hostame is set.""" |
---|
616 | n/a | return self._sslobj.server_hostname |
---|
617 | n/a | |
---|
618 | n/a | def read(self, len=1024, buffer=None): |
---|
619 | n/a | """Read up to 'len' bytes from the SSL object and return them. |
---|
620 | n/a | |
---|
621 | n/a | If 'buffer' is provided, read into this buffer and return the number of |
---|
622 | n/a | bytes read. |
---|
623 | n/a | """ |
---|
624 | n/a | if buffer is not None: |
---|
625 | n/a | v = self._sslobj.read(len, buffer) |
---|
626 | n/a | else: |
---|
627 | n/a | v = self._sslobj.read(len) |
---|
628 | n/a | return v |
---|
629 | n/a | |
---|
630 | n/a | def write(self, data): |
---|
631 | n/a | """Write 'data' to the SSL object and return the number of bytes |
---|
632 | n/a | written. |
---|
633 | n/a | |
---|
634 | n/a | The 'data' argument must support the buffer interface. |
---|
635 | n/a | """ |
---|
636 | n/a | return self._sslobj.write(data) |
---|
637 | n/a | |
---|
638 | n/a | def getpeercert(self, binary_form=False): |
---|
639 | n/a | """Returns a formatted version of the data in the certificate provided |
---|
640 | n/a | by the other end of the SSL channel. |
---|
641 | n/a | |
---|
642 | n/a | Return None if no certificate was provided, {} if a certificate was |
---|
643 | n/a | provided, but not validated. |
---|
644 | n/a | """ |
---|
645 | n/a | return self._sslobj.peer_certificate(binary_form) |
---|
646 | n/a | |
---|
647 | n/a | def selected_npn_protocol(self): |
---|
648 | n/a | """Return the currently selected NPN protocol as a string, or ``None`` |
---|
649 | n/a | if a next protocol was not negotiated or if NPN is not supported by one |
---|
650 | n/a | of the peers.""" |
---|
651 | n/a | if _ssl.HAS_NPN: |
---|
652 | n/a | return self._sslobj.selected_npn_protocol() |
---|
653 | n/a | |
---|
654 | n/a | def selected_alpn_protocol(self): |
---|
655 | n/a | """Return the currently selected ALPN protocol as a string, or ``None`` |
---|
656 | n/a | if a next protocol was not negotiated or if ALPN is not supported by one |
---|
657 | n/a | of the peers.""" |
---|
658 | n/a | if _ssl.HAS_ALPN: |
---|
659 | n/a | return self._sslobj.selected_alpn_protocol() |
---|
660 | n/a | |
---|
661 | n/a | def cipher(self): |
---|
662 | n/a | """Return the currently selected cipher as a 3-tuple ``(name, |
---|
663 | n/a | ssl_version, secret_bits)``.""" |
---|
664 | n/a | return self._sslobj.cipher() |
---|
665 | n/a | |
---|
666 | n/a | def shared_ciphers(self): |
---|
667 | n/a | """Return a list of ciphers shared by the client during the handshake or |
---|
668 | n/a | None if this is not a valid server connection. |
---|
669 | n/a | """ |
---|
670 | n/a | return self._sslobj.shared_ciphers() |
---|
671 | n/a | |
---|
672 | n/a | def compression(self): |
---|
673 | n/a | """Return the current compression algorithm in use, or ``None`` if |
---|
674 | n/a | compression was not negotiated or not supported by one of the peers.""" |
---|
675 | n/a | return self._sslobj.compression() |
---|
676 | n/a | |
---|
677 | n/a | def pending(self): |
---|
678 | n/a | """Return the number of bytes that can be read immediately.""" |
---|
679 | n/a | return self._sslobj.pending() |
---|
680 | n/a | |
---|
681 | n/a | def do_handshake(self): |
---|
682 | n/a | """Start the SSL/TLS handshake.""" |
---|
683 | n/a | self._sslobj.do_handshake() |
---|
684 | n/a | if self.context.check_hostname: |
---|
685 | n/a | if not self.server_hostname: |
---|
686 | n/a | raise ValueError("check_hostname needs server_hostname " |
---|
687 | n/a | "argument") |
---|
688 | n/a | match_hostname(self.getpeercert(), self.server_hostname) |
---|
689 | n/a | |
---|
690 | n/a | def unwrap(self): |
---|
691 | n/a | """Start the SSL shutdown handshake.""" |
---|
692 | n/a | return self._sslobj.shutdown() |
---|
693 | n/a | |
---|
694 | n/a | def get_channel_binding(self, cb_type="tls-unique"): |
---|
695 | n/a | """Get channel binding data for current connection. Raise ValueError |
---|
696 | n/a | if the requested `cb_type` is not supported. Return bytes of the data |
---|
697 | n/a | or None if the data is not available (e.g. before the handshake).""" |
---|
698 | n/a | if cb_type not in CHANNEL_BINDING_TYPES: |
---|
699 | n/a | raise ValueError("Unsupported channel binding type") |
---|
700 | n/a | if cb_type != "tls-unique": |
---|
701 | n/a | raise NotImplementedError( |
---|
702 | n/a | "{0} channel binding type not implemented" |
---|
703 | n/a | .format(cb_type)) |
---|
704 | n/a | return self._sslobj.tls_unique_cb() |
---|
705 | n/a | |
---|
706 | n/a | def version(self): |
---|
707 | n/a | """Return a string identifying the protocol version used by the |
---|
708 | n/a | current SSL channel. """ |
---|
709 | n/a | return self._sslobj.version() |
---|
710 | n/a | |
---|
711 | n/a | |
---|
712 | n/a | class SSLSocket(socket): |
---|
713 | n/a | """This class implements a subtype of socket.socket that wraps |
---|
714 | n/a | the underlying OS socket in an SSL context when necessary, and |
---|
715 | n/a | provides read and write methods over that channel.""" |
---|
716 | n/a | |
---|
717 | n/a | def __init__(self, sock=None, keyfile=None, certfile=None, |
---|
718 | n/a | server_side=False, cert_reqs=CERT_NONE, |
---|
719 | n/a | ssl_version=PROTOCOL_TLS, ca_certs=None, |
---|
720 | n/a | do_handshake_on_connect=True, |
---|
721 | n/a | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
---|
722 | n/a | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
---|
723 | n/a | server_hostname=None, |
---|
724 | n/a | _context=None, _session=None): |
---|
725 | n/a | |
---|
726 | n/a | if _context: |
---|
727 | n/a | self._context = _context |
---|
728 | n/a | else: |
---|
729 | n/a | if server_side and not certfile: |
---|
730 | n/a | raise ValueError("certfile must be specified for server-side " |
---|
731 | n/a | "operations") |
---|
732 | n/a | if keyfile and not certfile: |
---|
733 | n/a | raise ValueError("certfile must be specified") |
---|
734 | n/a | if certfile and not keyfile: |
---|
735 | n/a | keyfile = certfile |
---|
736 | n/a | self._context = SSLContext(ssl_version) |
---|
737 | n/a | self._context.verify_mode = cert_reqs |
---|
738 | n/a | if ca_certs: |
---|
739 | n/a | self._context.load_verify_locations(ca_certs) |
---|
740 | n/a | if certfile: |
---|
741 | n/a | self._context.load_cert_chain(certfile, keyfile) |
---|
742 | n/a | if npn_protocols: |
---|
743 | n/a | self._context.set_npn_protocols(npn_protocols) |
---|
744 | n/a | if ciphers: |
---|
745 | n/a | self._context.set_ciphers(ciphers) |
---|
746 | n/a | self.keyfile = keyfile |
---|
747 | n/a | self.certfile = certfile |
---|
748 | n/a | self.cert_reqs = cert_reqs |
---|
749 | n/a | self.ssl_version = ssl_version |
---|
750 | n/a | self.ca_certs = ca_certs |
---|
751 | n/a | self.ciphers = ciphers |
---|
752 | n/a | # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get |
---|
753 | n/a | # mixed in. |
---|
754 | n/a | if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: |
---|
755 | n/a | raise NotImplementedError("only stream sockets are supported") |
---|
756 | n/a | if server_side: |
---|
757 | n/a | if server_hostname: |
---|
758 | n/a | raise ValueError("server_hostname can only be specified " |
---|
759 | n/a | "in client mode") |
---|
760 | n/a | if _session is not None: |
---|
761 | n/a | raise ValueError("session can only be specified in " |
---|
762 | n/a | "client mode") |
---|
763 | n/a | if self._context.check_hostname and not server_hostname: |
---|
764 | n/a | raise ValueError("check_hostname requires server_hostname") |
---|
765 | n/a | self._session = _session |
---|
766 | n/a | self.server_side = server_side |
---|
767 | n/a | self.server_hostname = server_hostname |
---|
768 | n/a | self.do_handshake_on_connect = do_handshake_on_connect |
---|
769 | n/a | self.suppress_ragged_eofs = suppress_ragged_eofs |
---|
770 | n/a | if sock is not None: |
---|
771 | n/a | socket.__init__(self, |
---|
772 | n/a | family=sock.family, |
---|
773 | n/a | type=sock.type, |
---|
774 | n/a | proto=sock.proto, |
---|
775 | n/a | fileno=sock.fileno()) |
---|
776 | n/a | self.settimeout(sock.gettimeout()) |
---|
777 | n/a | sock.detach() |
---|
778 | n/a | elif fileno is not None: |
---|
779 | n/a | socket.__init__(self, fileno=fileno) |
---|
780 | n/a | else: |
---|
781 | n/a | socket.__init__(self, family=family, type=type, proto=proto) |
---|
782 | n/a | |
---|
783 | n/a | # See if we are connected |
---|
784 | n/a | try: |
---|
785 | n/a | self.getpeername() |
---|
786 | n/a | except OSError as e: |
---|
787 | n/a | if e.errno != errno.ENOTCONN: |
---|
788 | n/a | raise |
---|
789 | n/a | connected = False |
---|
790 | n/a | else: |
---|
791 | n/a | connected = True |
---|
792 | n/a | |
---|
793 | n/a | self._closed = False |
---|
794 | n/a | self._sslobj = None |
---|
795 | n/a | self._connected = connected |
---|
796 | n/a | if connected: |
---|
797 | n/a | # create the SSL object |
---|
798 | n/a | try: |
---|
799 | n/a | sslobj = self._context._wrap_socket(self, server_side, |
---|
800 | n/a | server_hostname) |
---|
801 | n/a | self._sslobj = SSLObject(sslobj, owner=self, |
---|
802 | n/a | session=self._session) |
---|
803 | n/a | if do_handshake_on_connect: |
---|
804 | n/a | timeout = self.gettimeout() |
---|
805 | n/a | if timeout == 0.0: |
---|
806 | n/a | # non-blocking |
---|
807 | n/a | raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") |
---|
808 | n/a | self.do_handshake() |
---|
809 | n/a | |
---|
810 | n/a | except (OSError, ValueError): |
---|
811 | n/a | self.close() |
---|
812 | n/a | raise |
---|
813 | n/a | |
---|
814 | n/a | @property |
---|
815 | n/a | def context(self): |
---|
816 | n/a | return self._context |
---|
817 | n/a | |
---|
818 | n/a | @context.setter |
---|
819 | n/a | def context(self, ctx): |
---|
820 | n/a | self._context = ctx |
---|
821 | n/a | self._sslobj.context = ctx |
---|
822 | n/a | |
---|
823 | n/a | @property |
---|
824 | n/a | def session(self): |
---|
825 | n/a | """The SSLSession for client socket.""" |
---|
826 | n/a | if self._sslobj is not None: |
---|
827 | n/a | return self._sslobj.session |
---|
828 | n/a | |
---|
829 | n/a | @session.setter |
---|
830 | n/a | def session(self, session): |
---|
831 | n/a | self._session = session |
---|
832 | n/a | if self._sslobj is not None: |
---|
833 | n/a | self._sslobj.session = session |
---|
834 | n/a | |
---|
835 | n/a | @property |
---|
836 | n/a | def session_reused(self): |
---|
837 | n/a | """Was the client session reused during handshake""" |
---|
838 | n/a | if self._sslobj is not None: |
---|
839 | n/a | return self._sslobj.session_reused |
---|
840 | n/a | |
---|
841 | n/a | def dup(self): |
---|
842 | n/a | raise NotImplemented("Can't dup() %s instances" % |
---|
843 | n/a | self.__class__.__name__) |
---|
844 | n/a | |
---|
845 | n/a | def _checkClosed(self, msg=None): |
---|
846 | n/a | # raise an exception here if you wish to check for spurious closes |
---|
847 | n/a | pass |
---|
848 | n/a | |
---|
849 | n/a | def _check_connected(self): |
---|
850 | n/a | if not self._connected: |
---|
851 | n/a | # getpeername() will raise ENOTCONN if the socket is really |
---|
852 | n/a | # not connected; note that we can be connected even without |
---|
853 | n/a | # _connected being set, e.g. if connect() first returned |
---|
854 | n/a | # EAGAIN. |
---|
855 | n/a | self.getpeername() |
---|
856 | n/a | |
---|
857 | n/a | def read(self, len=1024, buffer=None): |
---|
858 | n/a | """Read up to LEN bytes and return them. |
---|
859 | n/a | Return zero-length string on EOF.""" |
---|
860 | n/a | |
---|
861 | n/a | self._checkClosed() |
---|
862 | n/a | if not self._sslobj: |
---|
863 | n/a | raise ValueError("Read on closed or unwrapped SSL socket.") |
---|
864 | n/a | try: |
---|
865 | n/a | return self._sslobj.read(len, buffer) |
---|
866 | n/a | except SSLError as x: |
---|
867 | n/a | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
---|
868 | n/a | if buffer is not None: |
---|
869 | n/a | return 0 |
---|
870 | n/a | else: |
---|
871 | n/a | return b'' |
---|
872 | n/a | else: |
---|
873 | n/a | raise |
---|
874 | n/a | |
---|
875 | n/a | def write(self, data): |
---|
876 | n/a | """Write DATA to the underlying SSL channel. Returns |
---|
877 | n/a | number of bytes of DATA actually transmitted.""" |
---|
878 | n/a | |
---|
879 | n/a | self._checkClosed() |
---|
880 | n/a | if not self._sslobj: |
---|
881 | n/a | raise ValueError("Write on closed or unwrapped SSL socket.") |
---|
882 | n/a | return self._sslobj.write(data) |
---|
883 | n/a | |
---|
884 | n/a | def getpeercert(self, binary_form=False): |
---|
885 | n/a | """Returns a formatted version of the data in the |
---|
886 | n/a | certificate provided by the other end of the SSL channel. |
---|
887 | n/a | Return None if no certificate was provided, {} if a |
---|
888 | n/a | certificate was provided, but not validated.""" |
---|
889 | n/a | |
---|
890 | n/a | self._checkClosed() |
---|
891 | n/a | self._check_connected() |
---|
892 | n/a | return self._sslobj.getpeercert(binary_form) |
---|
893 | n/a | |
---|
894 | n/a | def selected_npn_protocol(self): |
---|
895 | n/a | self._checkClosed() |
---|
896 | n/a | if not self._sslobj or not _ssl.HAS_NPN: |
---|
897 | n/a | return None |
---|
898 | n/a | else: |
---|
899 | n/a | return self._sslobj.selected_npn_protocol() |
---|
900 | n/a | |
---|
901 | n/a | def selected_alpn_protocol(self): |
---|
902 | n/a | self._checkClosed() |
---|
903 | n/a | if not self._sslobj or not _ssl.HAS_ALPN: |
---|
904 | n/a | return None |
---|
905 | n/a | else: |
---|
906 | n/a | return self._sslobj.selected_alpn_protocol() |
---|
907 | n/a | |
---|
908 | n/a | def cipher(self): |
---|
909 | n/a | self._checkClosed() |
---|
910 | n/a | if not self._sslobj: |
---|
911 | n/a | return None |
---|
912 | n/a | else: |
---|
913 | n/a | return self._sslobj.cipher() |
---|
914 | n/a | |
---|
915 | n/a | def shared_ciphers(self): |
---|
916 | n/a | self._checkClosed() |
---|
917 | n/a | if not self._sslobj: |
---|
918 | n/a | return None |
---|
919 | n/a | return self._sslobj.shared_ciphers() |
---|
920 | n/a | |
---|
921 | n/a | def compression(self): |
---|
922 | n/a | self._checkClosed() |
---|
923 | n/a | if not self._sslobj: |
---|
924 | n/a | return None |
---|
925 | n/a | else: |
---|
926 | n/a | return self._sslobj.compression() |
---|
927 | n/a | |
---|
928 | n/a | def send(self, data, flags=0): |
---|
929 | n/a | self._checkClosed() |
---|
930 | n/a | if self._sslobj: |
---|
931 | n/a | if flags != 0: |
---|
932 | n/a | raise ValueError( |
---|
933 | n/a | "non-zero flags not allowed in calls to send() on %s" % |
---|
934 | n/a | self.__class__) |
---|
935 | n/a | return self._sslobj.write(data) |
---|
936 | n/a | else: |
---|
937 | n/a | return socket.send(self, data, flags) |
---|
938 | n/a | |
---|
939 | n/a | def sendto(self, data, flags_or_addr, addr=None): |
---|
940 | n/a | self._checkClosed() |
---|
941 | n/a | if self._sslobj: |
---|
942 | n/a | raise ValueError("sendto not allowed on instances of %s" % |
---|
943 | n/a | self.__class__) |
---|
944 | n/a | elif addr is None: |
---|
945 | n/a | return socket.sendto(self, data, flags_or_addr) |
---|
946 | n/a | else: |
---|
947 | n/a | return socket.sendto(self, data, flags_or_addr, addr) |
---|
948 | n/a | |
---|
949 | n/a | def sendmsg(self, *args, **kwargs): |
---|
950 | n/a | # Ensure programs don't send data unencrypted if they try to |
---|
951 | n/a | # use this method. |
---|
952 | n/a | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
---|
953 | n/a | self.__class__) |
---|
954 | n/a | |
---|
955 | n/a | def sendall(self, data, flags=0): |
---|
956 | n/a | self._checkClosed() |
---|
957 | n/a | if self._sslobj: |
---|
958 | n/a | if flags != 0: |
---|
959 | n/a | raise ValueError( |
---|
960 | n/a | "non-zero flags not allowed in calls to sendall() on %s" % |
---|
961 | n/a | self.__class__) |
---|
962 | n/a | amount = len(data) |
---|
963 | n/a | count = 0 |
---|
964 | n/a | while (count < amount): |
---|
965 | n/a | v = self.send(data[count:]) |
---|
966 | n/a | count += v |
---|
967 | n/a | else: |
---|
968 | n/a | return socket.sendall(self, data, flags) |
---|
969 | n/a | |
---|
970 | n/a | def sendfile(self, file, offset=0, count=None): |
---|
971 | n/a | """Send a file, possibly by using os.sendfile() if this is a |
---|
972 | n/a | clear-text socket. Return the total number of bytes sent. |
---|
973 | n/a | """ |
---|
974 | n/a | if self._sslobj is None: |
---|
975 | n/a | # os.sendfile() works with plain sockets only |
---|
976 | n/a | return super().sendfile(file, offset, count) |
---|
977 | n/a | else: |
---|
978 | n/a | return self._sendfile_use_send(file, offset, count) |
---|
979 | n/a | |
---|
980 | n/a | def recv(self, buflen=1024, flags=0): |
---|
981 | n/a | self._checkClosed() |
---|
982 | n/a | if self._sslobj: |
---|
983 | n/a | if flags != 0: |
---|
984 | n/a | raise ValueError( |
---|
985 | n/a | "non-zero flags not allowed in calls to recv() on %s" % |
---|
986 | n/a | self.__class__) |
---|
987 | n/a | return self.read(buflen) |
---|
988 | n/a | else: |
---|
989 | n/a | return socket.recv(self, buflen, flags) |
---|
990 | n/a | |
---|
991 | n/a | def recv_into(self, buffer, nbytes=None, flags=0): |
---|
992 | n/a | self._checkClosed() |
---|
993 | n/a | if buffer and (nbytes is None): |
---|
994 | n/a | nbytes = len(buffer) |
---|
995 | n/a | elif nbytes is None: |
---|
996 | n/a | nbytes = 1024 |
---|
997 | n/a | if self._sslobj: |
---|
998 | n/a | if flags != 0: |
---|
999 | n/a | raise ValueError( |
---|
1000 | n/a | "non-zero flags not allowed in calls to recv_into() on %s" % |
---|
1001 | n/a | self.__class__) |
---|
1002 | n/a | return self.read(nbytes, buffer) |
---|
1003 | n/a | else: |
---|
1004 | n/a | return socket.recv_into(self, buffer, nbytes, flags) |
---|
1005 | n/a | |
---|
1006 | n/a | def recvfrom(self, buflen=1024, flags=0): |
---|
1007 | n/a | self._checkClosed() |
---|
1008 | n/a | if self._sslobj: |
---|
1009 | n/a | raise ValueError("recvfrom not allowed on instances of %s" % |
---|
1010 | n/a | self.__class__) |
---|
1011 | n/a | else: |
---|
1012 | n/a | return socket.recvfrom(self, buflen, flags) |
---|
1013 | n/a | |
---|
1014 | n/a | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
---|
1015 | n/a | self._checkClosed() |
---|
1016 | n/a | if self._sslobj: |
---|
1017 | n/a | raise ValueError("recvfrom_into not allowed on instances of %s" % |
---|
1018 | n/a | self.__class__) |
---|
1019 | n/a | else: |
---|
1020 | n/a | return socket.recvfrom_into(self, buffer, nbytes, flags) |
---|
1021 | n/a | |
---|
1022 | n/a | def recvmsg(self, *args, **kwargs): |
---|
1023 | n/a | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
---|
1024 | n/a | self.__class__) |
---|
1025 | n/a | |
---|
1026 | n/a | def recvmsg_into(self, *args, **kwargs): |
---|
1027 | n/a | raise NotImplementedError("recvmsg_into not allowed on instances of " |
---|
1028 | n/a | "%s" % self.__class__) |
---|
1029 | n/a | |
---|
1030 | n/a | def pending(self): |
---|
1031 | n/a | self._checkClosed() |
---|
1032 | n/a | if self._sslobj: |
---|
1033 | n/a | return self._sslobj.pending() |
---|
1034 | n/a | else: |
---|
1035 | n/a | return 0 |
---|
1036 | n/a | |
---|
1037 | n/a | def shutdown(self, how): |
---|
1038 | n/a | self._checkClosed() |
---|
1039 | n/a | self._sslobj = None |
---|
1040 | n/a | socket.shutdown(self, how) |
---|
1041 | n/a | |
---|
1042 | n/a | def unwrap(self): |
---|
1043 | n/a | if self._sslobj: |
---|
1044 | n/a | s = self._sslobj.unwrap() |
---|
1045 | n/a | self._sslobj = None |
---|
1046 | n/a | return s |
---|
1047 | n/a | else: |
---|
1048 | n/a | raise ValueError("No SSL wrapper around " + str(self)) |
---|
1049 | n/a | |
---|
1050 | n/a | def _real_close(self): |
---|
1051 | n/a | self._sslobj = None |
---|
1052 | n/a | socket._real_close(self) |
---|
1053 | n/a | |
---|
1054 | n/a | def do_handshake(self, block=False): |
---|
1055 | n/a | """Perform a TLS/SSL handshake.""" |
---|
1056 | n/a | self._check_connected() |
---|
1057 | n/a | timeout = self.gettimeout() |
---|
1058 | n/a | try: |
---|
1059 | n/a | if timeout == 0.0 and block: |
---|
1060 | n/a | self.settimeout(None) |
---|
1061 | n/a | self._sslobj.do_handshake() |
---|
1062 | n/a | finally: |
---|
1063 | n/a | self.settimeout(timeout) |
---|
1064 | n/a | |
---|
1065 | n/a | def _real_connect(self, addr, connect_ex): |
---|
1066 | n/a | if self.server_side: |
---|
1067 | n/a | raise ValueError("can't connect in server-side mode") |
---|
1068 | n/a | # Here we assume that the socket is client-side, and not |
---|
1069 | n/a | # connected at the time of the call. We connect it, then wrap it. |
---|
1070 | n/a | if self._connected: |
---|
1071 | n/a | raise ValueError("attempt to connect already-connected SSLSocket!") |
---|
1072 | n/a | sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
---|
1073 | n/a | self._sslobj = SSLObject(sslobj, owner=self, |
---|
1074 | n/a | session=self._session) |
---|
1075 | n/a | try: |
---|
1076 | n/a | if connect_ex: |
---|
1077 | n/a | rc = socket.connect_ex(self, addr) |
---|
1078 | n/a | else: |
---|
1079 | n/a | rc = None |
---|
1080 | n/a | socket.connect(self, addr) |
---|
1081 | n/a | if not rc: |
---|
1082 | n/a | self._connected = True |
---|
1083 | n/a | if self.do_handshake_on_connect: |
---|
1084 | n/a | self.do_handshake() |
---|
1085 | n/a | return rc |
---|
1086 | n/a | except (OSError, ValueError): |
---|
1087 | n/a | self._sslobj = None |
---|
1088 | n/a | raise |
---|
1089 | n/a | |
---|
1090 | n/a | def connect(self, addr): |
---|
1091 | n/a | """Connects to remote ADDR, and then wraps the connection in |
---|
1092 | n/a | an SSL channel.""" |
---|
1093 | n/a | self._real_connect(addr, False) |
---|
1094 | n/a | |
---|
1095 | n/a | def connect_ex(self, addr): |
---|
1096 | n/a | """Connects to remote ADDR, and then wraps the connection in |
---|
1097 | n/a | an SSL channel.""" |
---|
1098 | n/a | return self._real_connect(addr, True) |
---|
1099 | n/a | |
---|
1100 | n/a | def accept(self): |
---|
1101 | n/a | """Accepts a new connection from a remote client, and returns |
---|
1102 | n/a | a tuple containing that new connection wrapped with a server-side |
---|
1103 | n/a | SSL channel, and the address of the remote client.""" |
---|
1104 | n/a | |
---|
1105 | n/a | newsock, addr = socket.accept(self) |
---|
1106 | n/a | newsock = self.context.wrap_socket(newsock, |
---|
1107 | n/a | do_handshake_on_connect=self.do_handshake_on_connect, |
---|
1108 | n/a | suppress_ragged_eofs=self.suppress_ragged_eofs, |
---|
1109 | n/a | server_side=True) |
---|
1110 | n/a | return newsock, addr |
---|
1111 | n/a | |
---|
1112 | n/a | def get_channel_binding(self, cb_type="tls-unique"): |
---|
1113 | n/a | """Get channel binding data for current connection. Raise ValueError |
---|
1114 | n/a | if the requested `cb_type` is not supported. Return bytes of the data |
---|
1115 | n/a | or None if the data is not available (e.g. before the handshake). |
---|
1116 | n/a | """ |
---|
1117 | n/a | if self._sslobj is None: |
---|
1118 | n/a | return None |
---|
1119 | n/a | return self._sslobj.get_channel_binding(cb_type) |
---|
1120 | n/a | |
---|
1121 | n/a | def version(self): |
---|
1122 | n/a | """ |
---|
1123 | n/a | Return a string identifying the protocol version used by the |
---|
1124 | n/a | current SSL channel, or None if there is no established channel. |
---|
1125 | n/a | """ |
---|
1126 | n/a | if self._sslobj is None: |
---|
1127 | n/a | return None |
---|
1128 | n/a | return self._sslobj.version() |
---|
1129 | n/a | |
---|
1130 | n/a | |
---|
1131 | n/a | def wrap_socket(sock, keyfile=None, certfile=None, |
---|
1132 | n/a | server_side=False, cert_reqs=CERT_NONE, |
---|
1133 | n/a | ssl_version=PROTOCOL_TLS, ca_certs=None, |
---|
1134 | n/a | do_handshake_on_connect=True, |
---|
1135 | n/a | suppress_ragged_eofs=True, |
---|
1136 | n/a | ciphers=None): |
---|
1137 | n/a | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
---|
1138 | n/a | server_side=server_side, cert_reqs=cert_reqs, |
---|
1139 | n/a | ssl_version=ssl_version, ca_certs=ca_certs, |
---|
1140 | n/a | do_handshake_on_connect=do_handshake_on_connect, |
---|
1141 | n/a | suppress_ragged_eofs=suppress_ragged_eofs, |
---|
1142 | n/a | ciphers=ciphers) |
---|
1143 | n/a | |
---|
1144 | n/a | # some utility functions |
---|
1145 | n/a | |
---|
1146 | n/a | def cert_time_to_seconds(cert_time): |
---|
1147 | n/a | """Return the time in seconds since the Epoch, given the timestring |
---|
1148 | n/a | representing the "notBefore" or "notAfter" date from a certificate |
---|
1149 | n/a | in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). |
---|
1150 | n/a | |
---|
1151 | n/a | "notBefore" or "notAfter" dates must use UTC (RFC 5280). |
---|
1152 | n/a | |
---|
1153 | n/a | Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec |
---|
1154 | n/a | UTC should be specified as GMT (see ASN1_TIME_print()) |
---|
1155 | n/a | """ |
---|
1156 | n/a | from time import strptime |
---|
1157 | n/a | from calendar import timegm |
---|
1158 | n/a | |
---|
1159 | n/a | months = ( |
---|
1160 | n/a | "Jan","Feb","Mar","Apr","May","Jun", |
---|
1161 | n/a | "Jul","Aug","Sep","Oct","Nov","Dec" |
---|
1162 | n/a | ) |
---|
1163 | n/a | time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT |
---|
1164 | n/a | try: |
---|
1165 | n/a | month_number = months.index(cert_time[:3].title()) + 1 |
---|
1166 | n/a | except ValueError: |
---|
1167 | n/a | raise ValueError('time data %r does not match ' |
---|
1168 | n/a | 'format "%%b%s"' % (cert_time, time_format)) |
---|
1169 | n/a | else: |
---|
1170 | n/a | # found valid month |
---|
1171 | n/a | tt = strptime(cert_time[3:], time_format) |
---|
1172 | n/a | # return an integer, the previous mktime()-based implementation |
---|
1173 | n/a | # returned a float (fractional seconds are always zero here). |
---|
1174 | n/a | return timegm((tt[0], month_number) + tt[2:6]) |
---|
1175 | n/a | |
---|
1176 | n/a | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
---|
1177 | n/a | PEM_FOOTER = "-----END CERTIFICATE-----" |
---|
1178 | n/a | |
---|
1179 | n/a | def DER_cert_to_PEM_cert(der_cert_bytes): |
---|
1180 | n/a | """Takes a certificate in binary DER format and returns the |
---|
1181 | n/a | PEM version of it as a string.""" |
---|
1182 | n/a | |
---|
1183 | n/a | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
---|
1184 | n/a | return (PEM_HEADER + '\n' + |
---|
1185 | n/a | textwrap.fill(f, 64) + '\n' + |
---|
1186 | n/a | PEM_FOOTER + '\n') |
---|
1187 | n/a | |
---|
1188 | n/a | def PEM_cert_to_DER_cert(pem_cert_string): |
---|
1189 | n/a | """Takes a certificate in ASCII PEM format and returns the |
---|
1190 | n/a | DER-encoded version of it as a byte sequence""" |
---|
1191 | n/a | |
---|
1192 | n/a | if not pem_cert_string.startswith(PEM_HEADER): |
---|
1193 | n/a | raise ValueError("Invalid PEM encoding; must start with %s" |
---|
1194 | n/a | % PEM_HEADER) |
---|
1195 | n/a | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
---|
1196 | n/a | raise ValueError("Invalid PEM encoding; must end with %s" |
---|
1197 | n/a | % PEM_FOOTER) |
---|
1198 | n/a | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
---|
1199 | n/a | return base64.decodebytes(d.encode('ASCII', 'strict')) |
---|
1200 | n/a | |
---|
1201 | n/a | def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None): |
---|
1202 | n/a | """Retrieve the certificate from the server at the specified address, |
---|
1203 | n/a | and return it as a PEM-encoded string. |
---|
1204 | n/a | If 'ca_certs' is specified, validate the server cert against it. |
---|
1205 | n/a | If 'ssl_version' is specified, use it in the connection attempt.""" |
---|
1206 | n/a | |
---|
1207 | n/a | host, port = addr |
---|
1208 | n/a | if ca_certs is not None: |
---|
1209 | n/a | cert_reqs = CERT_REQUIRED |
---|
1210 | n/a | else: |
---|
1211 | n/a | cert_reqs = CERT_NONE |
---|
1212 | n/a | context = _create_stdlib_context(ssl_version, |
---|
1213 | n/a | cert_reqs=cert_reqs, |
---|
1214 | n/a | cafile=ca_certs) |
---|
1215 | n/a | with create_connection(addr) as sock: |
---|
1216 | n/a | with context.wrap_socket(sock) as sslsock: |
---|
1217 | n/a | dercert = sslsock.getpeercert(True) |
---|
1218 | n/a | return DER_cert_to_PEM_cert(dercert) |
---|
1219 | n/a | |
---|
1220 | n/a | def get_protocol_name(protocol_code): |
---|
1221 | n/a | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |
---|