blob: 880a3d4af6795cc6ffaf07d5d7864c7d58ca467d [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
Christian Heimes72d28502013-11-23 13:56:58 +010095from enum import Enum as _Enum
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 Pitrou2463e5f2013-03-28 22:24:43 +0100122from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200123from _ssl import _OPENSSL_API_VERSION
124
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100125
Victor Stinner3de49192011-05-09 00:42:58 +0200126_PROTOCOL_NAMES = {
127 PROTOCOL_TLSv1: "TLSv1",
128 PROTOCOL_SSLv23: "SSLv23",
129 PROTOCOL_SSLv3: "SSLv3",
130}
131try:
132 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100133 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400134except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100135 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200136else:
137 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000138
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100139try:
140 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400141except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142 pass
143else:
144 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
145 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
146
Christian Heimes46bebee2013-06-09 19:03:31 +0200147if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100148 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200149
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000150from socket import getnameinfo as _getnameinfo
Antoine Pitrou15399c32011-04-28 19:23:55 +0200151from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000152import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000153import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000154import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000155
Andrew Svetlov0832af62012-12-18 23:10:48 +0200156
157socket_error = OSError # keep that public name in module namespace
158
Antoine Pitroud6494802011-07-21 01:11:30 +0200159if _ssl.HAS_TLS_UNIQUE:
160 CHANNEL_BINDING_TYPES = ['tls-unique']
161else:
162 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000163
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100164# Disable weak or insecure ciphers by default
165# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
166_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
167
Christian Heimes4c05b472013-11-23 15:58:30 +0100168# restricted and more secure ciphers
169# HIGH: high encryption cipher suites with key length >= 128 bits (no MD5)
170# !aNULL: only authenticated cipher suites (no anonymous DH)
171# !RC4: no RC4 streaming cipher, RC4 is broken
172# !DSS: RSA is preferred over DSA
173_RESTRICTED_CIPHERS = 'HIGH:!aNULL:!RC4:!DSS'
174
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000176class CertificateError(ValueError):
177 pass
178
179
Georg Brandl72c98d32013-10-27 07:16:53 +0100180def _dnsname_match(dn, hostname, max_wildcards=1):
181 """Matching according to RFC 6125, section 6.4.3
182
183 http://tools.ietf.org/html/rfc6125#section-6.4.3
184 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000185 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100186 if not dn:
187 return False
188
189 leftmost, *remainder = dn.split(r'.')
190
191 wildcards = leftmost.count('*')
192 if wildcards > max_wildcards:
193 # Issue #17980: avoid denials of service by refusing more
194 # than one wildcard per fragment. A survery of established
195 # policy among SSL implementations showed it to be a
196 # reasonable choice.
197 raise CertificateError(
198 "too many wildcards in certificate DNS name: " + repr(dn))
199
200 # speed up common case w/o wildcards
201 if not wildcards:
202 return dn.lower() == hostname.lower()
203
204 # RFC 6125, section 6.4.3, subitem 1.
205 # The client SHOULD NOT attempt to match a presented identifier in which
206 # the wildcard character comprises a label other than the left-most label.
207 if leftmost == '*':
208 # When '*' is a fragment by itself, it matches a non-empty dotless
209 # fragment.
210 pats.append('[^.]+')
211 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
212 # RFC 6125, section 6.4.3, subitem 3.
213 # The client SHOULD NOT attempt to match a presented identifier
214 # where the wildcard character is embedded within an A-label or
215 # U-label of an internationalized domain name.
216 pats.append(re.escape(leftmost))
217 else:
218 # Otherwise, '*' matches any dotless string, e.g. www*
219 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
220
221 # add the remaining fragments, ignore any wildcards
222 for frag in remainder:
223 pats.append(re.escape(frag))
224
225 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
226 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000227
228
229def match_hostname(cert, hostname):
230 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100231 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
232 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000233
234 CertificateError is raised on failure. On success, the function
235 returns nothing.
236 """
237 if not cert:
238 raise ValueError("empty or no certificate")
239 dnsnames = []
240 san = cert.get('subjectAltName', ())
241 for key, value in san:
242 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100243 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000244 return
245 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200246 if not dnsnames:
247 # The subject is only checked when there is no dNSName entry
248 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000249 for sub in cert.get('subject', ()):
250 for key, value in sub:
251 # XXX according to RFC 2818, the most specific Common Name
252 # must be used.
253 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100254 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000255 return
256 dnsnames.append(value)
257 if len(dnsnames) > 1:
258 raise CertificateError("hostname %r "
259 "doesn't match either of %s"
260 % (hostname, ', '.join(map(repr, dnsnames))))
261 elif len(dnsnames) == 1:
262 raise CertificateError("hostname %r "
263 "doesn't match %r"
264 % (hostname, dnsnames[0]))
265 else:
266 raise CertificateError("no appropriate commonName or "
267 "subjectAltName fields were found")
268
269
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100270DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200271 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
272 "openssl_capath")
273
274def get_default_verify_paths():
275 """Return paths to default cafile and capath.
276 """
277 parts = _ssl.get_default_verify_paths()
278
279 # environment vars shadow paths
280 cafile = os.environ.get(parts[0], parts[1])
281 capath = os.environ.get(parts[2], parts[3])
282
283 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
284 capath if os.path.isdir(capath) else None,
285 *parts)
286
287
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100288class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
289 """ASN.1 object identifier lookup
290 """
291 __slots__ = ()
292
293 def __new__(cls, oid):
294 return super().__new__(cls, *_txt2obj(oid, name=False))
295
296 @classmethod
297 def fromnid(cls, nid):
298 """Create _ASN1Object from OpenSSL numeric ID
299 """
300 return super().__new__(cls, *_nid2obj(nid))
301
302 @classmethod
303 def fromname(cls, name):
304 """Create _ASN1Object from short name, long name or OID
305 """
306 return super().__new__(cls, *_txt2obj(name, name=True))
307
308
Christian Heimes72d28502013-11-23 13:56:58 +0100309class Purpose(_ASN1Object, _Enum):
310 """SSLContext purpose flags with X509v3 Extended Key Usage objects
311 """
312 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
313 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
314
315
Antoine Pitrou152efa22010-05-16 18:19:27 +0000316class SSLContext(_SSLContext):
317 """An SSLContext holds various SSL-related configuration options and
318 data, such as certificates and possibly a private key."""
319
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100320 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100321 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000322
323 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100324 self = _SSLContext.__new__(cls, protocol)
325 if protocol != _SSLv2_IF_EXISTS:
326 self.set_ciphers(_DEFAULT_CIPHERS)
327 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000328
329 def __init__(self, protocol):
330 self.protocol = protocol
331
332 def wrap_socket(self, sock, server_side=False,
333 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000334 suppress_ragged_eofs=True,
335 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000336 return SSLSocket(sock=sock, server_side=server_side,
337 do_handshake_on_connect=do_handshake_on_connect,
338 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000339 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340 _context=self)
341
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100342 def set_npn_protocols(self, npn_protocols):
343 protos = bytearray()
344 for protocol in npn_protocols:
345 b = bytes(protocol, 'ascii')
346 if len(b) == 0 or len(b) > 255:
347 raise SSLError('NPN protocols must be 1 to 255 in length')
348 protos.append(len(b))
349 protos.extend(b)
350
351 self._set_npn_protocols(protos)
352
Christian Heimes72d28502013-11-23 13:56:58 +0100353 def _load_windows_store_certs(self, storename, purpose):
354 certs = bytearray()
355 for cert, encoding, trust in enum_certificates(storename):
356 # CA certs are never PKCS#7 encoded
357 if encoding == "x509_asn":
358 if trust is True or purpose.oid in trust:
359 certs.extend(cert)
360 self.load_verify_locations(cadata=certs)
361 return certs
362
363 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
364 if not isinstance(purpose, _ASN1Object):
365 raise TypeError(purpose)
366 if sys.platform == "win32":
367 for storename in self._windows_cert_stores:
368 self._load_windows_store_certs(storename, purpose)
369 else:
370 self.set_default_verify_paths()
371
Antoine Pitrou152efa22010-05-16 18:19:27 +0000372
Christian Heimes4c05b472013-11-23 15:58:30 +0100373def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
374 capath=None, cadata=None):
375 """Create a SSLContext object with default settings.
376
377 NOTE: The protocol and settings may change anytime without prior
378 deprecation. The values represent a fair balance between maximum
379 compatibility and security.
380 """
381 if not isinstance(purpose, _ASN1Object):
382 raise TypeError(purpose)
383 context = SSLContext(PROTOCOL_TLSv1)
384 # SSLv2 considered harmful.
385 context.options |= OP_NO_SSLv2
386 # disallow ciphers with known vulnerabilities
387 context.set_ciphers(_RESTRICTED_CIPHERS)
388 # verify certs in client mode
389 if purpose == Purpose.SERVER_AUTH:
390 context.verify_mode = CERT_REQUIRED
391 if cafile or capath or cadata:
392 context.load_verify_locations(cafile, capath, cadata)
393 elif context.verify_mode != CERT_NONE:
394 # no explicit cafile, capath or cadata but the verify mode is
395 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
396 # root CA certificates for the given purpose. This may fail silently.
397 context.load_default_certs(purpose)
398 return context
399
400
Antoine Pitrou152efa22010-05-16 18:19:27 +0000401class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000402 """This class implements a subtype of socket.socket that wraps
403 the underlying OS socket in an SSL context when necessary, and
404 provides read and write methods over that channel."""
405
Bill Janssen6e027db2007-11-15 22:23:56 +0000406 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000407 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000408 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
409 do_handshake_on_connect=True,
410 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100411 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000412 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000413 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000414
Antoine Pitrou152efa22010-05-16 18:19:27 +0000415 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100416 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000417 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000418 if server_side and not certfile:
419 raise ValueError("certfile must be specified for server-side "
420 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000421 if keyfile and not certfile:
422 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000423 if certfile and not keyfile:
424 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100425 self._context = SSLContext(ssl_version)
426 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100428 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100430 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100431 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100432 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000433 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100434 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000435 self.keyfile = keyfile
436 self.certfile = certfile
437 self.cert_reqs = cert_reqs
438 self.ssl_version = ssl_version
439 self.ca_certs = ca_certs
440 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000441 if server_side and server_hostname:
442 raise ValueError("server_hostname can only be specified "
443 "in client mode")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000444 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000445 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000446 self.do_handshake_on_connect = do_handshake_on_connect
447 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000448 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000449 socket.__init__(self,
450 family=sock.family,
451 type=sock.type,
452 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000453 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000454 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000455 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 elif fileno is not None:
457 socket.__init__(self, fileno=fileno)
458 else:
459 socket.__init__(self, family=family, type=type, proto=proto)
460
Antoine Pitrou242db722013-05-01 20:52:07 +0200461 # See if we are connected
462 try:
463 self.getpeername()
464 except OSError as e:
465 if e.errno != errno.ENOTCONN:
466 raise
467 connected = False
468 else:
469 connected = True
470
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000471 self._closed = False
472 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000473 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000474 if connected:
475 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000476 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100477 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000478 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000479 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000480 timeout = self.gettimeout()
481 if timeout == 0.0:
482 # non-blocking
483 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000484 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000485
Andrew Svetlov0832af62012-12-18 23:10:48 +0200486 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000487 self.close()
488 raise x
Antoine Pitrou242db722013-05-01 20:52:07 +0200489
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100490 @property
491 def context(self):
492 return self._context
493
494 @context.setter
495 def context(self, ctx):
496 self._context = ctx
497 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000498
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000499 def dup(self):
500 raise NotImplemented("Can't dup() %s instances" %
501 self.__class__.__name__)
502
Bill Janssen6e027db2007-11-15 22:23:56 +0000503 def _checkClosed(self, msg=None):
504 # raise an exception here if you wish to check for spurious closes
505 pass
506
Antoine Pitrou242db722013-05-01 20:52:07 +0200507 def _check_connected(self):
508 if not self._connected:
509 # getpeername() will raise ENOTCONN if the socket is really
510 # not connected; note that we can be connected even without
511 # _connected being set, e.g. if connect() first returned
512 # EAGAIN.
513 self.getpeername()
514
Bill Janssen54cc54c2007-12-14 22:08:56 +0000515 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000516 """Read up to LEN bytes and return them.
517 Return zero-length string on EOF."""
518
Bill Janssen6e027db2007-11-15 22:23:56 +0000519 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200520 if not self._sslobj:
521 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000522 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000523 if buffer is not None:
524 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000525 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000526 v = self._sslobj.read(len or 1024)
527 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000528 except SSLError as x:
529 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000530 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000531 return 0
532 else:
533 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000534 else:
535 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000536
537 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000538 """Write DATA to the underlying SSL channel. Returns
539 number of bytes of DATA actually transmitted."""
540
Bill Janssen6e027db2007-11-15 22:23:56 +0000541 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200542 if not self._sslobj:
543 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000544 return self._sslobj.write(data)
545
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000547 """Returns a formatted version of the data in the
548 certificate provided by the other end of the SSL channel.
549 Return None if no certificate was provided, {} if a
550 certificate was provided, but not validated."""
551
Bill Janssen6e027db2007-11-15 22:23:56 +0000552 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200553 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554 return self._sslobj.peer_certificate(binary_form)
555
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100556 def selected_npn_protocol(self):
557 self._checkClosed()
558 if not self._sslobj or not _ssl.HAS_NPN:
559 return None
560 else:
561 return self._sslobj.selected_npn_protocol()
562
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000563 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000564 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565 if not self._sslobj:
566 return None
567 else:
568 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000569
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100570 def compression(self):
571 self._checkClosed()
572 if not self._sslobj:
573 return None
574 else:
575 return self._sslobj.compression()
576
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000577 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000578 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000579 if self._sslobj:
580 if flags != 0:
581 raise ValueError(
582 "non-zero flags not allowed in calls to send() on %s" %
583 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200584 try:
585 v = self._sslobj.write(data)
586 except SSLError as x:
587 if x.args[0] == SSL_ERROR_WANT_READ:
588 return 0
589 elif x.args[0] == SSL_ERROR_WANT_WRITE:
590 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000591 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200592 raise
593 else:
594 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000595 else:
596 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000597
Antoine Pitroua468adc2010-09-14 14:43:44 +0000598 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000599 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000600 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000601 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000602 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000603 elif addr is None:
604 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000605 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000606 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000607
Nick Coghlan513886a2011-08-28 00:00:27 +1000608 def sendmsg(self, *args, **kwargs):
609 # Ensure programs don't send data unencrypted if they try to
610 # use this method.
611 raise NotImplementedError("sendmsg not allowed on instances of %s" %
612 self.__class__)
613
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000614 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000615 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000616 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000617 if flags != 0:
618 raise ValueError(
619 "non-zero flags not allowed in calls to sendall() on %s" %
620 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000621 amount = len(data)
622 count = 0
623 while (count < amount):
624 v = self.send(data[count:])
625 count += v
626 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000627 else:
628 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000629
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000630 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000631 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000632 if self._sslobj:
633 if flags != 0:
634 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000635 "non-zero flags not allowed in calls to recv() on %s" %
636 self.__class__)
637 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000638 else:
639 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000640
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000641 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000642 self._checkClosed()
643 if buffer and (nbytes is None):
644 nbytes = len(buffer)
645 elif nbytes is None:
646 nbytes = 1024
647 if self._sslobj:
648 if flags != 0:
649 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000650 "non-zero flags not allowed in calls to recv_into() on %s" %
651 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000652 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000653 else:
654 return socket.recv_into(self, buffer, nbytes, flags)
655
Antoine Pitroua468adc2010-09-14 14:43:44 +0000656 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000657 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000658 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000659 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000660 self.__class__)
661 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000662 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000663
Bill Janssen58afe4c2008-09-08 16:45:19 +0000664 def recvfrom_into(self, buffer, nbytes=None, flags=0):
665 self._checkClosed()
666 if self._sslobj:
667 raise ValueError("recvfrom_into not allowed on instances of %s" %
668 self.__class__)
669 else:
670 return socket.recvfrom_into(self, buffer, nbytes, flags)
671
Nick Coghlan513886a2011-08-28 00:00:27 +1000672 def recvmsg(self, *args, **kwargs):
673 raise NotImplementedError("recvmsg not allowed on instances of %s" %
674 self.__class__)
675
676 def recvmsg_into(self, *args, **kwargs):
677 raise NotImplementedError("recvmsg_into not allowed on instances of "
678 "%s" % self.__class__)
679
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000680 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000681 self._checkClosed()
682 if self._sslobj:
683 return self._sslobj.pending()
684 else:
685 return 0
686
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000687 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000688 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000690 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000691
Ezio Melottidc55e672010-01-18 09:15:14 +0000692 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000693 if self._sslobj:
694 s = self._sslobj.shutdown()
695 self._sslobj = None
696 return s
697 else:
698 raise ValueError("No SSL wrapper around " + str(self))
699
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000700 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000702 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000703
Bill Janssen48dc27c2007-12-05 03:38:10 +0000704 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000705 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200706 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000707 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000708 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000709 if timeout == 0.0 and block:
710 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000711 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000712 finally:
713 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000714
Antoine Pitroub4410db2011-05-18 18:51:06 +0200715 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000716 if self.server_side:
717 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000718 # Here we assume that the socket is client-side, and not
719 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000720 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000722 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000723 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200724 if connect_ex:
725 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000726 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200727 rc = None
728 socket.connect(self, addr)
729 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200730 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200731 if self.do_handshake_on_connect:
732 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200733 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200734 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200735 self._sslobj = None
736 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000737
738 def connect(self, addr):
739 """Connects to remote ADDR, and then wraps the connection in
740 an SSL channel."""
741 self._real_connect(addr, False)
742
743 def connect_ex(self, addr):
744 """Connects to remote ADDR, and then wraps the connection in
745 an SSL channel."""
746 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000747
748 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000749 """Accepts a new connection from a remote client, and returns
750 a tuple containing that new connection wrapped with a server-side
751 SSL channel, and the address of the remote client."""
752
753 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100754 newsock = self.context.wrap_socket(newsock,
755 do_handshake_on_connect=self.do_handshake_on_connect,
756 suppress_ragged_eofs=self.suppress_ragged_eofs,
757 server_side=True)
758 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759
Antoine Pitroud6494802011-07-21 01:11:30 +0200760 def get_channel_binding(self, cb_type="tls-unique"):
761 """Get channel binding data for current connection. Raise ValueError
762 if the requested `cb_type` is not supported. Return bytes of the data
763 or None if the data is not available (e.g. before the handshake).
764 """
765 if cb_type not in CHANNEL_BINDING_TYPES:
766 raise ValueError("Unsupported channel binding type")
767 if cb_type != "tls-unique":
768 raise NotImplementedError(
769 "{0} channel binding type not implemented"
770 .format(cb_type))
771 if self._sslobj is None:
772 return None
773 return self._sslobj.tls_unique_cb()
774
Bill Janssen54cc54c2007-12-14 22:08:56 +0000775
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776def wrap_socket(sock, keyfile=None, certfile=None,
777 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000778 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000779 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100780 suppress_ragged_eofs=True,
781 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Bill Janssen6e027db2007-11-15 22:23:56 +0000783 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000785 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000786 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000787 suppress_ragged_eofs=suppress_ragged_eofs,
788 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Thomas Woutersed03b412007-08-28 21:37:11 +0000790# some utility functions
791
792def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000793 """Takes a date-time string in standard ASN1_print form
794 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
795 a Python time value in seconds past the epoch."""
796
Thomas Woutersed03b412007-08-28 21:37:11 +0000797 import time
798 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
799
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800PEM_HEADER = "-----BEGIN CERTIFICATE-----"
801PEM_FOOTER = "-----END CERTIFICATE-----"
802
803def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804 """Takes a certificate in binary DER format and returns the
805 PEM version of it as a string."""
806
Bill Janssen6e027db2007-11-15 22:23:56 +0000807 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
808 return (PEM_HEADER + '\n' +
809 textwrap.fill(f, 64) + '\n' +
810 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
812def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813 """Takes a certificate in ASCII PEM format and returns the
814 DER-encoded version of it as a byte sequence"""
815
816 if not pem_cert_string.startswith(PEM_HEADER):
817 raise ValueError("Invalid PEM encoding; must start with %s"
818 % PEM_HEADER)
819 if not pem_cert_string.strip().endswith(PEM_FOOTER):
820 raise ValueError("Invalid PEM encoding; must end with %s"
821 % PEM_FOOTER)
822 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000823 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000825def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826 """Retrieve the certificate from the server at the specified address,
827 and return it as a PEM-encoded string.
828 If 'ca_certs' is specified, validate the server cert against it.
829 If 'ssl_version' is specified, use it in the connection attempt."""
830
831 host, port = addr
832 if (ca_certs is not None):
833 cert_reqs = CERT_REQUIRED
834 else:
835 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200836 s = create_connection(addr)
837 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839 dercert = s.getpeercert(True)
840 s.close()
841 return DER_cert_to_PEM_cert(dercert)
842
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000843def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200844 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')