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