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