ยปCore Development>Code coverage>Lib/ssl.py

Python code coverage for Lib/ssl.py

#countcontent
1n/a# Wrapper module for _ssl, providing some additional facilities
2n/a# implemented in Python. Written by Bill Janssen.
3n/a
4n/a"""This module provides some more Pythonic support for SSL.
5n/a
6n/aObject types:
7n/a
8n/a SSLSocket -- subtype of socket.socket which does SSL over the socket
9n/a
10n/aExceptions:
11n/a
12n/a SSLError -- exception raised for I/O errors
13n/a
14n/aFunctions:
15n/a
16n/a cert_time_to_seconds -- convert time string used for certificate
17n/a notBefore and notAfter functions to integer
18n/a seconds past the Epoch (the time values
19n/a returned from time.time())
20n/a
21n/a fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22n/a by the server running on HOST at port PORT. No
23n/a validation of the certificate is performed.
24n/a
25n/aInteger constants:
26n/a
27n/aSSL_ERROR_ZERO_RETURN
28n/aSSL_ERROR_WANT_READ
29n/aSSL_ERROR_WANT_WRITE
30n/aSSL_ERROR_WANT_X509_LOOKUP
31n/aSSL_ERROR_SYSCALL
32n/aSSL_ERROR_SSL
33n/aSSL_ERROR_WANT_CONNECT
34n/a
35n/aSSL_ERROR_EOF
36n/aSSL_ERROR_INVALID_ERROR_CODE
37n/a
38n/aThe following group define certificate requirements that one side is
39n/aallowing/requiring from the other side:
40n/a
41n/aCERT_NONE - no certificates from the other side are required (or will
42n/a be looked at if provided)
43n/aCERT_OPTIONAL - certificates are not required, but if provided will be
44n/a validated, and if validation fails, the connection will
45n/a also fail
46n/aCERT_REQUIRED - certificates are required, and will be validated, and
47n/a if validation fails, the connection will also fail
48n/a
49n/aThe following constants identify various SSL protocol variants:
50n/a
51n/aPROTOCOL_SSLv2
52n/aPROTOCOL_SSLv3
53n/aPROTOCOL_SSLv23
54n/aPROTOCOL_TLSv1
55n/aPROTOCOL_TLSv1_1
56n/aPROTOCOL_TLSv1_2
57n/a
58n/aThe following constants identify various SSL alert message descriptions as per
59n/ahttp://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
60n/a
61n/aALERT_DESCRIPTION_CLOSE_NOTIFY
62n/aALERT_DESCRIPTION_UNEXPECTED_MESSAGE
63n/aALERT_DESCRIPTION_BAD_RECORD_MAC
64n/aALERT_DESCRIPTION_RECORD_OVERFLOW
65n/aALERT_DESCRIPTION_DECOMPRESSION_FAILURE
66n/aALERT_DESCRIPTION_HANDSHAKE_FAILURE
67n/aALERT_DESCRIPTION_BAD_CERTIFICATE
68n/aALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
69n/aALERT_DESCRIPTION_CERTIFICATE_REVOKED
70n/aALERT_DESCRIPTION_CERTIFICATE_EXPIRED
71n/aALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
72n/aALERT_DESCRIPTION_ILLEGAL_PARAMETER
73n/aALERT_DESCRIPTION_UNKNOWN_CA
74n/aALERT_DESCRIPTION_ACCESS_DENIED
75n/aALERT_DESCRIPTION_DECODE_ERROR
76n/aALERT_DESCRIPTION_DECRYPT_ERROR
77n/aALERT_DESCRIPTION_PROTOCOL_VERSION
78n/aALERT_DESCRIPTION_INSUFFICIENT_SECURITY
79n/aALERT_DESCRIPTION_INTERNAL_ERROR
80n/aALERT_DESCRIPTION_USER_CANCELLED
81n/aALERT_DESCRIPTION_NO_RENEGOTIATION
82n/aALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
83n/aALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
84n/aALERT_DESCRIPTION_UNRECOGNIZED_NAME
85n/aALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
86n/aALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
87n/aALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
88n/a"""
89n/a
90n/aimport textwrap
91n/aimport re
92n/aimport sys
93n/aimport os
94n/aimport collections
95n/a
96n/aimport _ssl # if we can't import it, let the error propagate
97n/a
98n/afrom _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
99n/afrom _ssl import _SSLContext
100n/afrom _ssl import (
101n/a SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
102n/a SSLSyscallError, SSLEOFError,
103n/a )
104n/afrom _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
105n/afrom _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
106n/a
107n/adef _import_symbols(prefix):
108n/a for n in dir(_ssl):
109n/a if n.startswith(prefix):
110n/a globals()[n] = getattr(_ssl, n)
111n/a
112n/a_import_symbols('OP_')
113n/a_import_symbols('ALERT_DESCRIPTION_')
114n/a_import_symbols('SSL_ERROR_')
115n/a
116n/afrom _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
117n/a
118n/afrom _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
119n/afrom _ssl import _OPENSSL_API_VERSION
120n/a
121n/a
122n/a_PROTOCOL_NAMES = {
123n/a PROTOCOL_TLSv1: "TLSv1",
124n/a PROTOCOL_SSLv23: "SSLv23",
125n/a PROTOCOL_SSLv3: "SSLv3",
126n/a}
127n/atry:
128n/a from _ssl import PROTOCOL_SSLv2
129n/a _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
130n/aexcept ImportError:
131n/a _SSLv2_IF_EXISTS = None
132n/aelse:
133n/a _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
134n/a
135n/atry:
136n/a from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
137n/aexcept ImportError:
138n/a pass
139n/aelse:
140n/a _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
141n/a _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
142n/a
143n/aif sys.platform == "win32":
144n/a from _ssl import enum_cert_store, X509_ASN_ENCODING, PKCS_7_ASN_ENCODING
145n/a
146n/afrom socket import getnameinfo as _getnameinfo
147n/afrom socket import socket, AF_INET, SOCK_STREAM, create_connection
148n/aimport base64 # for DER-to-PEM translation
149n/aimport traceback
150n/aimport errno
151n/a
152n/a
153n/asocket_error = OSError # keep that public name in module namespace
154n/a
155n/aif _ssl.HAS_TLS_UNIQUE:
156n/a CHANNEL_BINDING_TYPES = ['tls-unique']
157n/aelse:
158n/a CHANNEL_BINDING_TYPES = []
159n/a
160n/a# Disable weak or insecure ciphers by default
161n/a# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
162n/a_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
163n/a
164n/a
165n/aclass CertificateError(ValueError):
166n/a pass
167n/a
168n/a
169n/adef _dnsname_to_pat(dn, max_wildcards=1):
170n/a pats = []
171n/a for frag in dn.split(r'.'):
172n/a if frag.count('*') > max_wildcards:
173n/a # Issue #17980: avoid denials of service by refusing more
174n/a # than one wildcard per fragment. A survery of established
175n/a # policy among SSL implementations showed it to be a
176n/a # reasonable choice.
177n/a raise CertificateError(
178n/a "too many wildcards in certificate DNS name: " + repr(dn))
179n/a if frag == '*':
180n/a # When '*' is a fragment by itself, it matches a non-empty dotless
181n/a # fragment.
182n/a pats.append('[^.]+')
183n/a else:
184n/a # Otherwise, '*' matches any dotless fragment.
185n/a frag = re.escape(frag)
186n/a pats.append(frag.replace(r'\*', '[^.]*'))
187n/a return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
188n/a
189n/a
190n/adef match_hostname(cert, hostname):
191n/a """Verify that *cert* (in decoded format as returned by
192n/a SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
193n/a are mostly followed, but IP addresses are not accepted for *hostname*.
194n/a
195n/a CertificateError is raised on failure. On success, the function
196n/a returns nothing.
197n/a """
198n/a if not cert:
199n/a raise ValueError("empty or no certificate")
200n/a dnsnames = []
201n/a san = cert.get('subjectAltName', ())
202n/a for key, value in san:
203n/a if key == 'DNS':
204n/a if _dnsname_to_pat(value).match(hostname):
205n/a return
206n/a dnsnames.append(value)
207n/a if not dnsnames:
208n/a # The subject is only checked when there is no dNSName entry
209n/a # in subjectAltName
210n/a for sub in cert.get('subject', ()):
211n/a for key, value in sub:
212n/a # XXX according to RFC 2818, the most specific Common Name
213n/a # must be used.
214n/a if key == 'commonName':
215n/a if _dnsname_to_pat(value).match(hostname):
216n/a return
217n/a dnsnames.append(value)
218n/a if len(dnsnames) > 1:
219n/a raise CertificateError("hostname %r "
220n/a "doesn't match either of %s"
221n/a % (hostname, ', '.join(map(repr, dnsnames))))
222n/a elif len(dnsnames) == 1:
223n/a raise CertificateError("hostname %r "
224n/a "doesn't match %r"
225n/a % (hostname, dnsnames[0]))
226n/a else:
227n/a raise CertificateError("no appropriate commonName or "
228n/a "subjectAltName fields were found")
229n/a
230n/a
231n/aDefaultVerifyPaths = collections.namedtuple("DefaultVerifyPaths",
232n/a "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
233n/a "openssl_capath")
234n/a
235n/adef get_default_verify_paths():
236n/a """Return paths to default cafile and capath.
237n/a """
238n/a parts = _ssl.get_default_verify_paths()
239n/a
240n/a # environment vars shadow paths
241n/a cafile = os.environ.get(parts[0], parts[1])
242n/a capath = os.environ.get(parts[2], parts[3])
243n/a
244n/a return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
245n/a capath if os.path.isdir(capath) else None,
246n/a *parts)
247n/a
248n/a
249n/aclass SSLContext(_SSLContext):
250n/a """An SSLContext holds various SSL-related configuration options and
251n/a data, such as certificates and possibly a private key."""
252n/a
253n/a __slots__ = ('protocol', '__weakref__')
254n/a
255n/a def __new__(cls, protocol, *args, **kwargs):
256n/a self = _SSLContext.__new__(cls, protocol)
257n/a if protocol != _SSLv2_IF_EXISTS:
258n/a self.set_ciphers(_DEFAULT_CIPHERS)
259n/a return self
260n/a
261n/a def __init__(self, protocol):
262n/a self.protocol = protocol
263n/a
264n/a def wrap_socket(self, sock, server_side=False,
265n/a do_handshake_on_connect=True,
266n/a suppress_ragged_eofs=True,
267n/a server_hostname=None):
268n/a return SSLSocket(sock=sock, server_side=server_side,
269n/a do_handshake_on_connect=do_handshake_on_connect,
270n/a suppress_ragged_eofs=suppress_ragged_eofs,
271n/a server_hostname=server_hostname,
272n/a _context=self)
273n/a
274n/a def set_npn_protocols(self, npn_protocols):
275n/a protos = bytearray()
276n/a for protocol in npn_protocols:
277n/a b = bytes(protocol, 'ascii')
278n/a if len(b) == 0 or len(b) > 255:
279n/a raise SSLError('NPN protocols must be 1 to 255 in length')
280n/a protos.append(len(b))
281n/a protos.extend(b)
282n/a
283n/a self._set_npn_protocols(protos)
284n/a
285n/a
286n/aclass SSLSocket(socket):
287n/a """This class implements a subtype of socket.socket that wraps
288n/a the underlying OS socket in an SSL context when necessary, and
289n/a provides read and write methods over that channel."""
290n/a
291n/a def __init__(self, sock=None, keyfile=None, certfile=None,
292n/a server_side=False, cert_reqs=CERT_NONE,
293n/a ssl_version=PROTOCOL_SSLv23, ca_certs=None,
294n/a do_handshake_on_connect=True,
295n/a family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
296n/a suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
297n/a server_hostname=None,
298n/a _context=None):
299n/a
300n/a if _context:
301n/a self._context = _context
302n/a else:
303n/a if server_side and not certfile:
304n/a raise ValueError("certfile must be specified for server-side "
305n/a "operations")
306n/a if keyfile and not certfile:
307n/a raise ValueError("certfile must be specified")
308n/a if certfile and not keyfile:
309n/a keyfile = certfile
310n/a self._context = SSLContext(ssl_version)
311n/a self._context.verify_mode = cert_reqs
312n/a if ca_certs:
313n/a self._context.load_verify_locations(ca_certs)
314n/a if certfile:
315n/a self._context.load_cert_chain(certfile, keyfile)
316n/a if npn_protocols:
317n/a self._context.set_npn_protocols(npn_protocols)
318n/a if ciphers:
319n/a self._context.set_ciphers(ciphers)
320n/a self.keyfile = keyfile
321n/a self.certfile = certfile
322n/a self.cert_reqs = cert_reqs
323n/a self.ssl_version = ssl_version
324n/a self.ca_certs = ca_certs
325n/a self.ciphers = ciphers
326n/a if server_side and server_hostname:
327n/a raise ValueError("server_hostname can only be specified "
328n/a "in client mode")
329n/a self.server_side = server_side
330n/a self.server_hostname = server_hostname
331n/a self.do_handshake_on_connect = do_handshake_on_connect
332n/a self.suppress_ragged_eofs = suppress_ragged_eofs
333n/a if sock is not None:
334n/a socket.__init__(self,
335n/a family=sock.family,
336n/a type=sock.type,
337n/a proto=sock.proto,
338n/a fileno=sock.fileno())
339n/a self.settimeout(sock.gettimeout())
340n/a sock.detach()
341n/a elif fileno is not None:
342n/a socket.__init__(self, fileno=fileno)
343n/a else:
344n/a socket.__init__(self, family=family, type=type, proto=proto)
345n/a
346n/a # See if we are connected
347n/a try:
348n/a self.getpeername()
349n/a except OSError as e:
350n/a if e.errno != errno.ENOTCONN:
351n/a raise
352n/a connected = False
353n/a else:
354n/a connected = True
355n/a
356n/a self._closed = False
357n/a self._sslobj = None
358n/a self._connected = connected
359n/a if connected:
360n/a # create the SSL object
361n/a try:
362n/a self._sslobj = self._context._wrap_socket(self, server_side,
363n/a server_hostname)
364n/a if do_handshake_on_connect:
365n/a timeout = self.gettimeout()
366n/a if timeout == 0.0:
367n/a # non-blocking
368n/a raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
369n/a self.do_handshake()
370n/a
371n/a except OSError as x:
372n/a self.close()
373n/a raise x
374n/a
375n/a @property
376n/a def context(self):
377n/a return self._context
378n/a
379n/a @context.setter
380n/a def context(self, ctx):
381n/a self._context = ctx
382n/a self._sslobj.context = ctx
383n/a
384n/a def dup(self):
385n/a raise NotImplemented("Can't dup() %s instances" %
386n/a self.__class__.__name__)
387n/a
388n/a def _checkClosed(self, msg=None):
389n/a # raise an exception here if you wish to check for spurious closes
390n/a pass
391n/a
392n/a def _check_connected(self):
393n/a if not self._connected:
394n/a # getpeername() will raise ENOTCONN if the socket is really
395n/a # not connected; note that we can be connected even without
396n/a # _connected being set, e.g. if connect() first returned
397n/a # EAGAIN.
398n/a self.getpeername()
399n/a
400n/a def read(self, len=0, buffer=None):
401n/a """Read up to LEN bytes and return them.
402n/a Return zero-length string on EOF."""
403n/a
404n/a self._checkClosed()
405n/a if not self._sslobj:
406n/a raise ValueError("Read on closed or unwrapped SSL socket.")
407n/a try:
408n/a if buffer is not None:
409n/a v = self._sslobj.read(len, buffer)
410n/a else:
411n/a v = self._sslobj.read(len or 1024)
412n/a return v
413n/a except SSLError as x:
414n/a if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
415n/a if buffer is not None:
416n/a return 0
417n/a else:
418n/a return b''
419n/a else:
420n/a raise
421n/a
422n/a def write(self, data):
423n/a """Write DATA to the underlying SSL channel. Returns
424n/a number of bytes of DATA actually transmitted."""
425n/a
426n/a self._checkClosed()
427n/a if not self._sslobj:
428n/a raise ValueError("Write on closed or unwrapped SSL socket.")
429n/a return self._sslobj.write(data)
430n/a
431n/a def getpeercert(self, binary_form=False):
432n/a """Returns a formatted version of the data in the
433n/a certificate provided by the other end of the SSL channel.
434n/a Return None if no certificate was provided, {} if a
435n/a certificate was provided, but not validated."""
436n/a
437n/a self._checkClosed()
438n/a self._check_connected()
439n/a return self._sslobj.peer_certificate(binary_form)
440n/a
441n/a def selected_npn_protocol(self):
442n/a self._checkClosed()
443n/a if not self._sslobj or not _ssl.HAS_NPN:
444n/a return None
445n/a else:
446n/a return self._sslobj.selected_npn_protocol()
447n/a
448n/a def cipher(self):
449n/a self._checkClosed()
450n/a if not self._sslobj:
451n/a return None
452n/a else:
453n/a return self._sslobj.cipher()
454n/a
455n/a def compression(self):
456n/a self._checkClosed()
457n/a if not self._sslobj:
458n/a return None
459n/a else:
460n/a return self._sslobj.compression()
461n/a
462n/a def send(self, data, flags=0):
463n/a self._checkClosed()
464n/a if self._sslobj:
465n/a if flags != 0:
466n/a raise ValueError(
467n/a "non-zero flags not allowed in calls to send() on %s" %
468n/a self.__class__)
469n/a try:
470n/a v = self._sslobj.write(data)
471n/a except SSLError as x:
472n/a if x.args[0] == SSL_ERROR_WANT_READ:
473n/a return 0
474n/a elif x.args[0] == SSL_ERROR_WANT_WRITE:
475n/a return 0
476n/a else:
477n/a raise
478n/a else:
479n/a return v
480n/a else:
481n/a return socket.send(self, data, flags)
482n/a
483n/a def sendto(self, data, flags_or_addr, addr=None):
484n/a self._checkClosed()
485n/a if self._sslobj:
486n/a raise ValueError("sendto not allowed on instances of %s" %
487n/a self.__class__)
488n/a elif addr is None:
489n/a return socket.sendto(self, data, flags_or_addr)
490n/a else:
491n/a return socket.sendto(self, data, flags_or_addr, addr)
492n/a
493n/a def sendmsg(self, *args, **kwargs):
494n/a # Ensure programs don't send data unencrypted if they try to
495n/a # use this method.
496n/a raise NotImplementedError("sendmsg not allowed on instances of %s" %
497n/a self.__class__)
498n/a
499n/a def sendall(self, data, flags=0):
500n/a self._checkClosed()
501n/a if self._sslobj:
502n/a if flags != 0:
503n/a raise ValueError(
504n/a "non-zero flags not allowed in calls to sendall() on %s" %
505n/a self.__class__)
506n/a amount = len(data)
507n/a count = 0
508n/a while (count < amount):
509n/a v = self.send(data[count:])
510n/a count += v
511n/a return amount
512n/a else:
513n/a return socket.sendall(self, data, flags)
514n/a
515n/a def recv(self, buflen=1024, flags=0):
516n/a self._checkClosed()
517n/a if self._sslobj:
518n/a if flags != 0:
519n/a raise ValueError(
520n/a "non-zero flags not allowed in calls to recv() on %s" %
521n/a self.__class__)
522n/a return self.read(buflen)
523n/a else:
524n/a return socket.recv(self, buflen, flags)
525n/a
526n/a def recv_into(self, buffer, nbytes=None, flags=0):
527n/a self._checkClosed()
528n/a if buffer and (nbytes is None):
529n/a nbytes = len(buffer)
530n/a elif nbytes is None:
531n/a nbytes = 1024
532n/a if self._sslobj:
533n/a if flags != 0:
534n/a raise ValueError(
535n/a "non-zero flags not allowed in calls to recv_into() on %s" %
536n/a self.__class__)
537n/a return self.read(nbytes, buffer)
538n/a else:
539n/a return socket.recv_into(self, buffer, nbytes, flags)
540n/a
541n/a def recvfrom(self, buflen=1024, flags=0):
542n/a self._checkClosed()
543n/a if self._sslobj:
544n/a raise ValueError("recvfrom not allowed on instances of %s" %
545n/a self.__class__)
546n/a else:
547n/a return socket.recvfrom(self, buflen, flags)
548n/a
549n/a def recvfrom_into(self, buffer, nbytes=None, flags=0):
550n/a self._checkClosed()
551n/a if self._sslobj:
552n/a raise ValueError("recvfrom_into not allowed on instances of %s" %
553n/a self.__class__)
554n/a else:
555n/a return socket.recvfrom_into(self, buffer, nbytes, flags)
556n/a
557n/a def recvmsg(self, *args, **kwargs):
558n/a raise NotImplementedError("recvmsg not allowed on instances of %s" %
559n/a self.__class__)
560n/a
561n/a def recvmsg_into(self, *args, **kwargs):
562n/a raise NotImplementedError("recvmsg_into not allowed on instances of "
563n/a "%s" % self.__class__)
564n/a
565n/a def pending(self):
566n/a self._checkClosed()
567n/a if self._sslobj:
568n/a return self._sslobj.pending()
569n/a else:
570n/a return 0
571n/a
572n/a def shutdown(self, how):
573n/a self._checkClosed()
574n/a self._sslobj = None
575n/a socket.shutdown(self, how)
576n/a
577n/a def unwrap(self):
578n/a if self._sslobj:
579n/a s = self._sslobj.shutdown()
580n/a self._sslobj = None
581n/a return s
582n/a else:
583n/a raise ValueError("No SSL wrapper around " + str(self))
584n/a
585n/a def _real_close(self):
586n/a self._sslobj = None
587n/a socket._real_close(self)
588n/a
589n/a def do_handshake(self, block=False):
590n/a """Perform a TLS/SSL handshake."""
591n/a self._check_connected()
592n/a timeout = self.gettimeout()
593n/a try:
594n/a if timeout == 0.0 and block:
595n/a self.settimeout(None)
596n/a self._sslobj.do_handshake()
597n/a finally:
598n/a self.settimeout(timeout)
599n/a
600n/a def _real_connect(self, addr, connect_ex):
601n/a if self.server_side:
602n/a raise ValueError("can't connect in server-side mode")
603n/a # Here we assume that the socket is client-side, and not
604n/a # connected at the time of the call. We connect it, then wrap it.
605n/a if self._connected:
606n/a raise ValueError("attempt to connect already-connected SSLSocket!")
607n/a self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
608n/a try:
609n/a if connect_ex:
610n/a rc = socket.connect_ex(self, addr)
611n/a else:
612n/a rc = None
613n/a socket.connect(self, addr)
614n/a if not rc:
615n/a self._connected = True
616n/a if self.do_handshake_on_connect:
617n/a self.do_handshake()
618n/a return rc
619n/a except OSError:
620n/a self._sslobj = None
621n/a raise
622n/a
623n/a def connect(self, addr):
624n/a """Connects to remote ADDR, and then wraps the connection in
625n/a an SSL channel."""
626n/a self._real_connect(addr, False)
627n/a
628n/a def connect_ex(self, addr):
629n/a """Connects to remote ADDR, and then wraps the connection in
630n/a an SSL channel."""
631n/a return self._real_connect(addr, True)
632n/a
633n/a def accept(self):
634n/a """Accepts a new connection from a remote client, and returns
635n/a a tuple containing that new connection wrapped with a server-side
636n/a SSL channel, and the address of the remote client."""
637n/a
638n/a newsock, addr = socket.accept(self)
639n/a newsock = self.context.wrap_socket(newsock,
640n/a do_handshake_on_connect=self.do_handshake_on_connect,
641n/a suppress_ragged_eofs=self.suppress_ragged_eofs,
642n/a server_side=True)
643n/a return newsock, addr
644n/a
645n/a def get_channel_binding(self, cb_type="tls-unique"):
646n/a """Get channel binding data for current connection. Raise ValueError
647n/a if the requested `cb_type` is not supported. Return bytes of the data
648n/a or None if the data is not available (e.g. before the handshake).
649n/a """
650n/a if cb_type not in CHANNEL_BINDING_TYPES:
651n/a raise ValueError("Unsupported channel binding type")
652n/a if cb_type != "tls-unique":
653n/a raise NotImplementedError(
654n/a "{0} channel binding type not implemented"
655n/a .format(cb_type))
656n/a if self._sslobj is None:
657n/a return None
658n/a return self._sslobj.tls_unique_cb()
659n/a
660n/a
661n/adef wrap_socket(sock, keyfile=None, certfile=None,
662n/a server_side=False, cert_reqs=CERT_NONE,
663n/a ssl_version=PROTOCOL_SSLv23, ca_certs=None,
664n/a do_handshake_on_connect=True,
665n/a suppress_ragged_eofs=True,
666n/a ciphers=None):
667n/a
668n/a return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
669n/a server_side=server_side, cert_reqs=cert_reqs,
670n/a ssl_version=ssl_version, ca_certs=ca_certs,
671n/a do_handshake_on_connect=do_handshake_on_connect,
672n/a suppress_ragged_eofs=suppress_ragged_eofs,
673n/a ciphers=ciphers)
674n/a
675n/a# some utility functions
676n/a
677n/adef cert_time_to_seconds(cert_time):
678n/a """Takes a date-time string in standard ASN1_print form
679n/a ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
680n/a a Python time value in seconds past the epoch."""
681n/a
682n/a import time
683n/a return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
684n/a
685n/aPEM_HEADER = "-----BEGIN CERTIFICATE-----"
686n/aPEM_FOOTER = "-----END CERTIFICATE-----"
687n/a
688n/adef DER_cert_to_PEM_cert(der_cert_bytes):
689n/a """Takes a certificate in binary DER format and returns the
690n/a PEM version of it as a string."""
691n/a
692n/a f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
693n/a return (PEM_HEADER + '\n' +
694n/a textwrap.fill(f, 64) + '\n' +
695n/a PEM_FOOTER + '\n')
696n/a
697n/adef PEM_cert_to_DER_cert(pem_cert_string):
698n/a """Takes a certificate in ASCII PEM format and returns the
699n/a DER-encoded version of it as a byte sequence"""
700n/a
701n/a if not pem_cert_string.startswith(PEM_HEADER):
702n/a raise ValueError("Invalid PEM encoding; must start with %s"
703n/a % PEM_HEADER)
704n/a if not pem_cert_string.strip().endswith(PEM_FOOTER):
705n/a raise ValueError("Invalid PEM encoding; must end with %s"
706n/a % PEM_FOOTER)
707n/a d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
708n/a return base64.decodebytes(d.encode('ASCII', 'strict'))
709n/a
710n/adef get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
711n/a """Retrieve the certificate from the server at the specified address,
712n/a and return it as a PEM-encoded string.
713n/a If 'ca_certs' is specified, validate the server cert against it.
714n/a If 'ssl_version' is specified, use it in the connection attempt."""
715n/a
716n/a host, port = addr
717n/a if (ca_certs is not None):
718n/a cert_reqs = CERT_REQUIRED
719n/a else:
720n/a cert_reqs = CERT_NONE
721n/a s = create_connection(addr)
722n/a s = wrap_socket(s, ssl_version=ssl_version,
723n/a cert_reqs=cert_reqs, ca_certs=ca_certs)
724n/a dercert = s.getpeercert(True)
725n/a s.close()
726n/a return DER_cert_to_PEM_cert(dercert)
727n/a
728n/adef get_protocol_name(protocol_code):
729n/a return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')