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