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 |
| 55 | """ |
| 56 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 57 | import textwrap |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 58 | import re |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 59 | |
| 60 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 61 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 62 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 63 | from _ssl import _SSLContext |
| 64 | from _ssl import ( |
| 65 | SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, |
| 66 | SSLSyscallError, SSLEOFError, |
| 67 | ) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 68 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Antoine Pitrou | 6db4944 | 2011-12-19 13:27:11 +0100 | [diff] [blame] | 69 | from _ssl import ( |
| 70 | OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1, |
Antoine Pitrou | a9bf2ac | 2012-02-17 18:47:54 +0100 | [diff] [blame] | 71 | OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE |
Antoine Pitrou | 6db4944 | 2011-12-19 13:27:11 +0100 | [diff] [blame] | 72 | ) |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 73 | try: |
| 74 | from _ssl import OP_NO_COMPRESSION |
| 75 | except ImportError: |
| 76 | pass |
Antoine Pitrou | a9bf2ac | 2012-02-17 18:47:54 +0100 | [diff] [blame] | 77 | try: |
| 78 | from _ssl import OP_SINGLE_ECDH_USE |
| 79 | except ImportError: |
| 80 | pass |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 81 | from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 82 | from _ssl import ( |
| 83 | SSL_ERROR_ZERO_RETURN, |
| 84 | SSL_ERROR_WANT_READ, |
| 85 | SSL_ERROR_WANT_WRITE, |
| 86 | SSL_ERROR_WANT_X509_LOOKUP, |
| 87 | SSL_ERROR_SYSCALL, |
| 88 | SSL_ERROR_SSL, |
| 89 | SSL_ERROR_WANT_CONNECT, |
| 90 | SSL_ERROR_EOF, |
| 91 | SSL_ERROR_INVALID_ERROR_CODE, |
| 92 | ) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 93 | from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 94 | from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23, |
| 95 | PROTOCOL_TLSv1) |
Antoine Pitrou | b9ac25d | 2011-07-08 18:47:06 +0200 | [diff] [blame] | 96 | from _ssl import _OPENSSL_API_VERSION |
| 97 | |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 98 | _PROTOCOL_NAMES = { |
| 99 | PROTOCOL_TLSv1: "TLSv1", |
| 100 | PROTOCOL_SSLv23: "SSLv23", |
| 101 | PROTOCOL_SSLv3: "SSLv3", |
| 102 | } |
| 103 | try: |
| 104 | from _ssl import PROTOCOL_SSLv2 |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 105 | _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 106 | except ImportError: |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 107 | _SSLv2_IF_EXISTS = None |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 108 | else: |
| 109 | _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 110 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 111 | from socket import getnameinfo as _getnameinfo |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 112 | from socket import error as socket_error |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 113 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 114 | import base64 # for DER-to-PEM translation |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 115 | import traceback |
Antoine Pitrou | de8cf32 | 2010-04-26 17:29:05 +0000 | [diff] [blame] | 116 | import errno |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 117 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 118 | if _ssl.HAS_TLS_UNIQUE: |
| 119 | CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 120 | else: |
| 121 | CHANNEL_BINDING_TYPES = [] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 122 | |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 123 | # Disable weak or insecure ciphers by default |
| 124 | # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') |
| 125 | _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2' |
| 126 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 127 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 128 | class CertificateError(ValueError): |
| 129 | pass |
| 130 | |
| 131 | |
| 132 | def _dnsname_to_pat(dn): |
| 133 | pats = [] |
| 134 | for frag in dn.split(r'.'): |
| 135 | if frag == '*': |
| 136 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 137 | # fragment. |
| 138 | pats.append('[^.]+') |
| 139 | else: |
| 140 | # Otherwise, '*' matches any dotless fragment. |
| 141 | frag = re.escape(frag) |
| 142 | pats.append(frag.replace(r'\*', '[^.]*')) |
| 143 | return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 144 | |
| 145 | |
| 146 | def match_hostname(cert, hostname): |
| 147 | """Verify that *cert* (in decoded format as returned by |
| 148 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules |
| 149 | are mostly followed, but IP addresses are not accepted for *hostname*. |
| 150 | |
| 151 | CertificateError is raised on failure. On success, the function |
| 152 | returns nothing. |
| 153 | """ |
| 154 | if not cert: |
| 155 | raise ValueError("empty or no certificate") |
| 156 | dnsnames = [] |
| 157 | san = cert.get('subjectAltName', ()) |
| 158 | for key, value in san: |
| 159 | if key == 'DNS': |
| 160 | if _dnsname_to_pat(value).match(hostname): |
| 161 | return |
| 162 | dnsnames.append(value) |
Antoine Pitrou | 1c86b44 | 2011-05-06 15:19:49 +0200 | [diff] [blame] | 163 | if not dnsnames: |
| 164 | # The subject is only checked when there is no dNSName entry |
| 165 | # in subjectAltName |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 166 | for sub in cert.get('subject', ()): |
| 167 | for key, value in sub: |
| 168 | # XXX according to RFC 2818, the most specific Common Name |
| 169 | # must be used. |
| 170 | if key == 'commonName': |
| 171 | if _dnsname_to_pat(value).match(hostname): |
| 172 | return |
| 173 | dnsnames.append(value) |
| 174 | if len(dnsnames) > 1: |
| 175 | raise CertificateError("hostname %r " |
| 176 | "doesn't match either of %s" |
| 177 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 178 | elif len(dnsnames) == 1: |
| 179 | raise CertificateError("hostname %r " |
| 180 | "doesn't match %r" |
| 181 | % (hostname, dnsnames[0])) |
| 182 | else: |
| 183 | raise CertificateError("no appropriate commonName or " |
| 184 | "subjectAltName fields were found") |
| 185 | |
| 186 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 187 | class SSLContext(_SSLContext): |
| 188 | """An SSLContext holds various SSL-related configuration options and |
| 189 | data, such as certificates and possibly a private key.""" |
| 190 | |
| 191 | __slots__ = ('protocol',) |
| 192 | |
| 193 | def __new__(cls, protocol, *args, **kwargs): |
Antoine Pitrou | 8f85f90 | 2012-01-03 22:46:48 +0100 | [diff] [blame] | 194 | self = _SSLContext.__new__(cls, protocol) |
| 195 | if protocol != _SSLv2_IF_EXISTS: |
| 196 | self.set_ciphers(_DEFAULT_CIPHERS) |
| 197 | return self |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 198 | |
| 199 | def __init__(self, protocol): |
| 200 | self.protocol = protocol |
| 201 | |
| 202 | def wrap_socket(self, sock, server_side=False, |
| 203 | do_handshake_on_connect=True, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 204 | suppress_ragged_eofs=True, |
| 205 | server_hostname=None): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 206 | return SSLSocket(sock=sock, server_side=server_side, |
| 207 | do_handshake_on_connect=do_handshake_on_connect, |
| 208 | suppress_ragged_eofs=suppress_ragged_eofs, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 209 | server_hostname=server_hostname, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 210 | _context=self) |
| 211 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 212 | def set_npn_protocols(self, npn_protocols): |
| 213 | protos = bytearray() |
| 214 | for protocol in npn_protocols: |
| 215 | b = bytes(protocol, 'ascii') |
| 216 | if len(b) == 0 or len(b) > 255: |
| 217 | raise SSLError('NPN protocols must be 1 to 255 in length') |
| 218 | protos.append(len(b)) |
| 219 | protos.extend(b) |
| 220 | |
| 221 | self._set_npn_protocols(protos) |
| 222 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 223 | |
| 224 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 225 | """This class implements a subtype of socket.socket that wraps |
| 226 | the underlying OS socket in an SSL context when necessary, and |
| 227 | provides read and write methods over that channel.""" |
| 228 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 229 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 230 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 231 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 232 | do_handshake_on_connect=True, |
| 233 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 234 | suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 235 | server_hostname=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 236 | _context=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 237 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 238 | if _context: |
| 239 | self.context = _context |
| 240 | else: |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 241 | if server_side and not certfile: |
| 242 | raise ValueError("certfile must be specified for server-side " |
| 243 | "operations") |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 244 | if keyfile and not certfile: |
| 245 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 246 | if certfile and not keyfile: |
| 247 | keyfile = certfile |
| 248 | self.context = SSLContext(ssl_version) |
| 249 | self.context.verify_mode = cert_reqs |
| 250 | if ca_certs: |
| 251 | self.context.load_verify_locations(ca_certs) |
| 252 | if certfile: |
| 253 | self.context.load_cert_chain(certfile, keyfile) |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 254 | if npn_protocols: |
| 255 | self.context.set_npn_protocols(npn_protocols) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 256 | if ciphers: |
| 257 | self.context.set_ciphers(ciphers) |
| 258 | self.keyfile = keyfile |
| 259 | self.certfile = certfile |
| 260 | self.cert_reqs = cert_reqs |
| 261 | self.ssl_version = ssl_version |
| 262 | self.ca_certs = ca_certs |
| 263 | self.ciphers = ciphers |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 264 | if server_side and server_hostname: |
| 265 | raise ValueError("server_hostname can only be specified " |
| 266 | "in client mode") |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 267 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 268 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 269 | self.do_handshake_on_connect = do_handshake_on_connect |
| 270 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 271 | connected = False |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 272 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 273 | socket.__init__(self, |
| 274 | family=sock.family, |
| 275 | type=sock.type, |
| 276 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 277 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 278 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 279 | # see if it's connected |
| 280 | try: |
| 281 | sock.getpeername() |
| 282 | except socket_error as e: |
| 283 | if e.errno != errno.ENOTCONN: |
| 284 | raise |
| 285 | else: |
| 286 | connected = True |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 287 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 288 | elif fileno is not None: |
| 289 | socket.__init__(self, fileno=fileno) |
| 290 | else: |
| 291 | socket.__init__(self, family=family, type=type, proto=proto) |
| 292 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 293 | self._closed = False |
| 294 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 295 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 296 | if connected: |
| 297 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 298 | try: |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 299 | self._sslobj = self.context._wrap_socket(self, server_side, |
| 300 | server_hostname) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 301 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 302 | timeout = self.gettimeout() |
| 303 | if timeout == 0.0: |
| 304 | # non-blocking |
| 305 | 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] | 306 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 307 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 308 | except socket_error as x: |
| 309 | self.close() |
| 310 | raise x |
| 311 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 312 | def dup(self): |
| 313 | raise NotImplemented("Can't dup() %s instances" % |
| 314 | self.__class__.__name__) |
| 315 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 316 | def _checkClosed(self, msg=None): |
| 317 | # raise an exception here if you wish to check for spurious closes |
| 318 | pass |
| 319 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 320 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 321 | """Read up to LEN bytes and return them. |
| 322 | Return zero-length string on EOF.""" |
| 323 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 324 | self._checkClosed() |
| 325 | try: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 326 | if buffer is not None: |
| 327 | v = self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 328 | else: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 329 | v = self._sslobj.read(len or 1024) |
| 330 | return v |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 331 | except SSLError as x: |
| 332 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 333 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 334 | return 0 |
| 335 | else: |
| 336 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 337 | else: |
| 338 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 339 | |
| 340 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 341 | """Write DATA to the underlying SSL channel. Returns |
| 342 | number of bytes of DATA actually transmitted.""" |
| 343 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 344 | self._checkClosed() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 345 | return self._sslobj.write(data) |
| 346 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 347 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 348 | """Returns a formatted version of the data in the |
| 349 | certificate provided by the other end of the SSL channel. |
| 350 | Return None if no certificate was provided, {} if a |
| 351 | certificate was provided, but not validated.""" |
| 352 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 353 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 354 | return self._sslobj.peer_certificate(binary_form) |
| 355 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 356 | def selected_npn_protocol(self): |
| 357 | self._checkClosed() |
| 358 | if not self._sslobj or not _ssl.HAS_NPN: |
| 359 | return None |
| 360 | else: |
| 361 | return self._sslobj.selected_npn_protocol() |
| 362 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 363 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 364 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 365 | if not self._sslobj: |
| 366 | return None |
| 367 | else: |
| 368 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 369 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 370 | def compression(self): |
| 371 | self._checkClosed() |
| 372 | if not self._sslobj: |
| 373 | return None |
| 374 | else: |
| 375 | return self._sslobj.compression() |
| 376 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 377 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 378 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 379 | if self._sslobj: |
| 380 | if flags != 0: |
| 381 | raise ValueError( |
| 382 | "non-zero flags not allowed in calls to send() on %s" % |
| 383 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 384 | while True: |
| 385 | try: |
| 386 | v = self._sslobj.write(data) |
| 387 | except SSLError as x: |
| 388 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 389 | return 0 |
| 390 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 391 | return 0 |
| 392 | else: |
| 393 | raise |
| 394 | else: |
| 395 | return v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 396 | else: |
| 397 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 398 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 399 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 400 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 401 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 402 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 403 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 404 | elif addr is None: |
| 405 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 406 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 407 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 408 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 409 | def sendmsg(self, *args, **kwargs): |
| 410 | # Ensure programs don't send data unencrypted if they try to |
| 411 | # use this method. |
| 412 | raise NotImplementedError("sendmsg not allowed on instances of %s" % |
| 413 | self.__class__) |
| 414 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 415 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 416 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 417 | if self._sslobj: |
Giampaolo Rodolà | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 418 | if flags != 0: |
| 419 | raise ValueError( |
| 420 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 421 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 422 | amount = len(data) |
| 423 | count = 0 |
| 424 | while (count < amount): |
| 425 | v = self.send(data[count:]) |
| 426 | count += v |
| 427 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 428 | else: |
| 429 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 430 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 431 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 432 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 433 | if self._sslobj: |
| 434 | if flags != 0: |
| 435 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 436 | "non-zero flags not allowed in calls to recv() on %s" % |
| 437 | self.__class__) |
| 438 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 439 | else: |
| 440 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 441 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 442 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 443 | self._checkClosed() |
| 444 | if buffer and (nbytes is None): |
| 445 | nbytes = len(buffer) |
| 446 | elif nbytes is None: |
| 447 | nbytes = 1024 |
| 448 | if self._sslobj: |
| 449 | if flags != 0: |
| 450 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 451 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 452 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 453 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 454 | else: |
| 455 | return socket.recv_into(self, buffer, nbytes, flags) |
| 456 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 457 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 458 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 459 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 460 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 461 | self.__class__) |
| 462 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 463 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 464 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 465 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 466 | self._checkClosed() |
| 467 | if self._sslobj: |
| 468 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 469 | self.__class__) |
| 470 | else: |
| 471 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 472 | |
Nick Coghlan | 513886a | 2011-08-28 00:00:27 +1000 | [diff] [blame] | 473 | def recvmsg(self, *args, **kwargs): |
| 474 | raise NotImplementedError("recvmsg not allowed on instances of %s" % |
| 475 | self.__class__) |
| 476 | |
| 477 | def recvmsg_into(self, *args, **kwargs): |
| 478 | raise NotImplementedError("recvmsg_into not allowed on instances of " |
| 479 | "%s" % self.__class__) |
| 480 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 481 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 482 | self._checkClosed() |
| 483 | if self._sslobj: |
| 484 | return self._sslobj.pending() |
| 485 | else: |
| 486 | return 0 |
| 487 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 488 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 489 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 490 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 491 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 492 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 493 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 494 | if self._sslobj: |
| 495 | s = self._sslobj.shutdown() |
| 496 | self._sslobj = None |
| 497 | return s |
| 498 | else: |
| 499 | raise ValueError("No SSL wrapper around " + str(self)) |
| 500 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 501 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 502 | self._sslobj = None |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 503 | # self._closed = True |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 504 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 505 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 506 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 507 | """Perform a TLS/SSL handshake.""" |
| 508 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 509 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 510 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 511 | if timeout == 0.0 and block: |
| 512 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 513 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 514 | finally: |
| 515 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 516 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 517 | def _real_connect(self, addr, connect_ex): |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 518 | if self.server_side: |
| 519 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 520 | # Here we assume that the socket is client-side, and not |
| 521 | # 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] | 522 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 523 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 524 | self._sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 525 | try: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 526 | if connect_ex: |
| 527 | rc = socket.connect_ex(self, addr) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 528 | else: |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 529 | rc = None |
| 530 | socket.connect(self, addr) |
| 531 | if not rc: |
| 532 | if self.do_handshake_on_connect: |
| 533 | self.do_handshake() |
| 534 | self._connected = True |
| 535 | return rc |
| 536 | except socket_error: |
| 537 | self._sslobj = None |
| 538 | raise |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 539 | |
| 540 | def connect(self, addr): |
| 541 | """Connects to remote ADDR, and then wraps the connection in |
| 542 | an SSL channel.""" |
| 543 | self._real_connect(addr, False) |
| 544 | |
| 545 | def connect_ex(self, addr): |
| 546 | """Connects to remote ADDR, and then wraps the connection in |
| 547 | an SSL channel.""" |
| 548 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 549 | |
| 550 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 551 | """Accepts a new connection from a remote client, and returns |
| 552 | a tuple containing that new connection wrapped with a server-side |
| 553 | SSL channel, and the address of the remote client.""" |
| 554 | |
| 555 | newsock, addr = socket.accept(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 556 | return (SSLSocket(sock=newsock, |
| 557 | keyfile=self.keyfile, certfile=self.certfile, |
| 558 | server_side=True, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 559 | cert_reqs=self.cert_reqs, |
| 560 | ssl_version=self.ssl_version, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 561 | ca_certs=self.ca_certs, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 562 | ciphers=self.ciphers, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 563 | do_handshake_on_connect= |
| 564 | self.do_handshake_on_connect), |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 565 | addr) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 566 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 567 | def get_channel_binding(self, cb_type="tls-unique"): |
| 568 | """Get channel binding data for current connection. Raise ValueError |
| 569 | if the requested `cb_type` is not supported. Return bytes of the data |
| 570 | or None if the data is not available (e.g. before the handshake). |
| 571 | """ |
| 572 | if cb_type not in CHANNEL_BINDING_TYPES: |
| 573 | raise ValueError("Unsupported channel binding type") |
| 574 | if cb_type != "tls-unique": |
| 575 | raise NotImplementedError( |
| 576 | "{0} channel binding type not implemented" |
| 577 | .format(cb_type)) |
| 578 | if self._sslobj is None: |
| 579 | return None |
| 580 | return self._sslobj.tls_unique_cb() |
| 581 | |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 582 | def __del__(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 583 | # sys.stderr.write("__del__ on %s\n" % repr(self)) |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 584 | self._real_close() |
| 585 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 586 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 587 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 588 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 589 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 590 | do_handshake_on_connect=True, |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 591 | suppress_ragged_eofs=True, |
| 592 | ciphers=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 593 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 594 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 595 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 596 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 597 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 598 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 599 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 600 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 601 | # some utility functions |
| 602 | |
| 603 | def cert_time_to_seconds(cert_time): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 604 | """Takes a date-time string in standard ASN1_print form |
| 605 | ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return |
| 606 | a Python time value in seconds past the epoch.""" |
| 607 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 608 | import time |
| 609 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 610 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 611 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 612 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 613 | |
| 614 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 615 | """Takes a certificate in binary DER format and returns the |
| 616 | PEM version of it as a string.""" |
| 617 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 618 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 619 | return (PEM_HEADER + '\n' + |
| 620 | textwrap.fill(f, 64) + '\n' + |
| 621 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 622 | |
| 623 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 624 | """Takes a certificate in ASCII PEM format and returns the |
| 625 | DER-encoded version of it as a byte sequence""" |
| 626 | |
| 627 | if not pem_cert_string.startswith(PEM_HEADER): |
| 628 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 629 | % PEM_HEADER) |
| 630 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 631 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 632 | % PEM_FOOTER) |
| 633 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 634 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 635 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 636 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 637 | """Retrieve the certificate from the server at the specified address, |
| 638 | and return it as a PEM-encoded string. |
| 639 | If 'ca_certs' is specified, validate the server cert against it. |
| 640 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 641 | |
| 642 | host, port = addr |
| 643 | if (ca_certs is not None): |
| 644 | cert_reqs = CERT_REQUIRED |
| 645 | else: |
| 646 | cert_reqs = CERT_NONE |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 647 | s = create_connection(addr) |
| 648 | s = wrap_socket(s, ssl_version=ssl_version, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 649 | cert_reqs=cert_reqs, ca_certs=ca_certs) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 650 | dercert = s.getpeercert(True) |
| 651 | s.close() |
| 652 | return DER_cert_to_PEM_cert(dercert) |
| 653 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 654 | def get_protocol_name(protocol_code): |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 655 | return _PROTOCOL_NAMES.get(protocol_code, '<unknown>') |