Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 1 | # Wrapper module for _ssl, providing some additional facilities |
| 2 | # implemented in Python. Written by Bill Janssen. |
| 3 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 4 | """This module provides some more Pythonic support for SSL. |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 5 | |
| 6 | Object types: |
| 7 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 8 | SSLSocket -- subtype of socket.socket which does SSL over the socket |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 9 | |
| 10 | Exceptions: |
| 11 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 12 | SSLError -- exception raised for I/O errors |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +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 |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 55 | PROTOCOL_TLSv1_1 |
| 56 | PROTOCOL_TLSv1_2 |
| 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 |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 88 | """ |
| 89 | |
Christian Heimes | c5f05e4 | 2008-02-23 17:40:11 +0000 | [diff] [blame] | 90 | import textwrap |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 91 | import re |
| 92 | import sys |
| 93 | import os |
| 94 | from collections import namedtuple |
| 95 | from contextlib import closing |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 96 | |
| 97 | import _ssl # if we can't import it, let the error propagate |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 98 | |
Antoine Pitrou | f9de534 | 2010-04-05 21:35:07 +0000 | [diff] [blame] | 99 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 100 | from _ssl import _SSLContext |
| 101 | from _ssl import ( |
| 102 | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
| 103 | SSLSyscallError, SSLEOFError, |
| 104 | ) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 105 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 106 | from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN, |
| 107 | VERIFY_X509_STRICT) |
| 108 | from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 109 | from _ssl import RAND_status, RAND_egd, RAND_add |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [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 | _import_symbols('PROTOCOL_') |
| 120 | |
| 121 | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN |
| 122 | |
| 123 | from _ssl import _OPENSSL_API_VERSION |
| 124 | |
| 125 | _PROTOCOL_NAMES = {value: name for name, value in globals().items() if name.startswith('PROTOCOL_')} |
| 126 | |
Victor Stinner | b1241f9 | 2011-05-10 01:52:03 +0200 | [diff] [blame] | 127 | try: |
Antoine Pitrou | d76088d | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 128 | _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 129 | except NameError: |
Antoine Pitrou | d76088d | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 130 | _SSLv2_IF_EXISTS = None |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 131 | |
Antoine Pitrou | dfb299b | 2010-04-23 22:54:59 +0000 | [diff] [blame] | 132 | from socket import socket, _fileobject, _delegate_methods, error as socket_error |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 133 | if sys.platform == "win32": |
| 134 | from _ssl import enum_certificates, enum_crls |
| 135 | |
| 136 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
| 137 | from socket import SOL_SOCKET, SO_TYPE |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 138 | import base64 # for DER-to-PEM translation |
Antoine Pitrou | 278d665 | 2010-04-26 17:23:33 +0000 | [diff] [blame] | 139 | import errno |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 140 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 141 | if _ssl.HAS_TLS_UNIQUE: |
| 142 | CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 143 | else: |
| 144 | CHANNEL_BINDING_TYPES = [] |
| 145 | |
Antoine Pitrou | d76088d | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 146 | # Disable weak or insecure ciphers by default |
| 147 | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 148 | # Enable a better set of ciphers by default |
| 149 | # This list has been explicitly chosen to: |
| 150 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 151 | # * Prefer ECDHE over DHE for better performance |
| 152 | # * Prefer any AES-GCM over any AES-CBC for better performance and security |
| 153 | # * Then Use HIGH cipher suites as a fallback |
| 154 | # * Then Use 3DES as fallback which is secure but slow |
| 155 | # * Finally use RC4 as a fallback which is problematic but needed for |
| 156 | # compatibility some times. |
| 157 | # * Disable NULL authentication, NULL encryption, and MD5 MACs for security |
| 158 | # reasons |
| 159 | _DEFAULT_CIPHERS = ( |
| 160 | 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' |
| 161 | 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:' |
| 162 | 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5' |
| 163 | ) |
Antoine Pitrou | d76088d | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 164 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 165 | # Restricted and more secure ciphers for the server side |
| 166 | # This list has been explicitly chosen to: |
| 167 | # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) |
| 168 | # * Prefer ECDHE over DHE for better performance |
| 169 | # * Prefer any AES-GCM over any AES-CBC for better performance and security |
| 170 | # * Then Use HIGH cipher suites as a fallback |
| 171 | # * Then Use 3DES as fallback which is secure but slow |
| 172 | # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for |
| 173 | # security reasons |
| 174 | _RESTRICTED_SERVER_CIPHERS = ( |
| 175 | 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' |
| 176 | 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' |
| 177 | '!eNULL:!MD5:!DSS:!RC4' |
| 178 | ) |
| 179 | |
| 180 | |
| 181 | class CertificateError(ValueError): |
| 182 | pass |
| 183 | |
| 184 | |
| 185 | def _dnsname_match(dn, hostname, max_wildcards=1): |
| 186 | """Matching according to RFC 6125, section 6.4.3 |
| 187 | |
| 188 | http://tools.ietf.org/html/rfc6125#section-6.4.3 |
| 189 | """ |
| 190 | pats = [] |
| 191 | if not dn: |
| 192 | return False |
| 193 | |
| 194 | pieces = dn.split(r'.') |
| 195 | leftmost = pieces[0] |
| 196 | remainder = pieces[1:] |
| 197 | |
| 198 | wildcards = leftmost.count('*') |
| 199 | if wildcards > max_wildcards: |
| 200 | # Issue #17980: avoid denials of service by refusing more |
| 201 | # than one wildcard per fragment. A survery of established |
| 202 | # policy among SSL implementations showed it to be a |
| 203 | # reasonable choice. |
| 204 | raise CertificateError( |
| 205 | "too many wildcards in certificate DNS name: " + repr(dn)) |
| 206 | |
| 207 | # speed up common case w/o wildcards |
| 208 | if not wildcards: |
| 209 | return dn.lower() == hostname.lower() |
| 210 | |
| 211 | # RFC 6125, section 6.4.3, subitem 1. |
| 212 | # The client SHOULD NOT attempt to match a presented identifier in which |
| 213 | # the wildcard character comprises a label other than the left-most label. |
| 214 | if leftmost == '*': |
| 215 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 216 | # fragment. |
| 217 | pats.append('[^.]+') |
| 218 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
| 219 | # RFC 6125, section 6.4.3, subitem 3. |
| 220 | # The client SHOULD NOT attempt to match a presented identifier |
| 221 | # where the wildcard character is embedded within an A-label or |
| 222 | # U-label of an internationalized domain name. |
| 223 | pats.append(re.escape(leftmost)) |
| 224 | else: |
| 225 | # Otherwise, '*' matches any dotless string, e.g. www* |
| 226 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
| 227 | |
| 228 | # add the remaining fragments, ignore any wildcards |
| 229 | for frag in remainder: |
| 230 | pats.append(re.escape(frag)) |
| 231 | |
| 232 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 233 | return pat.match(hostname) |
| 234 | |
| 235 | |
| 236 | def match_hostname(cert, hostname): |
| 237 | """Verify that *cert* (in decoded format as returned by |
| 238 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
| 239 | rules are followed, but IP addresses are not accepted for *hostname*. |
| 240 | |
| 241 | CertificateError is raised on failure. On success, the function |
| 242 | returns nothing. |
| 243 | """ |
| 244 | if not cert: |
| 245 | raise ValueError("empty or no certificate, match_hostname needs a " |
| 246 | "SSL socket or SSL context with either " |
| 247 | "CERT_OPTIONAL or CERT_REQUIRED") |
| 248 | dnsnames = [] |
| 249 | san = cert.get('subjectAltName', ()) |
| 250 | for key, value in san: |
| 251 | if key == 'DNS': |
| 252 | if _dnsname_match(value, hostname): |
| 253 | return |
| 254 | dnsnames.append(value) |
| 255 | if not dnsnames: |
| 256 | # The subject is only checked when there is no dNSName entry |
| 257 | # in subjectAltName |
| 258 | for sub in cert.get('subject', ()): |
| 259 | for key, value in sub: |
| 260 | # XXX according to RFC 2818, the most specific Common Name |
| 261 | # must be used. |
| 262 | if key == 'commonName': |
| 263 | if _dnsname_match(value, hostname): |
| 264 | return |
| 265 | dnsnames.append(value) |
| 266 | if len(dnsnames) > 1: |
| 267 | raise CertificateError("hostname %r " |
| 268 | "doesn't match either of %s" |
| 269 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 270 | elif len(dnsnames) == 1: |
| 271 | raise CertificateError("hostname %r " |
| 272 | "doesn't match %r" |
| 273 | % (hostname, dnsnames[0])) |
| 274 | else: |
| 275 | raise CertificateError("no appropriate commonName or " |
| 276 | "subjectAltName fields were found") |
| 277 | |
| 278 | |
| 279 | DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", |
| 280 | "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " |
| 281 | "openssl_capath") |
| 282 | |
| 283 | def get_default_verify_paths(): |
| 284 | """Return paths to default cafile and capath. |
| 285 | """ |
| 286 | parts = _ssl.get_default_verify_paths() |
| 287 | |
| 288 | # environment vars shadow paths |
| 289 | cafile = os.environ.get(parts[0], parts[1]) |
| 290 | capath = os.environ.get(parts[2], parts[3]) |
| 291 | |
| 292 | return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, |
| 293 | capath if os.path.isdir(capath) else None, |
| 294 | *parts) |
| 295 | |
| 296 | |
| 297 | class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")): |
| 298 | """ASN.1 object identifier lookup |
| 299 | """ |
| 300 | __slots__ = () |
| 301 | |
| 302 | def __new__(cls, oid): |
| 303 | return super(_ASN1Object, cls).__new__(cls, *_txt2obj(oid, name=False)) |
| 304 | |
| 305 | @classmethod |
| 306 | def fromnid(cls, nid): |
| 307 | """Create _ASN1Object from OpenSSL numeric ID |
| 308 | """ |
| 309 | return super(_ASN1Object, cls).__new__(cls, *_nid2obj(nid)) |
| 310 | |
| 311 | @classmethod |
| 312 | def fromname(cls, name): |
| 313 | """Create _ASN1Object from short name, long name or OID |
| 314 | """ |
| 315 | return super(_ASN1Object, cls).__new__(cls, *_txt2obj(name, name=True)) |
| 316 | |
| 317 | |
| 318 | class Purpose(_ASN1Object): |
| 319 | """SSLContext purpose flags with X509v3 Extended Key Usage objects |
| 320 | """ |
| 321 | |
| 322 | Purpose.SERVER_AUTH = Purpose('1.3.6.1.5.5.7.3.1') |
| 323 | Purpose.CLIENT_AUTH = Purpose('1.3.6.1.5.5.7.3.2') |
| 324 | |
| 325 | |
| 326 | class SSLContext(_SSLContext): |
| 327 | """An SSLContext holds various SSL-related configuration options and |
| 328 | data, such as certificates and possibly a private key.""" |
| 329 | |
| 330 | __slots__ = ('protocol', '__weakref__') |
| 331 | _windows_cert_stores = ("CA", "ROOT") |
| 332 | |
| 333 | def __new__(cls, protocol, *args, **kwargs): |
| 334 | self = _SSLContext.__new__(cls, protocol) |
| 335 | if protocol != _SSLv2_IF_EXISTS: |
| 336 | self.set_ciphers(_DEFAULT_CIPHERS) |
| 337 | return self |
| 338 | |
| 339 | def __init__(self, protocol): |
| 340 | self.protocol = protocol |
| 341 | |
| 342 | def wrap_socket(self, sock, server_side=False, |
| 343 | do_handshake_on_connect=True, |
| 344 | suppress_ragged_eofs=True, |
| 345 | server_hostname=None): |
| 346 | return SSLSocket(sock=sock, server_side=server_side, |
| 347 | do_handshake_on_connect=do_handshake_on_connect, |
| 348 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 349 | server_hostname=server_hostname, |
| 350 | _context=self) |
| 351 | |
| 352 | def set_npn_protocols(self, npn_protocols): |
| 353 | protos = bytearray() |
| 354 | for protocol in npn_protocols: |
| 355 | b = protocol.encode('ascii') |
| 356 | if len(b) == 0 or len(b) > 255: |
| 357 | raise SSLError('NPN protocols must be 1 to 255 in length') |
| 358 | protos.append(len(b)) |
| 359 | protos.extend(b) |
| 360 | |
| 361 | self._set_npn_protocols(protos) |
| 362 | |
| 363 | def _load_windows_store_certs(self, storename, purpose): |
| 364 | certs = bytearray() |
| 365 | for cert, encoding, trust in enum_certificates(storename): |
| 366 | # CA certs are never PKCS#7 encoded |
| 367 | if encoding == "x509_asn": |
| 368 | if trust is True or purpose.oid in trust: |
| 369 | certs.extend(cert) |
| 370 | self.load_verify_locations(cadata=certs) |
| 371 | return certs |
| 372 | |
| 373 | def load_default_certs(self, purpose=Purpose.SERVER_AUTH): |
| 374 | if not isinstance(purpose, _ASN1Object): |
| 375 | raise TypeError(purpose) |
| 376 | if sys.platform == "win32": |
| 377 | for storename in self._windows_cert_stores: |
| 378 | self._load_windows_store_certs(storename, purpose) |
Benjamin Peterson | 0b30a2b | 2014-10-03 17:27:05 -0400 | [diff] [blame] | 379 | self.set_default_verify_paths() |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 380 | |
| 381 | |
| 382 | def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, |
| 383 | capath=None, cadata=None): |
| 384 | """Create a SSLContext object with default settings. |
| 385 | |
| 386 | NOTE: The protocol and settings may change anytime without prior |
| 387 | deprecation. The values represent a fair balance between maximum |
| 388 | compatibility and security. |
| 389 | """ |
| 390 | if not isinstance(purpose, _ASN1Object): |
| 391 | raise TypeError(purpose) |
| 392 | |
| 393 | context = SSLContext(PROTOCOL_SSLv23) |
| 394 | |
| 395 | # SSLv2 considered harmful. |
| 396 | context.options |= OP_NO_SSLv2 |
| 397 | |
| 398 | # SSLv3 has problematic security and is only required for really old |
| 399 | # clients such as IE6 on Windows XP |
| 400 | context.options |= OP_NO_SSLv3 |
| 401 | |
| 402 | # disable compression to prevent CRIME attacks (OpenSSL 1.0+) |
| 403 | context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0) |
| 404 | |
| 405 | if purpose == Purpose.SERVER_AUTH: |
| 406 | # verify certs and host name in client mode |
| 407 | context.verify_mode = CERT_REQUIRED |
| 408 | context.check_hostname = True |
| 409 | elif purpose == Purpose.CLIENT_AUTH: |
| 410 | # Prefer the server's ciphers by default so that we get stronger |
| 411 | # encryption |
| 412 | context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) |
| 413 | |
| 414 | # Use single use keys in order to improve forward secrecy |
| 415 | context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0) |
| 416 | context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0) |
| 417 | |
| 418 | # disallow ciphers with known vulnerabilities |
| 419 | context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) |
| 420 | |
| 421 | if cafile or capath or cadata: |
| 422 | context.load_verify_locations(cafile, capath, cadata) |
| 423 | elif context.verify_mode != CERT_NONE: |
| 424 | # no explicit cafile, capath or cadata but the verify mode is |
| 425 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 426 | # root CA certificates for the given purpose. This may fail silently. |
| 427 | context.load_default_certs(purpose) |
| 428 | return context |
| 429 | |
Benjamin Peterson | e3e7d40 | 2014-11-23 21:02:02 -0600 | [diff] [blame] | 430 | def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 431 | check_hostname=False, purpose=Purpose.SERVER_AUTH, |
| 432 | certfile=None, keyfile=None, |
| 433 | cafile=None, capath=None, cadata=None): |
| 434 | """Create a SSLContext object for Python stdlib modules |
| 435 | |
| 436 | All Python stdlib modules shall use this function to create SSLContext |
| 437 | objects in order to keep common settings in one place. The configuration |
| 438 | is less restrict than create_default_context()'s to increase backward |
| 439 | compatibility. |
| 440 | """ |
| 441 | if not isinstance(purpose, _ASN1Object): |
| 442 | raise TypeError(purpose) |
| 443 | |
| 444 | context = SSLContext(protocol) |
| 445 | # SSLv2 considered harmful. |
| 446 | context.options |= OP_NO_SSLv2 |
Antoine Pitrou | 95b6164 | 2014-10-17 19:28:30 +0200 | [diff] [blame] | 447 | # SSLv3 has problematic security and is only required for really old |
| 448 | # clients such as IE6 on Windows XP |
| 449 | context.options |= OP_NO_SSLv3 |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 450 | |
| 451 | if cert_reqs is not None: |
| 452 | context.verify_mode = cert_reqs |
| 453 | context.check_hostname = check_hostname |
| 454 | |
| 455 | if keyfile and not certfile: |
| 456 | raise ValueError("certfile must be specified") |
| 457 | if certfile or keyfile: |
| 458 | context.load_cert_chain(certfile, keyfile) |
| 459 | |
| 460 | # load CA root certs |
| 461 | if cafile or capath or cadata: |
| 462 | context.load_verify_locations(cafile, capath, cadata) |
| 463 | elif context.verify_mode != CERT_NONE: |
| 464 | # no explicit cafile, capath or cadata but the verify mode is |
| 465 | # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system |
| 466 | # root CA certificates for the given purpose. This may fail silently. |
| 467 | context.load_default_certs(purpose) |
| 468 | |
| 469 | return context |
Antoine Pitrou | d76088d | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 470 | |
Benjamin Peterson | e3e7d40 | 2014-11-23 21:02:02 -0600 | [diff] [blame] | 471 | # Used by http.client if no context is explicitly passed. |
| 472 | _create_default_https_context = create_default_context |
| 473 | |
| 474 | |
| 475 | # Backwards compatibility alias, even though it's not a public name. |
| 476 | _create_stdlib_context = _create_unverified_context |
| 477 | |
| 478 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 479 | class SSLSocket(socket): |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 480 | """This class implements a subtype of socket.socket that wraps |
| 481 | the underlying OS socket in an SSL context when necessary, and |
| 482 | provides read and write methods over that channel.""" |
| 483 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 484 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 485 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 486 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 487 | do_handshake_on_connect=True, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 488 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
| 489 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
| 490 | server_hostname=None, |
| 491 | _context=None): |
| 492 | |
Benjamin Peterson | 5f6b89b | 2014-11-23 11:16:48 -0600 | [diff] [blame] | 493 | self._makefile_refs = 0 |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 494 | if _context: |
| 495 | self._context = _context |
| 496 | else: |
| 497 | if server_side and not certfile: |
| 498 | raise ValueError("certfile must be specified for server-side " |
| 499 | "operations") |
| 500 | if keyfile and not certfile: |
| 501 | raise ValueError("certfile must be specified") |
| 502 | if certfile and not keyfile: |
| 503 | keyfile = certfile |
| 504 | self._context = SSLContext(ssl_version) |
| 505 | self._context.verify_mode = cert_reqs |
| 506 | if ca_certs: |
| 507 | self._context.load_verify_locations(ca_certs) |
| 508 | if certfile: |
| 509 | self._context.load_cert_chain(certfile, keyfile) |
| 510 | if npn_protocols: |
| 511 | self._context.set_npn_protocols(npn_protocols) |
| 512 | if ciphers: |
| 513 | self._context.set_ciphers(ciphers) |
| 514 | self.keyfile = keyfile |
| 515 | self.certfile = certfile |
| 516 | self.cert_reqs = cert_reqs |
| 517 | self.ssl_version = ssl_version |
| 518 | self.ca_certs = ca_certs |
| 519 | self.ciphers = ciphers |
Antoine Pitrou | 63cc99d | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 520 | # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get |
| 521 | # mixed in. |
| 522 | if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: |
| 523 | raise NotImplementedError("only stream sockets are supported") |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 524 | socket.__init__(self, _sock=sock._sock) |
Antoine Pitrou | dfb299b | 2010-04-23 22:54:59 +0000 | [diff] [blame] | 525 | # The initializer for socket overrides the methods send(), recv(), etc. |
| 526 | # in the instancce, which we don't need -- but we want to provide the |
| 527 | # methods defined in SSLSocket. |
| 528 | for attr in _delegate_methods: |
| 529 | try: |
| 530 | delattr(self, attr) |
| 531 | except AttributeError: |
| 532 | pass |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 533 | if server_side and server_hostname: |
| 534 | raise ValueError("server_hostname can only be specified " |
| 535 | "in client mode") |
| 536 | if self._context.check_hostname and not server_hostname: |
Benjamin Peterson | 31aa69e | 2014-11-23 20:13:31 -0600 | [diff] [blame] | 537 | raise ValueError("check_hostname requires server_hostname") |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 538 | self.server_side = server_side |
| 539 | self.server_hostname = server_hostname |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 540 | self.do_handshake_on_connect = do_handshake_on_connect |
| 541 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 542 | |
| 543 | # See if we are connected |
| 544 | try: |
| 545 | self.getpeername() |
| 546 | except socket_error as e: |
| 547 | if e.errno != errno.ENOTCONN: |
| 548 | raise |
| 549 | connected = False |
| 550 | else: |
| 551 | connected = True |
| 552 | |
| 553 | self._closed = False |
| 554 | self._sslobj = None |
| 555 | self._connected = connected |
| 556 | if connected: |
| 557 | # create the SSL object |
| 558 | try: |
| 559 | self._sslobj = self._context._wrap_socket(self._sock, server_side, |
| 560 | server_hostname, ssl_sock=self) |
| 561 | if do_handshake_on_connect: |
| 562 | timeout = self.gettimeout() |
| 563 | if timeout == 0.0: |
| 564 | # non-blocking |
| 565 | raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") |
| 566 | self.do_handshake() |
| 567 | |
| 568 | except (OSError, ValueError): |
| 569 | self.close() |
| 570 | raise |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 571 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 572 | @property |
| 573 | def context(self): |
| 574 | return self._context |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 575 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 576 | @context.setter |
| 577 | def context(self, ctx): |
| 578 | self._context = ctx |
| 579 | self._sslobj.context = ctx |
| 580 | |
| 581 | def dup(self): |
| 582 | raise NotImplemented("Can't dup() %s instances" % |
| 583 | self.__class__.__name__) |
| 584 | |
| 585 | def _checkClosed(self, msg=None): |
| 586 | # raise an exception here if you wish to check for spurious closes |
| 587 | pass |
| 588 | |
| 589 | def _check_connected(self): |
| 590 | if not self._connected: |
| 591 | # getpeername() will raise ENOTCONN if the socket is really |
| 592 | # not connected; note that we can be connected even without |
| 593 | # _connected being set, e.g. if connect() first returned |
| 594 | # EAGAIN. |
| 595 | self.getpeername() |
| 596 | |
| 597 | def read(self, len=0, buffer=None): |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 598 | """Read up to LEN bytes and return them. |
| 599 | Return zero-length string on EOF.""" |
| 600 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 601 | self._checkClosed() |
| 602 | if not self._sslobj: |
| 603 | raise ValueError("Read on closed or unwrapped SSL socket.") |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 604 | try: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 605 | if buffer is not None: |
| 606 | v = self._sslobj.read(len, buffer) |
| 607 | else: |
| 608 | v = self._sslobj.read(len or 1024) |
| 609 | return v |
| 610 | except SSLError as x: |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 611 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 612 | if buffer is not None: |
| 613 | return 0 |
| 614 | else: |
| 615 | return b'' |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 616 | else: |
| 617 | raise |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 618 | |
| 619 | def write(self, data): |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 620 | """Write DATA to the underlying SSL channel. Returns |
| 621 | number of bytes of DATA actually transmitted.""" |
| 622 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 623 | self._checkClosed() |
| 624 | if not self._sslobj: |
| 625 | raise ValueError("Write on closed or unwrapped SSL socket.") |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 626 | return self._sslobj.write(data) |
| 627 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 628 | def getpeercert(self, binary_form=False): |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 629 | """Returns a formatted version of the data in the |
| 630 | certificate provided by the other end of the SSL channel. |
| 631 | Return None if no certificate was provided, {} if a |
| 632 | certificate was provided, but not validated.""" |
| 633 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 634 | self._checkClosed() |
| 635 | self._check_connected() |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 636 | return self._sslobj.peer_certificate(binary_form) |
| 637 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 638 | def selected_npn_protocol(self): |
| 639 | self._checkClosed() |
| 640 | if not self._sslobj or not _ssl.HAS_NPN: |
| 641 | return None |
| 642 | else: |
| 643 | return self._sslobj.selected_npn_protocol() |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 644 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 645 | def cipher(self): |
| 646 | self._checkClosed() |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 647 | if not self._sslobj: |
| 648 | return None |
| 649 | else: |
| 650 | return self._sslobj.cipher() |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 651 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 652 | def compression(self): |
| 653 | self._checkClosed() |
| 654 | if not self._sslobj: |
| 655 | return None |
| 656 | else: |
| 657 | return self._sslobj.compression() |
| 658 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 659 | def send(self, data, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 660 | self._checkClosed() |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 661 | if self._sslobj: |
| 662 | if flags != 0: |
| 663 | raise ValueError( |
| 664 | "non-zero flags not allowed in calls to send() on %s" % |
| 665 | self.__class__) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 666 | try: |
| 667 | v = self._sslobj.write(data) |
| 668 | except SSLError as x: |
| 669 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 670 | return 0 |
| 671 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 672 | return 0 |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 673 | else: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 674 | raise |
| 675 | else: |
| 676 | return v |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 677 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 678 | return self._sock.send(data, flags) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 679 | |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 680 | def sendto(self, data, flags_or_addr, addr=None): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 681 | self._checkClosed() |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 682 | if self._sslobj: |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 683 | raise ValueError("sendto not allowed on instances of %s" % |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 684 | self.__class__) |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 685 | elif addr is None: |
| 686 | return self._sock.sendto(data, flags_or_addr) |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 687 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 688 | return self._sock.sendto(data, flags_or_addr, addr) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 689 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 690 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 691 | def sendall(self, data, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 692 | self._checkClosed() |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 693 | if self._sslobj: |
| 694 | if flags != 0: |
| 695 | raise ValueError( |
| 696 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 697 | self.__class__) |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 698 | amount = len(data) |
| 699 | count = 0 |
| 700 | while (count < amount): |
| 701 | v = self.send(data[count:]) |
| 702 | count += v |
| 703 | return amount |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 704 | else: |
| 705 | return socket.sendall(self, data, flags) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 706 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 707 | def recv(self, buflen=1024, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 708 | self._checkClosed() |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 709 | if self._sslobj: |
| 710 | if flags != 0: |
| 711 | raise ValueError( |
Antoine Pitrou | 448da71 | 2010-03-21 19:33:38 +0000 | [diff] [blame] | 712 | "non-zero flags not allowed in calls to recv() on %s" % |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 713 | self.__class__) |
Antoine Pitrou | 448da71 | 2010-03-21 19:33:38 +0000 | [diff] [blame] | 714 | return self.read(buflen) |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 715 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 716 | return self._sock.recv(buflen, flags) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 717 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 718 | def recv_into(self, buffer, nbytes=None, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 719 | self._checkClosed() |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 720 | if buffer and (nbytes is None): |
| 721 | nbytes = len(buffer) |
| 722 | elif nbytes is None: |
| 723 | nbytes = 1024 |
| 724 | if self._sslobj: |
| 725 | if flags != 0: |
| 726 | raise ValueError( |
| 727 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 728 | self.__class__) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 729 | return self.read(nbytes, buffer) |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 730 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 731 | return self._sock.recv_into(buffer, nbytes, flags) |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 732 | |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 733 | def recvfrom(self, buflen=1024, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 734 | self._checkClosed() |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 735 | if self._sslobj: |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 736 | raise ValueError("recvfrom not allowed on instances of %s" % |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 737 | self.__class__) |
| 738 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 739 | return self._sock.recvfrom(buflen, flags) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 740 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 741 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 742 | self._checkClosed() |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 743 | if self._sslobj: |
| 744 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 745 | self.__class__) |
| 746 | else: |
Antoine Pitrou | f7f390a | 2010-09-14 14:37:18 +0000 | [diff] [blame] | 747 | return self._sock.recvfrom_into(buffer, nbytes, flags) |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 748 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 749 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 750 | def pending(self): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 751 | self._checkClosed() |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 752 | if self._sslobj: |
| 753 | return self._sslobj.pending() |
| 754 | else: |
| 755 | return 0 |
| 756 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 757 | def shutdown(self, how): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 758 | self._checkClosed() |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 759 | self._sslobj = None |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 760 | socket.shutdown(self, how) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 761 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 762 | def close(self): |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 763 | if self._makefile_refs < 1: |
| 764 | self._sslobj = None |
| 765 | socket.close(self) |
| 766 | else: |
| 767 | self._makefile_refs -= 1 |
| 768 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 769 | def unwrap(self): |
| 770 | if self._sslobj: |
| 771 | s = self._sslobj.shutdown() |
| 772 | self._sslobj = None |
| 773 | return s |
| 774 | else: |
| 775 | raise ValueError("No SSL wrapper around " + str(self)) |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 776 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 777 | def _real_close(self): |
| 778 | self._sslobj = None |
| 779 | socket._real_close(self) |
| 780 | |
| 781 | def do_handshake(self, block=False): |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 782 | """Perform a TLS/SSL handshake.""" |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 783 | self._check_connected() |
| 784 | timeout = self.gettimeout() |
| 785 | try: |
| 786 | if timeout == 0.0 and block: |
| 787 | self.settimeout(None) |
| 788 | self._sslobj.do_handshake() |
| 789 | finally: |
| 790 | self.settimeout(timeout) |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 791 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 792 | if self.context.check_hostname: |
| 793 | if not self.server_hostname: |
| 794 | raise ValueError("check_hostname needs server_hostname " |
| 795 | "argument") |
| 796 | match_hostname(self.getpeercert(), self.server_hostname) |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 797 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 798 | def _real_connect(self, addr, connect_ex): |
| 799 | if self.server_side: |
| 800 | raise ValueError("can't connect in server-side mode") |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 801 | # Here we assume that the socket is client-side, and not |
| 802 | # connected at the time of the call. We connect it, then wrap it. |
Antoine Pitrou | d3f6ea1 | 2011-02-26 23:35:27 +0000 | [diff] [blame] | 803 | if self._connected: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 804 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 805 | self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname, ssl_sock=self) |
Antoine Pitrou | d3f6ea1 | 2011-02-26 23:35:27 +0000 | [diff] [blame] | 806 | try: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 807 | if connect_ex: |
Antoine Pitrou | 40f12ab | 2012-12-28 19:03:43 +0100 | [diff] [blame] | 808 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | d3f6ea1 | 2011-02-26 23:35:27 +0000 | [diff] [blame] | 809 | else: |
Antoine Pitrou | 40f12ab | 2012-12-28 19:03:43 +0100 | [diff] [blame] | 810 | rc = None |
| 811 | socket.connect(self, addr) |
| 812 | if not rc: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 813 | self._connected = True |
Antoine Pitrou | 40f12ab | 2012-12-28 19:03:43 +0100 | [diff] [blame] | 814 | if self.do_handshake_on_connect: |
| 815 | self.do_handshake() |
Antoine Pitrou | 40f12ab | 2012-12-28 19:03:43 +0100 | [diff] [blame] | 816 | return rc |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 817 | except (OSError, ValueError): |
Antoine Pitrou | 40f12ab | 2012-12-28 19:03:43 +0100 | [diff] [blame] | 818 | self._sslobj = None |
| 819 | raise |
Antoine Pitrou | d3f6ea1 | 2011-02-26 23:35:27 +0000 | [diff] [blame] | 820 | |
| 821 | def connect(self, addr): |
| 822 | """Connects to remote ADDR, and then wraps the connection in |
| 823 | an SSL channel.""" |
| 824 | self._real_connect(addr, False) |
| 825 | |
| 826 | def connect_ex(self, addr): |
| 827 | """Connects to remote ADDR, and then wraps the connection in |
| 828 | an SSL channel.""" |
| 829 | return self._real_connect(addr, True) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 830 | |
| 831 | def accept(self): |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 832 | """Accepts a new connection from a remote client, and returns |
| 833 | a tuple containing that new connection wrapped with a server-side |
| 834 | SSL channel, and the address of the remote client.""" |
| 835 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 836 | newsock, addr = socket.accept(self) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 837 | newsock = self.context.wrap_socket(newsock, |
| 838 | do_handshake_on_connect=self.do_handshake_on_connect, |
| 839 | suppress_ragged_eofs=self.suppress_ragged_eofs, |
| 840 | server_side=True) |
| 841 | return newsock, addr |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 842 | |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 843 | def makefile(self, mode='r', bufsize=-1): |
| 844 | |
Bill Janssen | 61c001a | 2008-09-08 16:37:24 +0000 | [diff] [blame] | 845 | """Make and return a file-like object that |
| 846 | works with the SSL connection. Just use the code |
| 847 | from the socket module.""" |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 848 | |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 849 | self._makefile_refs += 1 |
Antoine Pitrou | b558f17 | 2010-04-23 23:25:45 +0000 | [diff] [blame] | 850 | # close=True so as to decrement the reference count when done with |
| 851 | # the file-like object. |
| 852 | return _fileobject(self, mode, bufsize, close=True) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 853 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 854 | def get_channel_binding(self, cb_type="tls-unique"): |
| 855 | """Get channel binding data for current connection. Raise ValueError |
| 856 | if the requested `cb_type` is not supported. Return bytes of the data |
| 857 | or None if the data is not available (e.g. before the handshake). |
| 858 | """ |
| 859 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 860 | raise ValueError("Unsupported channel binding type") |
| 861 | if cb_type != "tls-unique": |
| 862 | raise NotImplementedError( |
| 863 | "{0} channel binding type not implemented" |
| 864 | .format(cb_type)) |
| 865 | if self._sslobj is None: |
| 866 | return None |
| 867 | return self._sslobj.tls_unique_cb() |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 868 | |
Alex Gaynor | e98205d | 2014-09-04 13:33:22 -0700 | [diff] [blame] | 869 | def version(self): |
| 870 | """ |
| 871 | Return a string identifying the protocol version used by the |
| 872 | current SSL channel, or None if there is no established channel. |
| 873 | """ |
| 874 | if self._sslobj is None: |
| 875 | return None |
| 876 | return self._sslobj.version() |
| 877 | |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 878 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 879 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 880 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 881 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 882 | do_handshake_on_connect=True, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 883 | suppress_ragged_eofs=True, |
| 884 | ciphers=None): |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 885 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 886 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 887 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 888 | ssl_version=ssl_version, ca_certs=ca_certs, |
| 889 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 890 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 891 | ciphers=ciphers) |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 892 | |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 893 | # some utility functions |
| 894 | |
| 895 | def cert_time_to_seconds(cert_time): |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 896 | """Return the time in seconds since the Epoch, given the timestring |
| 897 | representing the "notBefore" or "notAfter" date from a certificate |
| 898 | in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 899 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 900 | "notBefore" or "notAfter" dates must use UTC (RFC 5280). |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 901 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 902 | Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec |
| 903 | UTC should be specified as GMT (see ASN1_TIME_print()) |
| 904 | """ |
| 905 | from time import strptime |
| 906 | from calendar import timegm |
| 907 | |
| 908 | months = ( |
| 909 | "Jan","Feb","Mar","Apr","May","Jun", |
| 910 | "Jul","Aug","Sep","Oct","Nov","Dec" |
| 911 | ) |
| 912 | time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT |
| 913 | try: |
| 914 | month_number = months.index(cert_time[:3].title()) + 1 |
| 915 | except ValueError: |
| 916 | raise ValueError('time data %r does not match ' |
| 917 | 'format "%%b%s"' % (cert_time, time_format)) |
| 918 | else: |
| 919 | # found valid month |
| 920 | tt = strptime(cert_time[3:], time_format) |
| 921 | # return an integer, the previous mktime()-based implementation |
| 922 | # returned a float (fractional seconds are always zero here). |
| 923 | return timegm((tt[0], month_number) + tt[2:6]) |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 924 | |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 925 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 926 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 927 | |
| 928 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 929 | """Takes a certificate in binary DER format and returns the |
| 930 | PEM version of it as a string.""" |
| 931 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 932 | f = base64.standard_b64encode(der_cert_bytes).decode('ascii') |
| 933 | return (PEM_HEADER + '\n' + |
| 934 | textwrap.fill(f, 64) + '\n' + |
| 935 | PEM_FOOTER + '\n') |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 936 | |
| 937 | def PEM_cert_to_DER_cert(pem_cert_string): |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 938 | """Takes a certificate in ASCII PEM format and returns the |
| 939 | DER-encoded version of it as a byte sequence""" |
| 940 | |
| 941 | if not pem_cert_string.startswith(PEM_HEADER): |
| 942 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 943 | % PEM_HEADER) |
| 944 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 945 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 946 | % PEM_FOOTER) |
| 947 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 948 | return base64.decodestring(d.encode('ASCII', 'strict')) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 949 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 950 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 951 | """Retrieve the certificate from the server at the specified address, |
| 952 | and return it as a PEM-encoded string. |
| 953 | If 'ca_certs' is specified, validate the server cert against it. |
| 954 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 955 | |
| 956 | host, port = addr |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 957 | if ca_certs is not None: |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 958 | cert_reqs = CERT_REQUIRED |
| 959 | else: |
| 960 | cert_reqs = CERT_NONE |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 961 | context = _create_stdlib_context(ssl_version, |
| 962 | cert_reqs=cert_reqs, |
| 963 | cafile=ca_certs) |
| 964 | with closing(create_connection(addr)) as sock: |
| 965 | with closing(context.wrap_socket(sock)) as sslsock: |
| 966 | dercert = sslsock.getpeercert(True) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 967 | return DER_cert_to_PEM_cert(dercert) |
| 968 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 969 | def get_protocol_name(protocol_code): |
Victor Stinner | b1241f9 | 2011-05-10 01:52:03 +0200 | [diff] [blame] | 970 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 971 | |
| 972 | |
Guido van Rossum | 4f2c3dd | 2007-08-25 15:08:43 +0000 | [diff] [blame] | 973 | # a replacement for the old socket.ssl function |
| 974 | |
Ezio Melotti | b01f5e6 | 2010-01-18 09:10:26 +0000 | [diff] [blame] | 975 | def sslwrap_simple(sock, keyfile=None, certfile=None): |
Bill Janssen | 24bccf2 | 2007-08-30 17:07:28 +0000 | [diff] [blame] | 976 | """A replacement for the old socket.ssl function. Designed |
| 977 | for compability with Python 2.5 and earlier. Will disappear in |
| 978 | Python 3.0.""" |
Bill Janssen | eb257ac | 2008-09-29 18:56:38 +0000 | [diff] [blame] | 979 | if hasattr(sock, "_sock"): |
| 980 | sock = sock._sock |
| 981 | |
Benjamin Peterson | 2f33456 | 2014-10-01 23:53:01 -0400 | [diff] [blame] | 982 | ctx = SSLContext(PROTOCOL_SSLv23) |
| 983 | if keyfile or certfile: |
| 984 | ctx.load_cert_chain(certfile, keyfile) |
| 985 | ssl_sock = ctx._wrap_socket(sock, server_side=False) |
Bill Janssen | eb257ac | 2008-09-29 18:56:38 +0000 | [diff] [blame] | 986 | try: |
| 987 | sock.getpeername() |
Benjamin Peterson | 941db4d | 2008-12-31 04:08:55 +0000 | [diff] [blame] | 988 | except socket_error: |
Bill Janssen | eb257ac | 2008-09-29 18:56:38 +0000 | [diff] [blame] | 989 | # no, no connection yet |
| 990 | pass |
| 991 | else: |
| 992 | # yes, do the handshake |
| 993 | ssl_sock.do_handshake() |
| 994 | |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 995 | return ssl_sock |