blob: 39cef2c699b3f61aa07aa56026277eaa915cf64c [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
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
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
54PROTOCOL_TLSv1
55"""
56
Christian Heimes05e8be12008-02-23 18:30:17 +000057import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000058import re
Thomas Woutersed03b412007-08-28 21:37:11 +000059
60import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061
Antoine Pitrou04f6a322010-04-05 21:40:07 +000062from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou152efa22010-05-16 18:19:27 +000063from _ssl import _SSLContext, SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000064from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Antoine Pitroub5218772010-05-21 09:56:06 +000065from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Victor Stinner99c8b162011-05-24 12:05:19 +020066from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Guido van Rossum5b8b1552007-11-16 00:06:11 +000067from _ssl import (
68 SSL_ERROR_ZERO_RETURN,
69 SSL_ERROR_WANT_READ,
70 SSL_ERROR_WANT_WRITE,
71 SSL_ERROR_WANT_X509_LOOKUP,
72 SSL_ERROR_SYSCALL,
73 SSL_ERROR_SSL,
74 SSL_ERROR_WANT_CONNECT,
75 SSL_ERROR_EOF,
76 SSL_ERROR_INVALID_ERROR_CODE,
77 )
Antoine Pitroud5323212010-10-22 18:19:07 +000078from _ssl import HAS_SNI
Victor Stinner3de49192011-05-09 00:42:58 +020079from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
80 PROTOCOL_TLSv1)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020081from _ssl import _OPENSSL_API_VERSION
82
Victor Stinner3de49192011-05-09 00:42:58 +020083_PROTOCOL_NAMES = {
84 PROTOCOL_TLSv1: "TLSv1",
85 PROTOCOL_SSLv23: "SSLv23",
86 PROTOCOL_SSLv3: "SSLv3",
87}
88try:
89 from _ssl import PROTOCOL_SSLv2
90except ImportError:
91 pass
92else:
93 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000094
Thomas Wouters47b49bf2007-08-30 22:15:33 +000095from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000096from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +020097from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000099import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000100import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000101
Antoine Pitroud6494802011-07-21 01:11:30 +0200102if _ssl.HAS_TLS_UNIQUE:
103 CHANNEL_BINDING_TYPES = ['tls-unique']
104else:
105 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000106
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000107class CertificateError(ValueError):
108 pass
109
110
111def _dnsname_to_pat(dn):
112 pats = []
113 for frag in dn.split(r'.'):
114 if frag == '*':
115 # When '*' is a fragment by itself, it matches a non-empty dotless
116 # fragment.
117 pats.append('[^.]+')
118 else:
119 # Otherwise, '*' matches any dotless fragment.
120 frag = re.escape(frag)
121 pats.append(frag.replace(r'\*', '[^.]*'))
122 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
123
124
125def match_hostname(cert, hostname):
126 """Verify that *cert* (in decoded format as returned by
127 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
128 are mostly followed, but IP addresses are not accepted for *hostname*.
129
130 CertificateError is raised on failure. On success, the function
131 returns nothing.
132 """
133 if not cert:
134 raise ValueError("empty or no certificate")
135 dnsnames = []
136 san = cert.get('subjectAltName', ())
137 for key, value in san:
138 if key == 'DNS':
139 if _dnsname_to_pat(value).match(hostname):
140 return
141 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200142 if not dnsnames:
143 # The subject is only checked when there is no dNSName entry
144 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000145 for sub in cert.get('subject', ()):
146 for key, value in sub:
147 # XXX according to RFC 2818, the most specific Common Name
148 # must be used.
149 if key == 'commonName':
150 if _dnsname_to_pat(value).match(hostname):
151 return
152 dnsnames.append(value)
153 if len(dnsnames) > 1:
154 raise CertificateError("hostname %r "
155 "doesn't match either of %s"
156 % (hostname, ', '.join(map(repr, dnsnames))))
157 elif len(dnsnames) == 1:
158 raise CertificateError("hostname %r "
159 "doesn't match %r"
160 % (hostname, dnsnames[0]))
161 else:
162 raise CertificateError("no appropriate commonName or "
163 "subjectAltName fields were found")
164
165
Antoine Pitrou152efa22010-05-16 18:19:27 +0000166class SSLContext(_SSLContext):
167 """An SSLContext holds various SSL-related configuration options and
168 data, such as certificates and possibly a private key."""
169
170 __slots__ = ('protocol',)
171
172 def __new__(cls, protocol, *args, **kwargs):
173 return _SSLContext.__new__(cls, protocol)
174
175 def __init__(self, protocol):
176 self.protocol = protocol
177
178 def wrap_socket(self, sock, server_side=False,
179 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000180 suppress_ragged_eofs=True,
181 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000182 return SSLSocket(sock=sock, server_side=server_side,
183 do_handshake_on_connect=do_handshake_on_connect,
184 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000185 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186 _context=self)
187
188
189class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000190 """This class implements a subtype of socket.socket that wraps
191 the underlying OS socket in an SSL context when necessary, and
192 provides read and write methods over that channel."""
193
Bill Janssen6e027db2007-11-15 22:23:56 +0000194 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000195 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000196 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
197 do_handshake_on_connect=True,
198 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000199 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000200 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000201 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000202
Antoine Pitrou152efa22010-05-16 18:19:27 +0000203 if _context:
204 self.context = _context
205 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000206 if server_side and not certfile:
207 raise ValueError("certfile must be specified for server-side "
208 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000209 if keyfile and not certfile:
210 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211 if certfile and not keyfile:
212 keyfile = certfile
213 self.context = SSLContext(ssl_version)
214 self.context.verify_mode = cert_reqs
215 if ca_certs:
216 self.context.load_verify_locations(ca_certs)
217 if certfile:
218 self.context.load_cert_chain(certfile, keyfile)
219 if ciphers:
220 self.context.set_ciphers(ciphers)
221 self.keyfile = keyfile
222 self.certfile = certfile
223 self.cert_reqs = cert_reqs
224 self.ssl_version = ssl_version
225 self.ca_certs = ca_certs
226 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000227 if server_side and server_hostname:
228 raise ValueError("server_hostname can only be specified "
229 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000230 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000231 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232 self.do_handshake_on_connect = do_handshake_on_connect
233 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000234 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000235 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000236 socket.__init__(self,
237 family=sock.family,
238 type=sock.type,
239 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000240 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000241 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000242 # see if it's connected
243 try:
244 sock.getpeername()
245 except socket_error as e:
246 if e.errno != errno.ENOTCONN:
247 raise
248 else:
249 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000250 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000251 elif fileno is not None:
252 socket.__init__(self, fileno=fileno)
253 else:
254 socket.__init__(self, family=family, type=type, proto=proto)
255
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000256 self._closed = False
257 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000258 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000259 if connected:
260 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000261 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000262 self._sslobj = self.context._wrap_socket(self, server_side,
263 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000265 timeout = self.gettimeout()
266 if timeout == 0.0:
267 # non-blocking
268 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000269 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000270
Bill Janssen6e027db2007-11-15 22:23:56 +0000271 except socket_error as x:
272 self.close()
273 raise x
274
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000275 def dup(self):
276 raise NotImplemented("Can't dup() %s instances" %
277 self.__class__.__name__)
278
Bill Janssen6e027db2007-11-15 22:23:56 +0000279 def _checkClosed(self, msg=None):
280 # raise an exception here if you wish to check for spurious closes
281 pass
282
Bill Janssen54cc54c2007-12-14 22:08:56 +0000283 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000284 """Read up to LEN bytes and return them.
285 Return zero-length string on EOF."""
286
Bill Janssen6e027db2007-11-15 22:23:56 +0000287 self._checkClosed()
288 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000289 if buffer is not None:
290 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000291 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000292 v = self._sslobj.read(len or 1024)
293 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000294 except SSLError as x:
295 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000296 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000297 return 0
298 else:
299 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000300 else:
301 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000302
303 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000304 """Write DATA to the underlying SSL channel. Returns
305 number of bytes of DATA actually transmitted."""
306
Bill Janssen6e027db2007-11-15 22:23:56 +0000307 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000308 return self._sslobj.write(data)
309
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000311 """Returns a formatted version of the data in the
312 certificate provided by the other end of the SSL channel.
313 Return None if no certificate was provided, {} if a
314 certificate was provided, but not validated."""
315
Bill Janssen6e027db2007-11-15 22:23:56 +0000316 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000317 return self._sslobj.peer_certificate(binary_form)
318
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000319 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000320 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321 if not self._sslobj:
322 return None
323 else:
324 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000325
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000326 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000327 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000328 if self._sslobj:
329 if flags != 0:
330 raise ValueError(
331 "non-zero flags not allowed in calls to send() on %s" %
332 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 while True:
334 try:
335 v = self._sslobj.write(data)
336 except SSLError as x:
337 if x.args[0] == SSL_ERROR_WANT_READ:
338 return 0
339 elif x.args[0] == SSL_ERROR_WANT_WRITE:
340 return 0
341 else:
342 raise
343 else:
344 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000345 else:
346 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000347
Antoine Pitroua468adc2010-09-14 14:43:44 +0000348 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000349 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000350 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000351 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000352 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000353 elif addr is None:
354 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000356 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
Nick Coghlan513886a2011-08-28 00:00:27 +1000358 def sendmsg(self, *args, **kwargs):
359 # Ensure programs don't send data unencrypted if they try to
360 # use this method.
361 raise NotImplementedError("sendmsg not allowed on instances of %s" %
362 self.__class__)
363
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000364 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000365 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000366 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000367 if flags != 0:
368 raise ValueError(
369 "non-zero flags not allowed in calls to sendall() on %s" %
370 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000371 amount = len(data)
372 count = 0
373 while (count < amount):
374 v = self.send(data[count:])
375 count += v
376 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000377 else:
378 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000380 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000381 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000382 if self._sslobj:
383 if flags != 0:
384 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000385 "non-zero flags not allowed in calls to recv() on %s" %
386 self.__class__)
387 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000388 else:
389 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000390
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000391 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000392 self._checkClosed()
393 if buffer and (nbytes is None):
394 nbytes = len(buffer)
395 elif nbytes is None:
396 nbytes = 1024
397 if self._sslobj:
398 if flags != 0:
399 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000400 "non-zero flags not allowed in calls to recv_into() on %s" %
401 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000402 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000403 else:
404 return socket.recv_into(self, buffer, nbytes, flags)
405
Antoine Pitroua468adc2010-09-14 14:43:44 +0000406 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000407 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000408 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000409 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000410 self.__class__)
411 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000412 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000413
Bill Janssen58afe4c2008-09-08 16:45:19 +0000414 def recvfrom_into(self, buffer, nbytes=None, flags=0):
415 self._checkClosed()
416 if self._sslobj:
417 raise ValueError("recvfrom_into not allowed on instances of %s" %
418 self.__class__)
419 else:
420 return socket.recvfrom_into(self, buffer, nbytes, flags)
421
Nick Coghlan513886a2011-08-28 00:00:27 +1000422 def recvmsg(self, *args, **kwargs):
423 raise NotImplementedError("recvmsg not allowed on instances of %s" %
424 self.__class__)
425
426 def recvmsg_into(self, *args, **kwargs):
427 raise NotImplementedError("recvmsg_into not allowed on instances of "
428 "%s" % self.__class__)
429
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000430 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000431 self._checkClosed()
432 if self._sslobj:
433 return self._sslobj.pending()
434 else:
435 return 0
436
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000437 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000438 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000439 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000440 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000441
Ezio Melottidc55e672010-01-18 09:15:14 +0000442 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000443 if self._sslobj:
444 s = self._sslobj.shutdown()
445 self._sslobj = None
446 return s
447 else:
448 raise ValueError("No SSL wrapper around " + str(self))
449
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000450 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000452 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000453 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000454
Bill Janssen48dc27c2007-12-05 03:38:10 +0000455 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 """Perform a TLS/SSL handshake."""
457
Bill Janssen48dc27c2007-12-05 03:38:10 +0000458 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000459 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000460 if timeout == 0.0 and block:
461 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000462 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000463 finally:
464 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000465
Antoine Pitroub4410db2011-05-18 18:51:06 +0200466 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000467 if self.server_side:
468 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000469 # Here we assume that the socket is client-side, and not
470 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000471 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000473 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000474 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200475 if connect_ex:
476 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000477 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200478 rc = None
479 socket.connect(self, addr)
480 if not rc:
481 if self.do_handshake_on_connect:
482 self.do_handshake()
483 self._connected = True
484 return rc
485 except socket_error:
486 self._sslobj = None
487 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000488
489 def connect(self, addr):
490 """Connects to remote ADDR, and then wraps the connection in
491 an SSL channel."""
492 self._real_connect(addr, False)
493
494 def connect_ex(self, addr):
495 """Connects to remote ADDR, and then wraps the connection in
496 an SSL channel."""
497 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000498
499 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000500 """Accepts a new connection from a remote client, and returns
501 a tuple containing that new connection wrapped with a server-side
502 SSL channel, and the address of the remote client."""
503
504 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000505 return (SSLSocket(sock=newsock,
506 keyfile=self.keyfile, certfile=self.certfile,
507 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000508 cert_reqs=self.cert_reqs,
509 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000510 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000511 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000512 do_handshake_on_connect=
513 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000514 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Antoine Pitroud6494802011-07-21 01:11:30 +0200516 def get_channel_binding(self, cb_type="tls-unique"):
517 """Get channel binding data for current connection. Raise ValueError
518 if the requested `cb_type` is not supported. Return bytes of the data
519 or None if the data is not available (e.g. before the handshake).
520 """
521 if cb_type not in CHANNEL_BINDING_TYPES:
522 raise ValueError("Unsupported channel binding type")
523 if cb_type != "tls-unique":
524 raise NotImplementedError(
525 "{0} channel binding type not implemented"
526 .format(cb_type))
527 if self._sslobj is None:
528 return None
529 return self._sslobj.tls_unique_cb()
530
Guido van Rossume6650f92007-12-06 19:05:55 +0000531 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000532 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000533 self._real_close()
534
Bill Janssen54cc54c2007-12-14 22:08:56 +0000535
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536def wrap_socket(sock, keyfile=None, certfile=None,
537 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000538 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000539 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000540 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Bill Janssen6e027db2007-11-15 22:23:56 +0000542 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000544 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000545 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000546 suppress_ragged_eofs=suppress_ragged_eofs,
547 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Thomas Woutersed03b412007-08-28 21:37:11 +0000549# some utility functions
550
551def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000552 """Takes a date-time string in standard ASN1_print form
553 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
554 a Python time value in seconds past the epoch."""
555
Thomas Woutersed03b412007-08-28 21:37:11 +0000556 import time
557 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
558
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559PEM_HEADER = "-----BEGIN CERTIFICATE-----"
560PEM_FOOTER = "-----END CERTIFICATE-----"
561
562def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 """Takes a certificate in binary DER format and returns the
564 PEM version of it as a string."""
565
Bill Janssen6e027db2007-11-15 22:23:56 +0000566 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
567 return (PEM_HEADER + '\n' +
568 textwrap.fill(f, 64) + '\n' +
569 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
571def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572 """Takes a certificate in ASCII PEM format and returns the
573 DER-encoded version of it as a byte sequence"""
574
575 if not pem_cert_string.startswith(PEM_HEADER):
576 raise ValueError("Invalid PEM encoding; must start with %s"
577 % PEM_HEADER)
578 if not pem_cert_string.strip().endswith(PEM_FOOTER):
579 raise ValueError("Invalid PEM encoding; must end with %s"
580 % PEM_FOOTER)
581 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000582 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000584def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585 """Retrieve the certificate from the server at the specified address,
586 and return it as a PEM-encoded string.
587 If 'ca_certs' is specified, validate the server cert against it.
588 If 'ssl_version' is specified, use it in the connection attempt."""
589
590 host, port = addr
591 if (ca_certs is not None):
592 cert_reqs = CERT_REQUIRED
593 else:
594 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200595 s = create_connection(addr)
596 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598 dercert = s.getpeercert(True)
599 s.close()
600 return DER_cert_to_PEM_cert(dercert)
601
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000602def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200603 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')