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