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