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 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 90 | import textwrap |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 91 | import re |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 92 | import sys |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 93 | import os |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 94 | from collections import namedtuple |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 95 | from enum import Enum as _Enum |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 96 | |
| 97 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 98 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 99 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 100 | from _ssl import _SSLContext |
| 101 | from _ssl import ( |
| 102 | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
| 103 | SSLSyscallError, SSLEOFError, |
| 104 | ) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 105 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Christian Heimes | 2258779 | 2013-11-21 23:56:13 +0100 | [diff] [blame] | 106 | from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN, |
| 107 | VERIFY_X509_STRICT) |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 108 | from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 109 | from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 110 | |
| 111 | def _import_symbols(prefix): |
| 112 | for n in dir(_ssl): |
| 113 | if n.startswith(prefix): |
| 114 | globals()[n] = getattr(_ssl, n) |
| 115 | |
| 116 | _import_symbols('OP_') |
| 117 | _import_symbols('ALERT_DESCRIPTION_') |
| 118 | _import_symbols('SSL_ERROR_') |
| 119 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 120 | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 121 | |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 122 | from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 |
Antoine Pitrou | b9ac25d | 2011-07-08 18:47:06 +0200 | [diff] [blame] | 123 | from _ssl import _OPENSSL_API_VERSION |
| 124 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 125 | |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 126 | _PROTOCOL_NAMES = { |
| 127 | PROTOCOL_TLSv1: "TLSv1", |
| 128 | PROTOCOL_SSLv23: "SSLv23", |
| 129 | PROTOCOL_SSLv3: "SSLv3", |
| 130 | } |
| 131 | try: |
| 132 | from _ssl import PROTOCOL_SSLv2 |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 133 | _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 134 | except ImportError: |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 135 | _SSLv2_IF_EXISTS = None |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 136 | else: |
| 137 | _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 138 | |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 139 | try: |
| 140 | from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 141 | except ImportError: |
Antoine Pitrou | 2463e5f | 2013-03-28 22:24:43 +0100 | [diff] [blame] | 142 | pass |
| 143 | else: |
| 144 | _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1" |
| 145 | _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2" |
| 146 | |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 147 | if sys.platform == "win32": |
Christian Heimes | 44109d7 | 2013-11-22 01:51:30 +0100 | [diff] [blame] | 148 | from _ssl import enum_certificates, enum_crls |
Christian Heimes | 46bebee | 2013-06-09 19:03:31 +0200 | [diff] [blame] | 149 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 150 | from socket import getnameinfo as _getnameinfo |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 151 | from socket import SHUT_RDWR as _SHUT_RDWR |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 152 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 153 | import base64 # for DER-to-PEM translation |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 154 | import traceback |
Antoine Pitrou | de8cf32 | 2010-04-26 17:29:05 +0000 | [diff] [blame] | 155 | import errno |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 156 | |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 157 | |
| 158 | socket_error = OSError # keep that public name in module namespace |
| 159 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 160 | if _ssl.HAS_TLS_UNIQUE: |
| 161 | CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 162 | else: |
| 163 | CHANNEL_BINDING_TYPES = [] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 164 | |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 165 | # Disable weak or insecure ciphers by default |
| 166 | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
| 167 | _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2' |
| 168 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 169 | # restricted and more secure ciphers |
| 170 | # HIGH: high encryption cipher suites with key length >= 128 bits (no MD5) |
| 171 | # !aNULL: only authenticated cipher suites (no anonymous DH) |
| 172 | # !RC4: no RC4 streaming cipher, RC4 is broken |
| 173 | # !DSS: RSA is preferred over DSA |
| 174 | _RESTRICTED_CIPHERS = 'HIGH:!aNULL:!RC4:!DSS' |
| 175 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 176 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 177 | class CertificateError(ValueError): |
| 178 | pass |
| 179 | |
| 180 | |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 181 | def _dnsname_match(dn, hostname, max_wildcards=1): |
| 182 | """Matching according to RFC 6125, section 6.4.3 |
| 183 | |
| 184 | http://tools.ietf.org/html/rfc6125#section-6.4.3 |
| 185 | """ |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 186 | pats = [] |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 187 | if not dn: |
| 188 | return False |
| 189 | |
| 190 | leftmost, *remainder = dn.split(r'.') |
| 191 | |
| 192 | wildcards = leftmost.count('*') |
| 193 | if wildcards > max_wildcards: |
| 194 | # Issue #17980: avoid denials of service by refusing more |
| 195 | # than one wildcard per fragment. A survery of established |
| 196 | # policy among SSL implementations showed it to be a |
| 197 | # reasonable choice. |
| 198 | raise CertificateError( |
| 199 | "too many wildcards in certificate DNS name: " + repr(dn)) |
| 200 | |
| 201 | # speed up common case w/o wildcards |
| 202 | if not wildcards: |
| 203 | return dn.lower() == hostname.lower() |
| 204 | |
| 205 | # RFC 6125, section 6.4.3, subitem 1. |
| 206 | # The client SHOULD NOT attempt to match a presented identifier in which |
| 207 | # the wildcard character comprises a label other than the left-most label. |
| 208 | if leftmost == '*': |
| 209 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 210 | # fragment. |
| 211 | pats.append('[^.]+') |
| 212 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
| 213 | # RFC 6125, section 6.4.3, subitem 3. |
| 214 | # The client SHOULD NOT attempt to match a presented identifier |
| 215 | # where the wildcard character is embedded within an A-label or |
| 216 | # U-label of an internationalized domain name. |
| 217 | pats.append(re.escape(leftmost)) |
| 218 | else: |
| 219 | # Otherwise, '*' matches any dotless string, e.g. www* |
| 220 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
| 221 | |
| 222 | # add the remaining fragments, ignore any wildcards |
| 223 | for frag in remainder: |
| 224 | pats.append(re.escape(frag)) |
| 225 | |
| 226 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 227 | return pat.match(hostname) |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 228 | |
| 229 | |
| 230 | def match_hostname(cert, hostname): |
| 231 | """Verify that *cert* (in decoded format as returned by |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 232 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
| 233 | rules are followed, but IP addresses are not accepted for *hostname*. |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 234 | |
| 235 | CertificateError is raised on failure. On success, the function |
| 236 | returns nothing. |
| 237 | """ |
| 238 | if not cert: |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 239 | raise ValueError("empty or no certificate, match_hostname needs a " |
| 240 | "SSL socket or SSL context with either " |
| 241 | "CERT_OPTIONAL or CERT_REQUIRED") |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 242 | dnsnames = [] |
| 243 | san = cert.get('subjectAltName', ()) |
| 244 | for key, value in san: |
| 245 | if key == 'DNS': |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 246 | if _dnsname_match(value, hostname): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 247 | return |
| 248 | dnsnames.append(value) |
Antoine Pitrou | 1c86b44 | 2011-05-06 15:19:49 +0200 | [diff] [blame] | 249 | if not dnsnames: |
| 250 | # The subject is only checked when there is no dNSName entry |
| 251 | # in subjectAltName |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 252 | for sub in cert.get('subject', ()): |
| 253 | for key, value in sub: |
| 254 | # XXX according to RFC 2818, the most specific Common Name |
| 255 | # must be used. |
| 256 | if key == 'commonName': |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 257 | if _dnsname_match(value, hostname): |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 258 | return |
| 259 | dnsnames.append(value) |
| 260 | if len(dnsnames) > 1: |
| 261 | raise CertificateError("hostname %r " |
| 262 | "doesn't match either of %s" |
| 263 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 264 | elif len(dnsnames) == 1: |
| 265 | raise CertificateError("hostname %r " |
| 266 | "doesn't match %r" |
| 267 | % (hostname, dnsnames[0])) |
| 268 | else: |
| 269 | raise CertificateError("no appropriate commonName or " |
| 270 | "subjectAltName fields were found") |
| 271 | |
| 272 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 273 | DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", |
Christian Heimes | 6d7ad13 | 2013-06-09 18:02:55 +0200 | [diff] [blame] | 274 | "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " |
| 275 | "openssl_capath") |
| 276 | |
| 277 | def get_default_verify_paths(): |
| 278 | """Return paths to default cafile and capath. |
| 279 | """ |
| 280 | parts = _ssl.get_default_verify_paths() |
| 281 | |
| 282 | # environment vars shadow paths |
| 283 | cafile = os.environ.get(parts[0], parts[1]) |
| 284 | capath = os.environ.get(parts[2], parts[3]) |
| 285 | |
| 286 | return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, |
| 287 | capath if os.path.isdir(capath) else None, |
| 288 | *parts) |
| 289 | |
| 290 | |
Christian Heimes | a6bc95a | 2013-11-17 19:59:14 +0100 | [diff] [blame] | 291 | class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")): |
| 292 | """ASN.1 object identifier lookup |
| 293 | """ |
| 294 | __slots__ = () |
| 295 | |
| 296 | def __new__(cls, oid): |
| 297 | return super().__new__(cls, *_txt2obj(oid, name=False)) |
| 298 | |
| 299 | @classmethod |
| 300 | def fromnid(cls, nid): |
| 301 | """Create _ASN1Object from OpenSSL numeric ID |
| 302 | """ |
| 303 | return super().__new__(cls, *_nid2obj(nid)) |
| 304 | |
| 305 | @classmethod |
| 306 | def fromname(cls, name): |
| 307 | """Create _ASN1Object from short name, long name or OID |
| 308 | """ |
| 309 | return super().__new__(cls, *_txt2obj(name, name=True)) |
| 310 | |
| 311 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 312 | class Purpose(_ASN1Object, _Enum): |
| 313 | """SSLContext purpose flags with X509v3 Extended Key Usage objects |
| 314 | """ |
| 315 | SERVER_AUTH = '1.3.6.1.5.5.7.3.1' |
| 316 | CLIENT_AUTH = '1.3.6.1.5.5.7.3.2' |
| 317 | |
| 318 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 319 | class SSLContext(_SSLContext): |
| 320 | """An SSLContext holds various SSL-related configuration options and |
| 321 | data, such as certificates and possibly a private key.""" |
| 322 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 323 | __slots__ = ('protocol', '__weakref__') |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 324 | _windows_cert_stores = ("CA", "ROOT") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 325 | |
| 326 | def __new__(cls, protocol, *args, **kwargs): |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 327 | self = _SSLContext.__new__(cls, protocol) |
| 328 | if protocol != _SSLv2_IF_EXISTS: |
| 329 | self.set_ciphers(_DEFAULT_CIPHERS) |
| 330 | return self |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 331 | |
| 332 | def __init__(self, protocol): |
| 333 | self.protocol = protocol |
| 334 | |
| 335 | def wrap_socket(self, sock, server_side=False, |
| 336 | do_handshake_on_connect=True, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 337 | suppress_ragged_eofs=True, |
| 338 | server_hostname=None): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 339 | return SSLSocket(sock=sock, server_side=server_side, |
| 340 | do_handshake_on_connect=do_handshake_on_connect, |
| 341 | suppress_ragged_eofs=suppress_ragged_eofs, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 342 | server_hostname=server_hostname, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 343 | _context=self) |
| 344 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 345 | def set_npn_protocols(self, npn_protocols): |
| 346 | protos = bytearray() |
| 347 | for protocol in npn_protocols: |
| 348 | b = bytes(protocol, 'ascii') |
| 349 | if len(b) == 0 or len(b) > 255: |
| 350 | raise SSLError('NPN protocols must be 1 to 255 in length') |
| 351 | protos.append(len(b)) |
| 352 | protos.extend(b) |
| 353 | |
| 354 | self._set_npn_protocols(protos) |
| 355 | |
Christian Heimes | 72d2850 | 2013-11-23 13:56:58 +0100 | [diff] [blame] | 356 | def _load_windows_store_certs(self, storename, purpose): |
| 357 | certs = bytearray() |
| 358 | for cert, encoding, trust in enum_certificates(storename): |
| 359 | # CA certs are never PKCS#7 encoded |
| 360 | if encoding == "x509_asn": |
| 361 | if trust is True or purpose.oid in trust: |
| 362 | certs.extend(cert) |
| 363 | self.load_verify_locations(cadata=certs) |
| 364 | return certs |
| 365 | |
| 366 | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
| 367 | if not isinstance(purpose, _ASN1Object): |
| 368 | raise TypeError(purpose) |
| 369 | if sys.platform == "win32": |
| 370 | for storename in self._windows_cert_stores: |
| 371 | self._load_windows_store_certs(storename, purpose) |
| 372 | else: |
| 373 | self.set_default_verify_paths() |
| 374 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 375 | |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 376 | def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, |
| 377 | capath=None, cadata=None): |
| 378 | """Create a SSLContext object with default settings. |
| 379 | |
| 380 | NOTE: The protocol and settings may change anytime without prior |
| 381 | deprecation. The values represent a fair balance between maximum |
| 382 | compatibility and security. |
| 383 | """ |
| 384 | if not isinstance(purpose, _ASN1Object): |
| 385 | raise TypeError(purpose) |
| 386 | context = SSLContext(PROTOCOL_TLSv1) |
| 387 | # SSLv2 considered harmful. |
| 388 | context.options |= OP_NO_SSLv2 |
Christian Heimes | dec813f | 2013-11-28 08:06:54 +0100 | [diff] [blame] | 389 | # disable compression to prevent CRIME attacks (OpenSSL 1.0+) |
| 390 | context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0) |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 391 | # disallow ciphers with known vulnerabilities |
| 392 | context.set_ciphers(_RESTRICTED_CIPHERS) |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 393 | # verify certs and host name in client mode |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 394 | if purpose == Purpose.SERVER_AUTH: |
| 395 | context.verify_mode = CERT_REQUIRED |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 396 | context.check_hostname = True |
Christian Heimes | 4c05b47 | 2013-11-23 15:58:30 +0100 | [diff] [blame] | 397 | if cafile or capath or cadata: |
| 398 | context.load_verify_locations(cafile, capath, cadata) |
| 399 | elif context.verify_mode != CERT_NONE: |
| 400 | # no explicit cafile, capath or cadata but the verify mode is |
| 401 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 402 | # root CA certificates for the given purpose. This may fail silently. |
| 403 | context.load_default_certs(purpose) |
| 404 | return context |
| 405 | |
| 406 | |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 407 | def _create_stdlib_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None, |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 408 | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 409 | certfile=None, keyfile=None, |
| 410 | cafile=None, capath=None, cadata=None): |
| 411 | """Create a SSLContext object for Python stdlib modules |
| 412 | |
| 413 | All Python stdlib modules shall use this function to create SSLContext |
| 414 | objects in order to keep common settings in one place. The configuration |
| 415 | is less restrict than create_default_context()'s to increase backward |
| 416 | compatibility. |
| 417 | """ |
| 418 | if not isinstance(purpose, _ASN1Object): |
| 419 | raise TypeError(purpose) |
| 420 | |
| 421 | context = SSLContext(protocol) |
| 422 | # SSLv2 considered harmful. |
| 423 | context.options |= OP_NO_SSLv2 |
| 424 | |
| 425 | if cert_reqs is not None: |
| 426 | context.verify_mode = cert_reqs |
Christian Heimes | a02c69a | 2013-12-02 20:59:28 +0100 | [diff] [blame] | 427 | context.check_hostname = check_hostname |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 428 | |
| 429 | if keyfile and not certfile: |
| 430 | raise ValueError("certfile must be specified") |
| 431 | if certfile or keyfile: |
| 432 | context.load_cert_chain(certfile, keyfile) |
| 433 | |
| 434 | # load CA root certs |
| 435 | if cafile or capath or cadata: |
| 436 | context.load_verify_locations(cafile, capath, cadata) |
| 437 | elif context.verify_mode != CERT_NONE: |
| 438 | # no explicit cafile, capath or cadata but the verify mode is |
| 439 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 440 | # root CA certificates for the given purpose. This may fail silently. |
| 441 | context.load_default_certs(purpose) |
| 442 | |
| 443 | return context |
| 444 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 445 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 446 | """This class implements a subtype of socket.socket that wraps |
| 447 | the underlying OS socket in an SSL context when necessary, and |
| 448 | provides read and write methods over that channel.""" |
| 449 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 450 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 451 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 452 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 453 | do_handshake_on_connect=True, |
| 454 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 455 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 456 | server_hostname=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 457 | _context=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 458 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 459 | if _context: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 460 | self._context = _context |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 461 | else: |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 462 | if server_side and not certfile: |
| 463 | raise ValueError("certfile must be specified for server-side " |
| 464 | "operations") |
Giampaolo RodolĂ | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 465 | if keyfile and not certfile: |
| 466 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 467 | if certfile and not keyfile: |
| 468 | keyfile = certfile |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 469 | self._context = SSLContext(ssl_version) |
| 470 | self._context.verify_mode = cert_reqs |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 471 | if ca_certs: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 472 | self._context.load_verify_locations(ca_certs) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 473 | if certfile: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 474 | self._context.load_cert_chain(certfile, keyfile) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 475 | if npn_protocols: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 476 | self._context.set_npn_protocols(npn_protocols) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 477 | if ciphers: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 478 | self._context.set_ciphers(ciphers) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 479 | self.keyfile = keyfile |
| 480 | self.certfile = certfile |
| 481 | self.cert_reqs = cert_reqs |
| 482 | self.ssl_version = ssl_version |
| 483 | self.ca_certs = ca_certs |
| 484 | self.ciphers = ciphers |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 485 | if server_side and server_hostname: |
| 486 | raise ValueError("server_hostname can only be specified " |
| 487 | "in client mode") |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 488 | if self._context.check_hostname and not server_hostname: |
| 489 | if HAS_SNI: |
| 490 | raise ValueError("check_hostname requires server_hostname") |
| 491 | else: |
| 492 | raise ValueError("check_hostname requires server_hostname, " |
| 493 | "but it's not supported by your OpenSSL " |
| 494 | "library") |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 495 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 496 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 497 | self.do_handshake_on_connect = do_handshake_on_connect |
| 498 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 499 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 500 | socket.__init__(self, |
| 501 | family=sock.family, |
| 502 | type=sock.type, |
| 503 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 504 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 505 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 506 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 507 | elif fileno is not None: |
| 508 | socket.__init__(self, fileno=fileno) |
| 509 | else: |
| 510 | socket.__init__(self, family=family, type=type, proto=proto) |
| 511 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 512 | # See if we are connected |
| 513 | try: |
| 514 | self.getpeername() |
| 515 | except OSError as e: |
| 516 | if e.errno != errno.ENOTCONN: |
| 517 | raise |
| 518 | connected = False |
| 519 | else: |
| 520 | connected = True |
| 521 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 522 | self._closed = False |
| 523 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 524 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 525 | if connected: |
| 526 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 527 | try: |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 528 | self._sslobj = self._context._wrap_socket(self, server_side, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 529 | server_hostname) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 530 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 531 | timeout = self.gettimeout() |
| 532 | if timeout == 0.0: |
| 533 | # non-blocking |
| 534 | 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] | 535 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 536 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 537 | except (OSError, ValueError): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 538 | self.close() |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 539 | raise |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 540 | |
Antoine Pitrou | 58ddc9d | 2013-01-05 21:20:29 +0100 | [diff] [blame] | 541 | @property |
| 542 | def context(self): |
| 543 | return self._context |
| 544 | |
| 545 | @context.setter |
| 546 | def context(self, ctx): |
| 547 | self._context = ctx |
| 548 | self._sslobj.context = ctx |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 549 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 550 | def dup(self): |
| 551 | raise NotImplemented("Can't dup() %s instances" % |
| 552 | self.__class__.__name__) |
| 553 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 554 | def _checkClosed(self, msg=None): |
| 555 | # raise an exception here if you wish to check for spurious closes |
| 556 | pass |
| 557 | |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 558 | def _check_connected(self): |
| 559 | if not self._connected: |
| 560 | # getpeername() will raise ENOTCONN if the socket is really |
| 561 | # not connected; note that we can be connected even without |
| 562 | # _connected being set, e.g. if connect() first returned |
| 563 | # EAGAIN. |
| 564 | self.getpeername() |
| 565 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 566 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 567 | """Read up to LEN bytes and return them. |
| 568 | Return zero-length string on EOF.""" |
| 569 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 570 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 571 | if not self._sslobj: |
| 572 | raise ValueError("Read on closed or unwrapped SSL socket.") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 573 | try: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 574 | if buffer is not None: |
| 575 | v = self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 576 | else: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 577 | v = self._sslobj.read(len or 1024) |
| 578 | return v |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 579 | except SSLError as x: |
| 580 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 581 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 582 | return 0 |
| 583 | else: |
| 584 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 585 | else: |
| 586 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 587 | |
| 588 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 589 | """Write DATA to the underlying SSL channel. Returns |
| 590 | number of bytes of DATA actually transmitted.""" |
| 591 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 592 | self._checkClosed() |
Antoine Pitrou | 60a26e0 | 2013-07-20 19:35:16 +0200 | [diff] [blame] | 593 | if not self._sslobj: |
| 594 | raise ValueError("Write on closed or unwrapped SSL socket.") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 595 | return self._sslobj.write(data) |
| 596 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 597 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 598 | """Returns a formatted version of the data in the |
| 599 | certificate provided by the other end of the SSL channel. |
| 600 | Return None if no certificate was provided, {} if a |
| 601 | certificate was provided, but not validated.""" |
| 602 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 603 | self._checkClosed() |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 604 | self._check_connected() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 605 | return self._sslobj.peer_certificate(binary_form) |
| 606 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 607 | def selected_npn_protocol(self): |
| 608 | self._checkClosed() |
| 609 | if not self._sslobj or not _ssl.HAS_NPN: |
| 610 | return None |
| 611 | else: |
| 612 | return self._sslobj.selected_npn_protocol() |
| 613 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 614 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 615 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 616 | if not self._sslobj: |
| 617 | return None |
| 618 | else: |
| 619 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 620 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 621 | def compression(self): |
| 622 | self._checkClosed() |
| 623 | if not self._sslobj: |
| 624 | return None |
| 625 | else: |
| 626 | return self._sslobj.compression() |
| 627 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 628 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 629 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 630 | if self._sslobj: |
| 631 | if flags != 0: |
| 632 | raise ValueError( |
| 633 | "non-zero flags not allowed in calls to send() on %s" % |
| 634 | self.__class__) |
Giampaolo Rodola' | 06d0c1e | 2013-04-03 12:01:44 +0200 | [diff] [blame] | 635 | try: |
| 636 | v = self._sslobj.write(data) |
| 637 | except SSLError as x: |
| 638 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 639 | return 0 |
| 640 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 641 | return 0 |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 642 | else: |
Giampaolo Rodola' | 06d0c1e | 2013-04-03 12:01:44 +0200 | [diff] [blame] | 643 | raise |
| 644 | else: |
| 645 | return v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 646 | else: |
| 647 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 648 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 649 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 650 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 651 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 652 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 653 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 654 | elif addr is None: |
| 655 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 656 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 657 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 658 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 659 | def sendmsg(self, *args, **kwargs): |
| 660 | # Ensure programs don't send data unencrypted if they try to |
| 661 | # use this method. |
| 662 | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
| 663 | self.__class__) |
| 664 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 665 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 666 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 667 | if self._sslobj: |
Giampaolo RodolĂ | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 668 | if flags != 0: |
| 669 | raise ValueError( |
| 670 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 671 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 672 | amount = len(data) |
| 673 | count = 0 |
| 674 | while (count < amount): |
| 675 | v = self.send(data[count:]) |
| 676 | count += v |
| 677 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 678 | else: |
| 679 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 680 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 681 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 682 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 683 | if self._sslobj: |
| 684 | if flags != 0: |
| 685 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 686 | "non-zero flags not allowed in calls to recv() on %s" % |
| 687 | self.__class__) |
| 688 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 689 | else: |
| 690 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 691 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 692 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 693 | self._checkClosed() |
| 694 | if buffer and (nbytes is None): |
| 695 | nbytes = len(buffer) |
| 696 | elif nbytes is None: |
| 697 | nbytes = 1024 |
| 698 | if self._sslobj: |
| 699 | if flags != 0: |
| 700 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 701 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 702 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 703 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 704 | else: |
| 705 | return socket.recv_into(self, buffer, nbytes, flags) |
| 706 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 707 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 708 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 709 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 710 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 711 | self.__class__) |
| 712 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 713 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 714 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 715 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 716 | self._checkClosed() |
| 717 | if self._sslobj: |
| 718 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 719 | self.__class__) |
| 720 | else: |
| 721 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 722 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 723 | def recvmsg(self, *args, **kwargs): |
| 724 | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
| 725 | self.__class__) |
| 726 | |
| 727 | def recvmsg_into(self, *args, **kwargs): |
| 728 | raise NotImplementedError("recvmsg_into not allowed on instances of " |
| 729 | "%s" % self.__class__) |
| 730 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 731 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 732 | self._checkClosed() |
| 733 | if self._sslobj: |
| 734 | return self._sslobj.pending() |
| 735 | else: |
| 736 | return 0 |
| 737 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 738 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 739 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 740 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 741 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 742 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 743 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 744 | if self._sslobj: |
| 745 | s = self._sslobj.shutdown() |
| 746 | self._sslobj = None |
| 747 | return s |
| 748 | else: |
| 749 | raise ValueError("No SSL wrapper around " + str(self)) |
| 750 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 751 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 752 | self._sslobj = None |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 753 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 754 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 755 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 756 | """Perform a TLS/SSL handshake.""" |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 757 | self._check_connected() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 758 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 759 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 760 | if timeout == 0.0 and block: |
| 761 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 762 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 763 | finally: |
| 764 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 765 | |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 766 | if self.context.check_hostname: |
| 767 | try: |
| 768 | if not self.server_hostname: |
| 769 | raise ValueError("check_hostname needs server_hostname " |
| 770 | "argument") |
| 771 | match_hostname(self.getpeercert(), self.server_hostname) |
| 772 | except Exception: |
| 773 | self.shutdown(_SHUT_RDWR) |
| 774 | self.close() |
| 775 | raise |
| 776 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 777 | def _real_connect(self, addr, connect_ex): |
Giampaolo RodolĂ | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 778 | if self.server_side: |
| 779 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 780 | # Here we assume that the socket is client-side, and not |
| 781 | # 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] | 782 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 783 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 784 | self._sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 785 | try: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 786 | if connect_ex: |
| 787 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 788 | else: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 789 | rc = None |
| 790 | socket.connect(self, addr) |
| 791 | if not rc: |
Antoine Pitrou | 242db72 | 2013-05-01 20:52:07 +0200 | [diff] [blame] | 792 | self._connected = True |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 793 | if self.do_handshake_on_connect: |
| 794 | self.do_handshake() |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 795 | return rc |
Christian Heimes | 1aa9a75 | 2013-12-02 02:41:19 +0100 | [diff] [blame] | 796 | except (OSError, ValueError): |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 797 | self._sslobj = None |
| 798 | raise |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 799 | |
| 800 | def connect(self, addr): |
| 801 | """Connects to remote ADDR, and then wraps the connection in |
| 802 | an SSL channel.""" |
| 803 | self._real_connect(addr, False) |
| 804 | |
| 805 | def connect_ex(self, addr): |
| 806 | """Connects to remote ADDR, and then wraps the connection in |
| 807 | an SSL channel.""" |
| 808 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 809 | |
| 810 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 811 | """Accepts a new connection from a remote client, and returns |
| 812 | a tuple containing that new connection wrapped with a server-side |
| 813 | SSL channel, and the address of the remote client.""" |
| 814 | |
| 815 | newsock, addr = socket.accept(self) |
Antoine Pitrou | 5c89b4e | 2012-11-11 01:25:36 +0100 | [diff] [blame] | 816 | newsock = self.context.wrap_socket(newsock, |
| 817 | do_handshake_on_connect=self.do_handshake_on_connect, |
| 818 | suppress_ragged_eofs=self.suppress_ragged_eofs, |
| 819 | server_side=True) |
| 820 | return newsock, addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 821 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 822 | def get_channel_binding(self, cb_type="tls-unique"): |
| 823 | """Get channel binding data for current connection. Raise ValueError |
| 824 | if the requested `cb_type` is not supported. Return bytes of the data |
| 825 | or None if the data is not available (e.g. before the handshake). |
| 826 | """ |
| 827 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 828 | raise ValueError("Unsupported channel binding type") |
| 829 | if cb_type != "tls-unique": |
| 830 | raise NotImplementedError( |
| 831 | "{0} channel binding type not implemented" |
| 832 | .format(cb_type)) |
| 833 | if self._sslobj is None: |
| 834 | return None |
| 835 | return self._sslobj.tls_unique_cb() |
| 836 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 837 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 838 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 839 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 840 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 841 | do_handshake_on_connect=True, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 842 | suppress_ragged_eofs=True, |
| 843 | ciphers=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 844 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 845 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 846 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 847 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 848 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 849 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 850 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 851 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 852 | # some utility functions |
| 853 | |
| 854 | def cert_time_to_seconds(cert_time): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 855 | """Takes a date-time string in standard ASN1_print form |
| 856 | ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return |
| 857 | a Python time value in seconds past the epoch.""" |
| 858 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 859 | import time |
| 860 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 861 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 862 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 863 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 864 | |
| 865 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 866 | """Takes a certificate in binary DER format and returns the |
| 867 | PEM version of it as a string.""" |
| 868 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 869 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 870 | return (PEM_HEADER + '\n' + |
| 871 | textwrap.fill(f, 64) + '\n' + |
| 872 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 873 | |
| 874 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 875 | """Takes a certificate in ASCII PEM format and returns the |
| 876 | DER-encoded version of it as a byte sequence""" |
| 877 | |
| 878 | if not pem_cert_string.startswith(PEM_HEADER): |
| 879 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 880 | % PEM_HEADER) |
| 881 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 882 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 883 | % PEM_FOOTER) |
| 884 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 885 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 886 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 887 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 888 | """Retrieve the certificate from the server at the specified address, |
| 889 | and return it as a PEM-encoded string. |
| 890 | If 'ca_certs' is specified, validate the server cert against it. |
| 891 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 892 | |
| 893 | host, port = addr |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 894 | if ca_certs is not None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 895 | cert_reqs = CERT_REQUIRED |
| 896 | else: |
| 897 | cert_reqs = CERT_NONE |
Christian Heimes | 67986f9 | 2013-11-23 22:43:47 +0100 | [diff] [blame] | 898 | context = _create_stdlib_context(ssl_version, |
| 899 | cert_reqs=cert_reqs, |
| 900 | cafile=ca_certs) |
| 901 | with create_connection(addr) as sock: |
| 902 | with context.wrap_socket(sock) as sslsock: |
| 903 | dercert = sslsock.getpeercert(True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 904 | return DER_cert_to_PEM_cert(dercert) |
| 905 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 906 | def get_protocol_name(protocol_code): |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 907 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |