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) |
| 413 | self.load_verify_locations(cadata=certs) |
| 414 | return certs |
| 415 | |
| 416 | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
| 417 | if not isinstance(purpose, _ASN1Object): |
| 418 | raise TypeError(purpose) |
| 419 | if sys.platform == "win32": |
| 420 | for storename in self._windows_cert_stores: |
| 421 | self._load_windows_store_certs(storename, purpose) |
Benjamin Peterson | 5915b0f | 2014-10-03 17:27:05 -0400 | [diff] [blame] | 422 | self.set_default_verify_paths() |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 423 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 424 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 425 | def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, |
| 426 | capath=None, cadata=None): |
| 427 | """Create a SSLContext object with default settings. |
| 428 | |
| 429 | NOTE: The protocol and settings may change anytime without prior |
| 430 | deprecation. The values represent a fair balance between maximum |
| 431 | compatibility and security. |
| 432 | """ |
| 433 | if not isinstance(purpose, _ASN1Object): |
| 434 | raise TypeError(purpose) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 435 | |
| 436 | context = SSLContext(PROTOCOL_SSLv23) |
| 437 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 438 | # SSLv2 considered harmful. |
| 439 | context.options |= OP_NO_SSLv2 |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 440 | |
| 441 | # SSLv3 has problematic security and is only required for really old |
| 442 | # clients such as IE6 on Windows XP |
| 443 | context.options |= OP_NO_SSLv3 |
| 444 | |
Christian Heimes | dec813f | 2013-11-28 08:06:54 +0100 | [diff] [blame] | 445 | # disable compression to prevent CRIME attacks (OpenSSL 1.0+) |
| 446 | context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0) |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 447 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 448 | if purpose == Purpose.SERVER_AUTH: |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 449 | # verify certs and host name in client mode |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 450 | context.verify_mode = CERT_REQUIRED |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 451 | context.check_hostname = True |
Donald Stufft | 6a2ba94 | 2014-03-23 19:05:28 -0400 | [diff] [blame] | 452 | elif purpose == Purpose.CLIENT_AUTH: |
| 453 | # Prefer the server's ciphers by default so that we get stronger |
| 454 | # encryption |
| 455 | context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) |
| 456 | |
| 457 | # Use single use keys in order to improve forward secrecy |
| 458 | context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0) |
| 459 | context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0) |
| 460 | |
| 461 | # disallow ciphers with known vulnerabilities |
| 462 | context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) |
| 463 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 464 | if cafile or capath or cadata: |
| 465 | context.load_verify_locations(cafile, capath, cadata) |
| 466 | elif context.verify_mode != CERT_NONE: |
| 467 | # no explicit cafile, capath or cadata but the verify mode is |
| 468 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 469 | # root CA certificates for the given purpose. This may fail silently. |
| 470 | context.load_default_certs(purpose) |
| 471 | return context |
| 472 | |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 473 | def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None, |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 474 | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 475 | certfile=None, keyfile=None, |
| 476 | cafile=None, capath=None, cadata=None): |
| 477 | """Create a SSLContext object for Python stdlib modules |
| 478 | |
| 479 | All Python stdlib modules shall use this function to create SSLContext |
| 480 | objects in order to keep common settings in one place. The configuration |
| 481 | is less restrict than create_default_context()'s to increase backward |
| 482 | compatibility. |
| 483 | """ |
| 484 | if not isinstance(purpose, _ASN1Object): |
| 485 | raise TypeError(purpose) |
| 486 | |
| 487 | context = SSLContext(protocol) |
| 488 | # SSLv2 considered harmful. |
| 489 | context.options |= OP_NO_SSLv2 |
Antoine Pitrou | e4eda4d | 2014-10-17 19:28:30 +0200 | [diff] [blame] | 490 | # SSLv3 has problematic security and is only required for really old |
| 491 | # clients such as IE6 on Windows XP |
| 492 | context.options |= OP_NO_SSLv3 |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 493 | |
| 494 | if cert_reqs is not None: |
| 495 | context.verify_mode = cert_reqs |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 496 | context.check_hostname = check_hostname |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 497 | |
| 498 | if keyfile and not certfile: |
| 499 | raise ValueError("certfile must be specified") |
| 500 | if certfile or keyfile: |
| 501 | context.load_cert_chain(certfile, keyfile) |
| 502 | |
| 503 | # load CA root certs |
| 504 | if cafile or capath or cadata: |
| 505 | context.load_verify_locations(cafile, capath, cadata) |
| 506 | elif context.verify_mode != CERT_NONE: |
| 507 | # no explicit cafile, capath or cadata but the verify mode is |
| 508 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 509 | # root CA certificates for the given purpose. This may fail silently. |
| 510 | context.load_default_certs(purpose) |
| 511 | |
| 512 | return context |
| 513 | |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 514 | # Used by http.client if no context is explicitly passed. |
| 515 | _create_default_https_context = create_default_context |
| 516 | |
| 517 | |
| 518 | # Backwards compatibility alias, even though it's not a public name. |
| 519 | _create_stdlib_context = _create_unverified_context |
| 520 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 521 | |
| 522 | class SSLObject: |
| 523 | """This class implements an interface on top of a low-level SSL object as |
| 524 | implemented by OpenSSL. This object captures the state of an SSL connection |
| 525 | but does not provide any network IO itself. IO needs to be performed |
| 526 | through separate "BIO" objects which are OpenSSL's IO abstraction layer. |
| 527 | |
| 528 | This class does not have a public constructor. Instances are returned by |
| 529 | ``SSLContext.wrap_bio``. This class is typically used by framework authors |
| 530 | that want to implement asynchronous IO for SSL through memory buffers. |
| 531 | |
| 532 | When compared to ``SSLSocket``, this object lacks the following features: |
| 533 | |
| 534 | * Any form of network IO incluging methods such as ``recv`` and ``send``. |
| 535 | * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. |
| 536 | """ |
| 537 | |
| 538 | def __init__(self, sslobj, owner=None): |
| 539 | self._sslobj = sslobj |
| 540 | # Note: _sslobj takes a weak reference to owner |
| 541 | self._sslobj.owner = owner or self |
| 542 | |
| 543 | @property |
| 544 | def context(self): |
| 545 | """The SSLContext that is currently in use.""" |
| 546 | return self._sslobj.context |
| 547 | |
| 548 | @context.setter |
| 549 | def context(self, ctx): |
| 550 | self._sslobj.context = ctx |
| 551 | |
| 552 | @property |
| 553 | def server_side(self): |
| 554 | """Whether this is a server-side socket.""" |
| 555 | return self._sslobj.server_side |
| 556 | |
| 557 | @property |
| 558 | def server_hostname(self): |
| 559 | """The currently set server hostname (for SNI), or ``None`` if no |
| 560 | server hostame is set.""" |
| 561 | return self._sslobj.server_hostname |
| 562 | |
| 563 | def read(self, len=0, buffer=None): |
| 564 | """Read up to 'len' bytes from the SSL object and return them. |
| 565 | |
| 566 | If 'buffer' is provided, read into this buffer and return the number of |
| 567 | bytes read. |
| 568 | """ |
| 569 | if buffer is not None: |
| 570 | v = self._sslobj.read(len, buffer) |
| 571 | else: |
| 572 | v = self._sslobj.read(len or 1024) |
| 573 | return v |
| 574 | |
| 575 | def write(self, data): |
| 576 | """Write 'data' to the SSL object and return the number of bytes |
| 577 | written. |
| 578 | |
| 579 | The 'data' argument must support the buffer interface. |
| 580 | """ |
| 581 | return self._sslobj.write(data) |
| 582 | |
| 583 | def getpeercert(self, binary_form=False): |
| 584 | """Returns a formatted version of the data in the certificate provided |
| 585 | by the other end of the SSL channel. |
| 586 | |
| 587 | Return None if no certificate was provided, {} if a certificate was |
| 588 | provided, but not validated. |
| 589 | """ |
| 590 | return self._sslobj.peer_certificate(binary_form) |
| 591 | |
| 592 | def selected_npn_protocol(self): |
| 593 | """Return the currently selected NPN protocol as a string, or ``None`` |
| 594 | if a next protocol was not negotiated or if NPN is not supported by one |
| 595 | of the peers.""" |
| 596 | if _ssl.HAS_NPN: |
| 597 | return self._sslobj.selected_npn_protocol() |
| 598 | |
Benjamin Peterson | cca2732 | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 599 | def selected_alpn_protocol(self): |
| 600 | """Return the currently selected ALPN protocol as a string, or ``None`` |
| 601 | if a next protocol was not negotiated or if ALPN is not supported by one |
| 602 | of the peers.""" |
| 603 | if _ssl.HAS_ALPN: |
| 604 | return self._sslobj.selected_alpn_protocol() |
| 605 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 606 | def cipher(self): |
| 607 | """Return the currently selected cipher as a 3-tuple ``(name, |
| 608 | ssl_version, secret_bits)``.""" |
| 609 | return self._sslobj.cipher() |
| 610 | |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 611 | def shared_ciphers(self): |
Benjamin Peterson | c114e7d | 2015-01-11 15:22:07 -0500 | [diff] [blame] | 612 | """Return a list of ciphers shared by the client during the handshake or |
| 613 | None if this is not a valid server connection. |
Benjamin Peterson | 5318c7a | 2015-01-07 11:26:50 -0600 | [diff] [blame] | 614 | """ |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 615 | return self._sslobj.shared_ciphers() |
| 616 | |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 617 | def compression(self): |
| 618 | """Return the current compression algorithm in use, or ``None`` if |
| 619 | compression was not negotiated or not supported by one of the peers.""" |
| 620 | return self._sslobj.compression() |
| 621 | |
| 622 | def pending(self): |
| 623 | """Return the number of bytes that can be read immediately.""" |
| 624 | return self._sslobj.pending() |
| 625 | |
Antoine Pitrou | 3cb9379 | 2014-10-06 00:21:09 +0200 | [diff] [blame] | 626 | def do_handshake(self): |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 627 | """Start the SSL/TLS handshake.""" |
| 628 | self._sslobj.do_handshake() |
| 629 | if self.context.check_hostname: |
| 630 | if not self.server_hostname: |
| 631 | raise ValueError("check_hostname needs server_hostname " |
| 632 | "argument") |
| 633 | match_hostname(self.getpeercert(), self.server_hostname) |
| 634 | |
| 635 | def unwrap(self): |
| 636 | """Start the SSL shutdown handshake.""" |
| 637 | return self._sslobj.shutdown() |
| 638 | |
| 639 | def get_channel_binding(self, cb_type="tls-unique"): |
| 640 | """Get channel binding data for current connection. Raise ValueError |
| 641 | if the requested `cb_type` is not supported. Return bytes of the data |
| 642 | or None if the data is not available (e.g. before the handshake).""" |
| 643 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 644 | raise ValueError("Unsupported channel binding type") |
| 645 | if cb_type != "tls-unique": |
| 646 | raise NotImplementedError( |
| 647 | "{0} channel binding type not implemented" |
| 648 | .format(cb_type)) |
| 649 | return self._sslobj.tls_unique_cb() |
| 650 | |
| 651 | def version(self): |
| 652 | """Return a string identifying the protocol version used by the |
| 653 | current SSL channel. """ |
| 654 | return self._sslobj.version() |
| 655 | |
| 656 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 657 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 658 | """This class implements a subtype of socket.socket that wraps |
| 659 | the underlying OS socket in an SSL context when necessary, and |
| 660 | provides read and write methods over that channel.""" |
| 661 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 662 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 663 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 664 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 665 | do_handshake_on_connect=True, |
| 666 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 667 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 668 | server_hostname=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 669 | _context=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 670 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 671 | if _context: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 672 | self._context = _context |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 673 | else: |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 674 | if server_side and not certfile: |
| 675 | raise ValueError("certfile must be specified for server-side " |
| 676 | "operations") |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 677 | if keyfile and not certfile: |
| 678 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 679 | if certfile and not keyfile: |
| 680 | keyfile = certfile |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 681 | self._context = SSLContext(ssl_version) |
| 682 | self._context.verify_mode = cert_reqs |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 683 | if ca_certs: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 684 | self._context.load_verify_locations(ca_certs) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 685 | if certfile: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 686 | self._context.load_cert_chain(certfile, keyfile) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 687 | if npn_protocols: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 688 | self._context.set_npn_protocols(npn_protocols) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 689 | if ciphers: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 690 | self._context.set_ciphers(ciphers) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 691 | self.keyfile = keyfile |
| 692 | self.certfile = certfile |
| 693 | self.cert_reqs = cert_reqs |
| 694 | self.ssl_version = ssl_version |
| 695 | self.ca_certs = ca_certs |
| 696 | self.ciphers = ciphers |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 697 | # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get |
| 698 | # mixed in. |
| 699 | if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: |
| 700 | raise NotImplementedError("only stream sockets are supported") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 701 | if server_side and server_hostname: |
| 702 | raise ValueError("server_hostname can only be specified " |
| 703 | "in client mode") |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 704 | if self._context.check_hostname and not server_hostname: |
Benjamin Peterson | 7243b57 | 2014-11-23 17:04:34 -0600 | [diff] [blame] | 705 | raise ValueError("check_hostname requires server_hostname") |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 706 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 707 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 708 | self.do_handshake_on_connect = do_handshake_on_connect |
| 709 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 710 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 711 | socket.__init__(self, |
| 712 | family=sock.family, |
| 713 | type=sock.type, |
| 714 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 715 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 716 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 717 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 718 | elif fileno is not None: |
| 719 | socket.__init__(self, fileno=fileno) |
| 720 | else: |
| 721 | socket.__init__(self, family=family, type=type, proto=proto) |
| 722 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 723 | # See if we are connected |
| 724 | try: |
| 725 | self.getpeername() |
| 726 | except OSError as e: |
| 727 | if e.errno != errno.ENOTCONN: |
| 728 | raise |
| 729 | connected = False |
| 730 | else: |
| 731 | connected = True |
| 732 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 733 | self._closed = False |
| 734 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 735 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 736 | if connected: |
| 737 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 738 | try: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 739 | sslobj = self._context._wrap_socket(self, server_side, |
| 740 | server_hostname) |
| 741 | self._sslobj = SSLObject(sslobj, owner=self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 742 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 743 | timeout = self.gettimeout() |
| 744 | if timeout == 0.0: |
| 745 | # non-blocking |
| 746 | 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] | 747 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 748 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 749 | except (OSError, ValueError): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 750 | self.close() |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 751 | raise |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 752 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 753 | @property |
| 754 | def context(self): |
| 755 | return self._context |
| 756 | |
| 757 | @context.setter |
| 758 | def context(self, ctx): |
| 759 | self._context = ctx |
| 760 | self._sslobj.context = ctx |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 761 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 762 | def dup(self): |
| 763 | raise NotImplemented("Can't dup() %s instances" % |
| 764 | self.__class__.__name__) |
| 765 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 766 | def _checkClosed(self, msg=None): |
| 767 | # raise an exception here if you wish to check for spurious closes |
| 768 | pass |
| 769 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 770 | def _check_connected(self): |
| 771 | if not self._connected: |
| 772 | # getpeername() will raise ENOTCONN if the socket is really |
| 773 | # not connected; note that we can be connected even without |
| 774 | # _connected being set, e.g. if connect() first returned |
| 775 | # EAGAIN. |
| 776 | self.getpeername() |
| 777 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 778 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 779 | """Read up to LEN bytes and return them. |
| 780 | Return zero-length string on EOF.""" |
| 781 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 782 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 783 | if not self._sslobj: |
| 784 | raise ValueError("Read on closed or unwrapped SSL socket.") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 785 | try: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 786 | return self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 787 | except SSLError as x: |
| 788 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 789 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 790 | return 0 |
| 791 | else: |
| 792 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 793 | else: |
| 794 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 795 | |
| 796 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 797 | """Write DATA to the underlying SSL channel. Returns |
| 798 | number of bytes of DATA actually transmitted.""" |
| 799 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 800 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 801 | if not self._sslobj: |
| 802 | raise ValueError("Write on closed or unwrapped SSL socket.") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 803 | return self._sslobj.write(data) |
| 804 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 805 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 806 | """Returns a formatted version of the data in the |
| 807 | certificate provided by the other end of the SSL channel. |
| 808 | Return None if no certificate was provided, {} if a |
| 809 | certificate was provided, but not validated.""" |
| 810 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 811 | self._checkClosed() |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 812 | self._check_connected() |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 813 | return self._sslobj.getpeercert(binary_form) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 814 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 815 | def selected_npn_protocol(self): |
| 816 | self._checkClosed() |
| 817 | if not self._sslobj or not _ssl.HAS_NPN: |
| 818 | return None |
| 819 | else: |
| 820 | return self._sslobj.selected_npn_protocol() |
| 821 | |
Benjamin Peterson | cca2732 | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 822 | def selected_alpn_protocol(self): |
| 823 | self._checkClosed() |
| 824 | if not self._sslobj or not _ssl.HAS_ALPN: |
| 825 | return None |
| 826 | else: |
| 827 | return self._sslobj.selected_alpn_protocol() |
| 828 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 829 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 830 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 831 | if not self._sslobj: |
| 832 | return None |
| 833 | else: |
| 834 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 835 | |
Benjamin Peterson | 4cb1781 | 2015-01-07 11:14:26 -0600 | [diff] [blame] | 836 | def shared_ciphers(self): |
| 837 | self._checkClosed() |
| 838 | if not self._sslobj: |
| 839 | return None |
| 840 | return self._sslobj.shared_ciphers() |
| 841 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 842 | def compression(self): |
| 843 | self._checkClosed() |
| 844 | if not self._sslobj: |
| 845 | return None |
| 846 | else: |
| 847 | return self._sslobj.compression() |
| 848 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 849 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 850 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 851 | if self._sslobj: |
| 852 | if flags != 0: |
| 853 | raise ValueError( |
| 854 | "non-zero flags not allowed in calls to send() on %s" % |
| 855 | self.__class__) |
Antoine Pitrou | b4bebda | 2014-04-29 10:03:28 +0200 | [diff] [blame] | 856 | return self._sslobj.write(data) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 857 | else: |
| 858 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 859 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 860 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 861 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 862 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 863 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 864 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 865 | elif addr is None: |
| 866 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 867 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 868 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 869 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 870 | def sendmsg(self, *args, **kwargs): |
| 871 | # Ensure programs don't send data unencrypted if they try to |
| 872 | # use this method. |
| 873 | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
| 874 | self.__class__) |
| 875 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 876 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 877 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 878 | if self._sslobj: |
Giampaolo Rodolà | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 879 | if flags != 0: |
| 880 | raise ValueError( |
| 881 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 882 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 883 | amount = len(data) |
| 884 | count = 0 |
| 885 | while (count < amount): |
| 886 | v = self.send(data[count:]) |
| 887 | count += v |
| 888 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 889 | else: |
| 890 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 891 | |
Giampaolo Rodola' | 915d141 | 2014-06-11 03:54:30 +0200 | [diff] [blame] | 892 | def sendfile(self, file, offset=0, count=None): |
| 893 | """Send a file, possibly by using os.sendfile() if this is a |
| 894 | clear-text socket. Return the total number of bytes sent. |
| 895 | """ |
| 896 | if self._sslobj is None: |
| 897 | # os.sendfile() works with plain sockets only |
| 898 | return super().sendfile(file, offset, count) |
| 899 | else: |
| 900 | return self._sendfile_use_send(file, offset, count) |
| 901 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 902 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 903 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 904 | if self._sslobj: |
| 905 | if flags != 0: |
| 906 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 907 | "non-zero flags not allowed in calls to recv() on %s" % |
| 908 | self.__class__) |
| 909 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 910 | else: |
| 911 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 912 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 913 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 914 | self._checkClosed() |
| 915 | if buffer and (nbytes is None): |
| 916 | nbytes = len(buffer) |
| 917 | elif nbytes is None: |
| 918 | nbytes = 1024 |
| 919 | if self._sslobj: |
| 920 | if flags != 0: |
| 921 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 922 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 923 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 924 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 925 | else: |
| 926 | return socket.recv_into(self, buffer, nbytes, flags) |
| 927 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 928 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 929 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 930 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 931 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 932 | self.__class__) |
| 933 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 934 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 935 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 936 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 937 | self._checkClosed() |
| 938 | if self._sslobj: |
| 939 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 940 | self.__class__) |
| 941 | else: |
| 942 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 943 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 944 | def recvmsg(self, *args, **kwargs): |
| 945 | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
| 946 | self.__class__) |
| 947 | |
| 948 | def recvmsg_into(self, *args, **kwargs): |
| 949 | raise NotImplementedError("recvmsg_into not allowed on instances of " |
| 950 | "%s" % self.__class__) |
| 951 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 952 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 953 | self._checkClosed() |
| 954 | if self._sslobj: |
| 955 | return self._sslobj.pending() |
| 956 | else: |
| 957 | return 0 |
| 958 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 959 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 960 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 961 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 962 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 963 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 964 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 965 | if self._sslobj: |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 966 | s = self._sslobj.unwrap() |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 967 | self._sslobj = None |
| 968 | return s |
| 969 | else: |
| 970 | raise ValueError("No SSL wrapper around " + str(self)) |
| 971 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 972 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 973 | self._sslobj = None |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 974 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 975 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 976 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 977 | """Perform a TLS/SSL handshake.""" |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 978 | self._check_connected() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 979 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 980 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 981 | if timeout == 0.0 and block: |
| 982 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 983 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 984 | finally: |
| 985 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 986 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 987 | def _real_connect(self, addr, connect_ex): |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 988 | if self.server_side: |
| 989 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 990 | # Here we assume that the socket is client-side, and not |
| 991 | # 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] | 992 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 993 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 994 | sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
| 995 | self._sslobj = SSLObject(sslobj, owner=self) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 996 | try: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 997 | if connect_ex: |
| 998 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 999 | else: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1000 | rc = None |
| 1001 | socket.connect(self, addr) |
| 1002 | if not rc: |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 1003 | self._connected = True |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1004 | if self.do_handshake_on_connect: |
| 1005 | self.do_handshake() |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1006 | return rc |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 1007 | except (OSError, ValueError): |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 1008 | self._sslobj = None |
| 1009 | raise |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 1010 | |
| 1011 | def connect(self, addr): |
| 1012 | """Connects to remote ADDR, and then wraps the connection in |
| 1013 | an SSL channel.""" |
| 1014 | self._real_connect(addr, False) |
| 1015 | |
| 1016 | def connect_ex(self, addr): |
| 1017 | """Connects to remote ADDR, and then wraps the connection in |
| 1018 | an SSL channel.""" |
| 1019 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1020 | |
| 1021 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1022 | """Accepts a new connection from a remote client, and returns |
| 1023 | a tuple containing that new connection wrapped with a server-side |
| 1024 | SSL channel, and the address of the remote client.""" |
| 1025 | |
| 1026 | newsock, addr = socket.accept(self) |
Antoine Pitrou | 5c89b4e | 2012-11-11 01:25:36 +0100 | [diff] [blame] | 1027 | newsock = self.context.wrap_socket(newsock, |
| 1028 | do_handshake_on_connect=self.do_handshake_on_connect, |
| 1029 | suppress_ragged_eofs=self.suppress_ragged_eofs, |
| 1030 | server_side=True) |
| 1031 | return newsock, addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1032 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1033 | def get_channel_binding(self, cb_type="tls-unique"): |
| 1034 | """Get channel binding data for current connection. Raise ValueError |
| 1035 | if the requested `cb_type` is not supported. Return bytes of the data |
| 1036 | or None if the data is not available (e.g. before the handshake). |
| 1037 | """ |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1038 | if self._sslobj is None: |
| 1039 | return None |
Antoine Pitrou | b1fdf47 | 2014-10-05 20:41:53 +0200 | [diff] [blame] | 1040 | return self._sslobj.get_channel_binding(cb_type) |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 1041 | |
Antoine Pitrou | 47e4042 | 2014-09-04 21:00:10 +0200 | [diff] [blame] | 1042 | def version(self): |
| 1043 | """ |
| 1044 | Return a string identifying the protocol version used by the |
| 1045 | current SSL channel, or None if there is no established channel. |
| 1046 | """ |
| 1047 | if self._sslobj is None: |
| 1048 | return None |
| 1049 | return self._sslobj.version() |
| 1050 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 1051 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1052 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 1053 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1054 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1055 | do_handshake_on_connect=True, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 1056 | suppress_ragged_eofs=True, |
| 1057 | ciphers=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1058 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1059 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1060 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1061 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 1062 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 1063 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 1064 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1065 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1066 | # some utility functions |
| 1067 | |
| 1068 | def cert_time_to_seconds(cert_time): |
Antoine Pitrou | c695c95 | 2014-04-28 20:57:36 +0200 | [diff] [blame] | 1069 | """Return the time in seconds since the Epoch, given the timestring |
| 1070 | representing the "notBefore" or "notAfter" date from a certificate |
| 1071 | in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1072 | |
Antoine Pitrou | c695c95 | 2014-04-28 20:57:36 +0200 | [diff] [blame] | 1073 | "notBefore" or "notAfter" dates must use UTC (RFC 5280). |
| 1074 | |
| 1075 | Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec |
| 1076 | UTC should be specified as GMT (see ASN1_TIME_print()) |
| 1077 | """ |
| 1078 | from time import strptime |
| 1079 | from calendar import timegm |
| 1080 | |
| 1081 | months = ( |
| 1082 | "Jan","Feb","Mar","Apr","May","Jun", |
| 1083 | "Jul","Aug","Sep","Oct","Nov","Dec" |
| 1084 | ) |
| 1085 | time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT |
| 1086 | try: |
| 1087 | month_number = months.index(cert_time[:3].title()) + 1 |
| 1088 | except ValueError: |
| 1089 | raise ValueError('time data %r does not match ' |
| 1090 | 'format "%%b%s"' % (cert_time, time_format)) |
| 1091 | else: |
| 1092 | # found valid month |
| 1093 | tt = strptime(cert_time[3:], time_format) |
| 1094 | # return an integer, the previous mktime()-based implementation |
| 1095 | # returned a float (fractional seconds are always zero here). |
| 1096 | return timegm((tt[0], month_number) + tt[2:6]) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1097 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1098 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 1099 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 1100 | |
| 1101 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1102 | """Takes a certificate in binary DER format and returns the |
| 1103 | PEM version of it as a string.""" |
| 1104 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1105 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 1106 | return (PEM_HEADER + '\n' + |
| 1107 | textwrap.fill(f, 64) + '\n' + |
| 1108 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1109 | |
| 1110 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1111 | """Takes a certificate in ASCII PEM format and returns the |
| 1112 | DER-encoded version of it as a byte sequence""" |
| 1113 | |
| 1114 | if not pem_cert_string.startswith(PEM_HEADER): |
| 1115 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 1116 | % PEM_HEADER) |
| 1117 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 1118 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 1119 | % PEM_FOOTER) |
| 1120 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 1121 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1122 | |
Antoine Pitrou | 94a5b66 | 2014-04-16 18:56:28 +0200 | [diff] [blame] | 1123 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1124 | """Retrieve the certificate from the server at the specified address, |
| 1125 | and return it as a PEM-encoded string. |
| 1126 | If 'ca_certs' is specified, validate the server cert against it. |
| 1127 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 1128 | |
| 1129 | host, port = addr |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 1130 | if ca_certs is not None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1131 | cert_reqs = CERT_REQUIRED |
| 1132 | else: |
| 1133 | cert_reqs = CERT_NONE |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 1134 | context = _create_stdlib_context(ssl_version, |
| 1135 | cert_reqs=cert_reqs, |
| 1136 | cafile=ca_certs) |
| 1137 | with create_connection(addr) as sock: |
| 1138 | with context.wrap_socket(sock) as sslsock: |
| 1139 | dercert = sslsock.getpeercert(True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1140 | return DER_cert_to_PEM_cert(dercert) |
| 1141 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 1142 | def get_protocol_name(protocol_code): |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 1143 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |