blob: 9c91096d1d267575c467b05ef01187b5bde0f86b [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
15
16 cert_time_to_seconds -- convert time string used for certificate
17 notBefore and notAfter functions to integer
18 seconds past the Epoch (the time values
19 returned from time.time())
20
21 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22 by the server running on HOST at port PORT. No
23 validation of the certificate is performed.
24
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
54PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010055PROTOCOL_TLSv1_1
56PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010057
58The following constants identify various SSL alert message descriptions as per
59http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
60
61ALERT_DESCRIPTION_CLOSE_NOTIFY
62ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
63ALERT_DESCRIPTION_BAD_RECORD_MAC
64ALERT_DESCRIPTION_RECORD_OVERFLOW
65ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
66ALERT_DESCRIPTION_HANDSHAKE_FAILURE
67ALERT_DESCRIPTION_BAD_CERTIFICATE
68ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
69ALERT_DESCRIPTION_CERTIFICATE_REVOKED
70ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
71ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
72ALERT_DESCRIPTION_ILLEGAL_PARAMETER
73ALERT_DESCRIPTION_UNKNOWN_CA
74ALERT_DESCRIPTION_ACCESS_DENIED
75ALERT_DESCRIPTION_DECODE_ERROR
76ALERT_DESCRIPTION_DECRYPT_ERROR
77ALERT_DESCRIPTION_PROTOCOL_VERSION
78ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
79ALERT_DESCRIPTION_INTERNAL_ERROR
80ALERT_DESCRIPTION_USER_CANCELLED
81ALERT_DESCRIPTION_NO_RENEGOTIATION
82ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
83ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
84ALERT_DESCRIPTION_UNRECOGNIZED_NAME
85ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
86ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
87ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000088"""
89
Christian Heimes05e8be12008-02-23 18:30:17 +000090import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000091import re
Christian Heimes46bebee2013-06-09 19:03:31 +020092import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020093import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010094from collections import namedtuple
Antoine Pitrou172f0252014-04-18 20:33:08 +020095from enum import Enum as _Enum, IntEnum as _IntEnum
Thomas Woutersed03b412007-08-28 21:37:11 +000096
97import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098
Antoine Pitrou04f6a322010-04-05 21:40:07 +000099from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou41032a62011-10-27 23:56:55 +0200100from _ssl import _SSLContext
101from _ssl import (
102 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
103 SSLSyscallError, SSLEOFError,
104 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000105from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Christian Heimes22587792013-11-21 23:56:13 +0100106from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
107 VERIFY_X509_STRICT)
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinner99c8b162011-05-24 12:05:19 +0200109from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100110
111def _import_symbols(prefix):
112 for n in dir(_ssl):
113 if n.startswith(prefix):
114 globals()[n] = getattr(_ssl, n)
115
116_import_symbols('OP_')
117_import_symbols('ALERT_DESCRIPTION_')
118_import_symbols('SSL_ERROR_')
119
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100120from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100121
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200122from _ssl import _OPENSSL_API_VERSION
123
Antoine Pitrou172f0252014-04-18 20:33:08 +0200124_SSLMethod = _IntEnum('_SSLMethod',
125 {name: value for name, value in vars(_ssl).items()
126 if name.startswith('PROTOCOL_')})
127globals().update(_SSLMethod.__members__)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100128
Antoine Pitrou172f0252014-04-18 20:33:08 +0200129_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
130
Victor Stinner3de49192011-05-09 00:42:58 +0200131try:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100132 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Antoine Pitrou172f0252014-04-18 20:33:08 +0200133except NameError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100134 _SSLv2_IF_EXISTS = None
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135
Christian Heimes46bebee2013-06-09 19:03:31 +0200136if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100137 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200138
Antoine Pitrou15399c32011-04-28 19:23:55 +0200139from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100140from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000141import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000142import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000143
Andrew Svetlov0832af62012-12-18 23:10:48 +0200144
145socket_error = OSError # keep that public name in module namespace
146
Antoine Pitroud6494802011-07-21 01:11:30 +0200147if _ssl.HAS_TLS_UNIQUE:
148 CHANNEL_BINDING_TYPES = ['tls-unique']
149else:
150 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000151
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100152# Disable weak or insecure ciphers by default
153# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400154# Enable a better set of ciphers by default
155# This list has been explicitly chosen to:
156# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
157# * Prefer ECDHE over DHE for better performance
158# * Prefer any AES-GCM over any AES-CBC for better performance and security
159# * Then Use HIGH cipher suites as a fallback
160# * Then Use 3DES as fallback which is secure but slow
161# * Finally use RC4 as a fallback which is problematic but needed for
162# compatibility some times.
163# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
164# reasons
165_DEFAULT_CIPHERS = (
166 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
167 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
168 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
169)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100170
Donald Stufft6a2ba942014-03-23 19:05:28 -0400171# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400172# This list has been explicitly chosen to:
173# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
174# * Prefer ECDHE over DHE for better performance
175# * Prefer any AES-GCM over any AES-CBC for better performance and security
176# * Then Use HIGH cipher suites as a fallback
177# * Then Use 3DES as fallback which is secure but slow
178# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
179# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400180_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400181 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
182 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
183 '!eNULL:!MD5:!DSS:!RC4'
184)
Christian Heimes4c05b472013-11-23 15:58:30 +0100185
Thomas Woutersed03b412007-08-28 21:37:11 +0000186
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000187class CertificateError(ValueError):
188 pass
189
190
Georg Brandl72c98d32013-10-27 07:16:53 +0100191def _dnsname_match(dn, hostname, max_wildcards=1):
192 """Matching according to RFC 6125, section 6.4.3
193
194 http://tools.ietf.org/html/rfc6125#section-6.4.3
195 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000196 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100197 if not dn:
198 return False
199
200 leftmost, *remainder = dn.split(r'.')
201
202 wildcards = leftmost.count('*')
203 if wildcards > max_wildcards:
204 # Issue #17980: avoid denials of service by refusing more
205 # than one wildcard per fragment. A survery of established
206 # policy among SSL implementations showed it to be a
207 # reasonable choice.
208 raise CertificateError(
209 "too many wildcards in certificate DNS name: " + repr(dn))
210
211 # speed up common case w/o wildcards
212 if not wildcards:
213 return dn.lower() == hostname.lower()
214
215 # RFC 6125, section 6.4.3, subitem 1.
216 # The client SHOULD NOT attempt to match a presented identifier in which
217 # the wildcard character comprises a label other than the left-most label.
218 if leftmost == '*':
219 # When '*' is a fragment by itself, it matches a non-empty dotless
220 # fragment.
221 pats.append('[^.]+')
222 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
223 # RFC 6125, section 6.4.3, subitem 3.
224 # The client SHOULD NOT attempt to match a presented identifier
225 # where the wildcard character is embedded within an A-label or
226 # U-label of an internationalized domain name.
227 pats.append(re.escape(leftmost))
228 else:
229 # Otherwise, '*' matches any dotless string, e.g. www*
230 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
231
232 # add the remaining fragments, ignore any wildcards
233 for frag in remainder:
234 pats.append(re.escape(frag))
235
236 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
237 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000238
239
240def match_hostname(cert, hostname):
241 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100242 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
243 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000244
245 CertificateError is raised on failure. On success, the function
246 returns nothing.
247 """
248 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100249 raise ValueError("empty or no certificate, match_hostname needs a "
250 "SSL socket or SSL context with either "
251 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000252 dnsnames = []
253 san = cert.get('subjectAltName', ())
254 for key, value in san:
255 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100256 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000257 return
258 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200259 if not dnsnames:
260 # The subject is only checked when there is no dNSName entry
261 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000262 for sub in cert.get('subject', ()):
263 for key, value in sub:
264 # XXX according to RFC 2818, the most specific Common Name
265 # must be used.
266 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100267 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000268 return
269 dnsnames.append(value)
270 if len(dnsnames) > 1:
271 raise CertificateError("hostname %r "
272 "doesn't match either of %s"
273 % (hostname, ', '.join(map(repr, dnsnames))))
274 elif len(dnsnames) == 1:
275 raise CertificateError("hostname %r "
276 "doesn't match %r"
277 % (hostname, dnsnames[0]))
278 else:
279 raise CertificateError("no appropriate commonName or "
280 "subjectAltName fields were found")
281
282
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100283DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200284 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
285 "openssl_capath")
286
287def get_default_verify_paths():
288 """Return paths to default cafile and capath.
289 """
290 parts = _ssl.get_default_verify_paths()
291
292 # environment vars shadow paths
293 cafile = os.environ.get(parts[0], parts[1])
294 capath = os.environ.get(parts[2], parts[3])
295
296 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
297 capath if os.path.isdir(capath) else None,
298 *parts)
299
300
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100301class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
302 """ASN.1 object identifier lookup
303 """
304 __slots__ = ()
305
306 def __new__(cls, oid):
307 return super().__new__(cls, *_txt2obj(oid, name=False))
308
309 @classmethod
310 def fromnid(cls, nid):
311 """Create _ASN1Object from OpenSSL numeric ID
312 """
313 return super().__new__(cls, *_nid2obj(nid))
314
315 @classmethod
316 def fromname(cls, name):
317 """Create _ASN1Object from short name, long name or OID
318 """
319 return super().__new__(cls, *_txt2obj(name, name=True))
320
321
Christian Heimes72d28502013-11-23 13:56:58 +0100322class Purpose(_ASN1Object, _Enum):
323 """SSLContext purpose flags with X509v3 Extended Key Usage objects
324 """
325 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
326 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
327
328
Antoine Pitrou152efa22010-05-16 18:19:27 +0000329class SSLContext(_SSLContext):
330 """An SSLContext holds various SSL-related configuration options and
331 data, such as certificates and possibly a private key."""
332
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100333 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100334 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000335
336 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100337 self = _SSLContext.__new__(cls, protocol)
338 if protocol != _SSLv2_IF_EXISTS:
339 self.set_ciphers(_DEFAULT_CIPHERS)
340 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000341
342 def __init__(self, protocol):
343 self.protocol = protocol
344
345 def wrap_socket(self, sock, server_side=False,
346 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000347 suppress_ragged_eofs=True,
348 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000349 return SSLSocket(sock=sock, server_side=server_side,
350 do_handshake_on_connect=do_handshake_on_connect,
351 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000352 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000353 _context=self)
354
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100355 def set_npn_protocols(self, npn_protocols):
356 protos = bytearray()
357 for protocol in npn_protocols:
358 b = bytes(protocol, 'ascii')
359 if len(b) == 0 or len(b) > 255:
360 raise SSLError('NPN protocols must be 1 to 255 in length')
361 protos.append(len(b))
362 protos.extend(b)
363
364 self._set_npn_protocols(protos)
365
Christian Heimes72d28502013-11-23 13:56:58 +0100366 def _load_windows_store_certs(self, storename, purpose):
367 certs = bytearray()
368 for cert, encoding, trust in enum_certificates(storename):
369 # CA certs are never PKCS#7 encoded
370 if encoding == "x509_asn":
371 if trust is True or purpose.oid in trust:
372 certs.extend(cert)
373 self.load_verify_locations(cadata=certs)
374 return certs
375
376 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
377 if not isinstance(purpose, _ASN1Object):
378 raise TypeError(purpose)
379 if sys.platform == "win32":
380 for storename in self._windows_cert_stores:
381 self._load_windows_store_certs(storename, purpose)
382 else:
383 self.set_default_verify_paths()
384
Antoine Pitrou152efa22010-05-16 18:19:27 +0000385
Christian Heimes4c05b472013-11-23 15:58:30 +0100386def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
387 capath=None, cadata=None):
388 """Create a SSLContext object with default settings.
389
390 NOTE: The protocol and settings may change anytime without prior
391 deprecation. The values represent a fair balance between maximum
392 compatibility and security.
393 """
394 if not isinstance(purpose, _ASN1Object):
395 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400396
397 context = SSLContext(PROTOCOL_SSLv23)
398
Christian Heimes4c05b472013-11-23 15:58:30 +0100399 # SSLv2 considered harmful.
400 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400401
402 # SSLv3 has problematic security and is only required for really old
403 # clients such as IE6 on Windows XP
404 context.options |= OP_NO_SSLv3
405
Christian Heimesdec813f2013-11-28 08:06:54 +0100406 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
407 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400408
Christian Heimes4c05b472013-11-23 15:58:30 +0100409 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400410 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100411 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100412 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400413 elif purpose == Purpose.CLIENT_AUTH:
414 # Prefer the server's ciphers by default so that we get stronger
415 # encryption
416 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
417
418 # Use single use keys in order to improve forward secrecy
419 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
420 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
421
422 # disallow ciphers with known vulnerabilities
423 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
424
Christian Heimes4c05b472013-11-23 15:58:30 +0100425 if cafile or capath or cadata:
426 context.load_verify_locations(cafile, capath, cadata)
427 elif context.verify_mode != CERT_NONE:
428 # no explicit cafile, capath or cadata but the verify mode is
429 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
430 # root CA certificates for the given purpose. This may fail silently.
431 context.load_default_certs(purpose)
432 return context
433
434
Christian Heimes67986f92013-11-23 22:43:47 +0100435def _create_stdlib_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100436 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100437 certfile=None, keyfile=None,
438 cafile=None, capath=None, cadata=None):
439 """Create a SSLContext object for Python stdlib modules
440
441 All Python stdlib modules shall use this function to create SSLContext
442 objects in order to keep common settings in one place. The configuration
443 is less restrict than create_default_context()'s to increase backward
444 compatibility.
445 """
446 if not isinstance(purpose, _ASN1Object):
447 raise TypeError(purpose)
448
449 context = SSLContext(protocol)
450 # SSLv2 considered harmful.
451 context.options |= OP_NO_SSLv2
452
453 if cert_reqs is not None:
454 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100455 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100456
457 if keyfile and not certfile:
458 raise ValueError("certfile must be specified")
459 if certfile or keyfile:
460 context.load_cert_chain(certfile, keyfile)
461
462 # load CA root certs
463 if cafile or capath or cadata:
464 context.load_verify_locations(cafile, capath, cadata)
465 elif context.verify_mode != CERT_NONE:
466 # no explicit cafile, capath or cadata but the verify mode is
467 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
468 # root CA certificates for the given purpose. This may fail silently.
469 context.load_default_certs(purpose)
470
471 return context
472
Antoine Pitrou152efa22010-05-16 18:19:27 +0000473class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000474 """This class implements a subtype of socket.socket that wraps
475 the underlying OS socket in an SSL context when necessary, and
476 provides read and write methods over that channel."""
477
Bill Janssen6e027db2007-11-15 22:23:56 +0000478 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000479 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000480 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
481 do_handshake_on_connect=True,
482 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100483 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000484 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000485 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000486
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100488 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000490 if server_side and not certfile:
491 raise ValueError("certfile must be specified for server-side "
492 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000493 if keyfile and not certfile:
494 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495 if certfile and not keyfile:
496 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 self._context = SSLContext(ssl_version)
498 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000499 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100500 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100502 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100503 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100504 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100506 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000507 self.keyfile = keyfile
508 self.certfile = certfile
509 self.cert_reqs = cert_reqs
510 self.ssl_version = ssl_version
511 self.ca_certs = ca_certs
512 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100513 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
514 # mixed in.
515 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
516 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000517 if server_side and server_hostname:
518 raise ValueError("server_hostname can only be specified "
519 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100520 if self._context.check_hostname and not server_hostname:
521 if HAS_SNI:
522 raise ValueError("check_hostname requires server_hostname")
523 else:
524 raise ValueError("check_hostname requires server_hostname, "
525 "but it's not supported by your OpenSSL "
526 "library")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000527 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000528 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000529 self.do_handshake_on_connect = do_handshake_on_connect
530 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000531 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000532 socket.__init__(self,
533 family=sock.family,
534 type=sock.type,
535 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000536 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000537 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000538 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000539 elif fileno is not None:
540 socket.__init__(self, fileno=fileno)
541 else:
542 socket.__init__(self, family=family, type=type, proto=proto)
543
Antoine Pitrou242db722013-05-01 20:52:07 +0200544 # See if we are connected
545 try:
546 self.getpeername()
547 except OSError as e:
548 if e.errno != errno.ENOTCONN:
549 raise
550 connected = False
551 else:
552 connected = True
553
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000554 self._closed = False
555 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000556 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000557 if connected:
558 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000559 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100560 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000561 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000562 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000563 timeout = self.gettimeout()
564 if timeout == 0.0:
565 # non-blocking
566 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000567 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000568
Christian Heimes1aa9a752013-12-02 02:41:19 +0100569 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000570 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100571 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200572
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100573 @property
574 def context(self):
575 return self._context
576
577 @context.setter
578 def context(self, ctx):
579 self._context = ctx
580 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000581
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000582 def dup(self):
583 raise NotImplemented("Can't dup() %s instances" %
584 self.__class__.__name__)
585
Bill Janssen6e027db2007-11-15 22:23:56 +0000586 def _checkClosed(self, msg=None):
587 # raise an exception here if you wish to check for spurious closes
588 pass
589
Antoine Pitrou242db722013-05-01 20:52:07 +0200590 def _check_connected(self):
591 if not self._connected:
592 # getpeername() will raise ENOTCONN if the socket is really
593 # not connected; note that we can be connected even without
594 # _connected being set, e.g. if connect() first returned
595 # EAGAIN.
596 self.getpeername()
597
Bill Janssen54cc54c2007-12-14 22:08:56 +0000598 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000599 """Read up to LEN bytes and return them.
600 Return zero-length string on EOF."""
601
Bill Janssen6e027db2007-11-15 22:23:56 +0000602 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200603 if not self._sslobj:
604 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000605 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000606 if buffer is not None:
607 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000608 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000609 v = self._sslobj.read(len or 1024)
610 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000611 except SSLError as x:
612 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000613 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000614 return 0
615 else:
616 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000617 else:
618 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000619
620 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000621 """Write DATA to the underlying SSL channel. Returns
622 number of bytes of DATA actually transmitted."""
623
Bill Janssen6e027db2007-11-15 22:23:56 +0000624 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200625 if not self._sslobj:
626 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000627 return self._sslobj.write(data)
628
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000630 """Returns a formatted version of the data in the
631 certificate provided by the other end of the SSL channel.
632 Return None if no certificate was provided, {} if a
633 certificate was provided, but not validated."""
634
Bill Janssen6e027db2007-11-15 22:23:56 +0000635 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200636 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637 return self._sslobj.peer_certificate(binary_form)
638
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100639 def selected_npn_protocol(self):
640 self._checkClosed()
641 if not self._sslobj or not _ssl.HAS_NPN:
642 return None
643 else:
644 return self._sslobj.selected_npn_protocol()
645
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000646 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000647 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648 if not self._sslobj:
649 return None
650 else:
651 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000652
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100653 def compression(self):
654 self._checkClosed()
655 if not self._sslobj:
656 return None
657 else:
658 return self._sslobj.compression()
659
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000660 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000661 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000662 if self._sslobj:
663 if flags != 0:
664 raise ValueError(
665 "non-zero flags not allowed in calls to send() on %s" %
666 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200667 try:
668 v = self._sslobj.write(data)
669 except SSLError as x:
670 if x.args[0] == SSL_ERROR_WANT_READ:
671 return 0
672 elif x.args[0] == SSL_ERROR_WANT_WRITE:
673 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000674 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200675 raise
676 else:
677 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000678 else:
679 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000680
Antoine Pitroua468adc2010-09-14 14:43:44 +0000681 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000682 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000683 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000684 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000685 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000686 elif addr is None:
687 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000688 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000689 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000690
Nick Coghlan513886a2011-08-28 00:00:27 +1000691 def sendmsg(self, *args, **kwargs):
692 # Ensure programs don't send data unencrypted if they try to
693 # use this method.
694 raise NotImplementedError("sendmsg not allowed on instances of %s" %
695 self.__class__)
696
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000697 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000698 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000699 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000700 if flags != 0:
701 raise ValueError(
702 "non-zero flags not allowed in calls to sendall() on %s" %
703 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000704 amount = len(data)
705 count = 0
706 while (count < amount):
707 v = self.send(data[count:])
708 count += v
709 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000710 else:
711 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000712
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000713 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000714 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000715 if self._sslobj:
716 if flags != 0:
717 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000718 "non-zero flags not allowed in calls to recv() on %s" %
719 self.__class__)
720 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000721 else:
722 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000723
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000724 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000725 self._checkClosed()
726 if buffer and (nbytes is None):
727 nbytes = len(buffer)
728 elif nbytes is None:
729 nbytes = 1024
730 if self._sslobj:
731 if flags != 0:
732 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000733 "non-zero flags not allowed in calls to recv_into() on %s" %
734 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000735 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000736 else:
737 return socket.recv_into(self, buffer, nbytes, flags)
738
Antoine Pitroua468adc2010-09-14 14:43:44 +0000739 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000740 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000741 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000742 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000743 self.__class__)
744 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000745 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000746
Bill Janssen58afe4c2008-09-08 16:45:19 +0000747 def recvfrom_into(self, buffer, nbytes=None, flags=0):
748 self._checkClosed()
749 if self._sslobj:
750 raise ValueError("recvfrom_into not allowed on instances of %s" %
751 self.__class__)
752 else:
753 return socket.recvfrom_into(self, buffer, nbytes, flags)
754
Nick Coghlan513886a2011-08-28 00:00:27 +1000755 def recvmsg(self, *args, **kwargs):
756 raise NotImplementedError("recvmsg not allowed on instances of %s" %
757 self.__class__)
758
759 def recvmsg_into(self, *args, **kwargs):
760 raise NotImplementedError("recvmsg_into not allowed on instances of "
761 "%s" % self.__class__)
762
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000763 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000764 self._checkClosed()
765 if self._sslobj:
766 return self._sslobj.pending()
767 else:
768 return 0
769
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000770 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000771 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000772 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000773 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000774
Ezio Melottidc55e672010-01-18 09:15:14 +0000775 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000776 if self._sslobj:
777 s = self._sslobj.shutdown()
778 self._sslobj = None
779 return s
780 else:
781 raise ValueError("No SSL wrapper around " + str(self))
782
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000783 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000785 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000786
Bill Janssen48dc27c2007-12-05 03:38:10 +0000787 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000788 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200789 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000790 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000791 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000792 if timeout == 0.0 and block:
793 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000794 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000795 finally:
796 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000797
Christian Heimes1aa9a752013-12-02 02:41:19 +0100798 if self.context.check_hostname:
Christian Heimes1da3ba82013-12-04 20:46:20 +0100799 if not self.server_hostname:
800 raise ValueError("check_hostname needs server_hostname "
801 "argument")
802 match_hostname(self.getpeercert(), self.server_hostname)
Christian Heimes1aa9a752013-12-02 02:41:19 +0100803
Antoine Pitroub4410db2011-05-18 18:51:06 +0200804 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000805 if self.server_side:
806 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000807 # Here we assume that the socket is client-side, and not
808 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000809 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000811 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000812 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200813 if connect_ex:
814 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000815 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200816 rc = None
817 socket.connect(self, addr)
818 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200819 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200820 if self.do_handshake_on_connect:
821 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200822 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +0100823 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +0200824 self._sslobj = None
825 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000826
827 def connect(self, addr):
828 """Connects to remote ADDR, and then wraps the connection in
829 an SSL channel."""
830 self._real_connect(addr, False)
831
832 def connect_ex(self, addr):
833 """Connects to remote ADDR, and then wraps the connection in
834 an SSL channel."""
835 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000836
837 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000838 """Accepts a new connection from a remote client, and returns
839 a tuple containing that new connection wrapped with a server-side
840 SSL channel, and the address of the remote client."""
841
842 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100843 newsock = self.context.wrap_socket(newsock,
844 do_handshake_on_connect=self.do_handshake_on_connect,
845 suppress_ragged_eofs=self.suppress_ragged_eofs,
846 server_side=True)
847 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitroud6494802011-07-21 01:11:30 +0200849 def get_channel_binding(self, cb_type="tls-unique"):
850 """Get channel binding data for current connection. Raise ValueError
851 if the requested `cb_type` is not supported. Return bytes of the data
852 or None if the data is not available (e.g. before the handshake).
853 """
854 if cb_type not in CHANNEL_BINDING_TYPES:
855 raise ValueError("Unsupported channel binding type")
856 if cb_type != "tls-unique":
857 raise NotImplementedError(
858 "{0} channel binding type not implemented"
859 .format(cb_type))
860 if self._sslobj is None:
861 return None
862 return self._sslobj.tls_unique_cb()
863
Bill Janssen54cc54c2007-12-14 22:08:56 +0000864
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865def wrap_socket(sock, keyfile=None, certfile=None,
866 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000867 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000868 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100869 suppress_ragged_eofs=True,
870 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Bill Janssen6e027db2007-11-15 22:23:56 +0000872 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000874 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000875 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000876 suppress_ragged_eofs=suppress_ragged_eofs,
877 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Thomas Woutersed03b412007-08-28 21:37:11 +0000879# some utility functions
880
881def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +0200882 """Return the time in seconds since the Epoch, given the timestring
883 representing the "notBefore" or "notAfter" date from a certificate
884 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000885
Antoine Pitrouc695c952014-04-28 20:57:36 +0200886 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
887
888 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
889 UTC should be specified as GMT (see ASN1_TIME_print())
890 """
891 from time import strptime
892 from calendar import timegm
893
894 months = (
895 "Jan","Feb","Mar","Apr","May","Jun",
896 "Jul","Aug","Sep","Oct","Nov","Dec"
897 )
898 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
899 try:
900 month_number = months.index(cert_time[:3].title()) + 1
901 except ValueError:
902 raise ValueError('time data %r does not match '
903 'format "%%b%s"' % (cert_time, time_format))
904 else:
905 # found valid month
906 tt = strptime(cert_time[3:], time_format)
907 # return an integer, the previous mktime()-based implementation
908 # returned a float (fractional seconds are always zero here).
909 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +0000910
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911PEM_HEADER = "-----BEGIN CERTIFICATE-----"
912PEM_FOOTER = "-----END CERTIFICATE-----"
913
914def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915 """Takes a certificate in binary DER format and returns the
916 PEM version of it as a string."""
917
Bill Janssen6e027db2007-11-15 22:23:56 +0000918 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
919 return (PEM_HEADER + '\n' +
920 textwrap.fill(f, 64) + '\n' +
921 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
923def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 """Takes a certificate in ASCII PEM format and returns the
925 DER-encoded version of it as a byte sequence"""
926
927 if not pem_cert_string.startswith(PEM_HEADER):
928 raise ValueError("Invalid PEM encoding; must start with %s"
929 % PEM_HEADER)
930 if not pem_cert_string.strip().endswith(PEM_FOOTER):
931 raise ValueError("Invalid PEM encoding; must end with %s"
932 % PEM_FOOTER)
933 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000934 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitrou94a5b662014-04-16 18:56:28 +0200936def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937 """Retrieve the certificate from the server at the specified address,
938 and return it as a PEM-encoded string.
939 If 'ca_certs' is specified, validate the server cert against it.
940 If 'ssl_version' is specified, use it in the connection attempt."""
941
942 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +0100943 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944 cert_reqs = CERT_REQUIRED
945 else:
946 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +0100947 context = _create_stdlib_context(ssl_version,
948 cert_reqs=cert_reqs,
949 cafile=ca_certs)
950 with create_connection(addr) as sock:
951 with context.wrap_socket(sock) as sslsock:
952 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953 return DER_cert_to_PEM_cert(dercert)
954
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000955def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200956 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')