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