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