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