blob: 0b2f743f227971197699cde7fa534a7775010c9a [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 Pitrou41032a62011-10-27 23:56:55 +020063from _ssl import _SSLContext
64from _ssl import (
65 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
66 SSLSyscallError, SSLEOFError,
67 )
Thomas Woutersed03b412007-08-28 21:37:11 +000068from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Antoine Pitrou6db49442011-12-19 13:27:11 +010069from _ssl import (
70 OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1,
Antoine Pitrou923df6f2011-12-19 17:16:51 +010071 OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_ECDH_USE,
Antoine Pitrou6db49442011-12-19 13:27:11 +010072 )
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +010073try:
74 from _ssl import OP_NO_COMPRESSION
75except ImportError:
76 pass
Victor Stinner99c8b162011-05-24 12:05:19 +020077from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Guido van Rossum5b8b1552007-11-16 00:06:11 +000078from _ssl import (
79 SSL_ERROR_ZERO_RETURN,
80 SSL_ERROR_WANT_READ,
81 SSL_ERROR_WANT_WRITE,
82 SSL_ERROR_WANT_X509_LOOKUP,
83 SSL_ERROR_SYSCALL,
84 SSL_ERROR_SSL,
85 SSL_ERROR_WANT_CONNECT,
86 SSL_ERROR_EOF,
87 SSL_ERROR_INVALID_ERROR_CODE,
88 )
Antoine Pitroud5323212010-10-22 18:19:07 +000089from _ssl import HAS_SNI
Victor Stinner3de49192011-05-09 00:42:58 +020090from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
91 PROTOCOL_TLSv1)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020092from _ssl import _OPENSSL_API_VERSION
93
Victor Stinner3de49192011-05-09 00:42:58 +020094_PROTOCOL_NAMES = {
95 PROTOCOL_TLSv1: "TLSv1",
96 PROTOCOL_SSLv23: "SSLv23",
97 PROTOCOL_SSLv3: "SSLv3",
98}
99try:
100 from _ssl import PROTOCOL_SSLv2
101except ImportError:
102 pass
103else:
104 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000105
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000106from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +0000107from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +0200108from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000110import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000111import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000112
Antoine Pitroud6494802011-07-21 01:11:30 +0200113if _ssl.HAS_TLS_UNIQUE:
114 CHANNEL_BINDING_TYPES = ['tls-unique']
115else:
116 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000117
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000118class CertificateError(ValueError):
119 pass
120
121
122def _dnsname_to_pat(dn):
123 pats = []
124 for frag in dn.split(r'.'):
125 if frag == '*':
126 # When '*' is a fragment by itself, it matches a non-empty dotless
127 # fragment.
128 pats.append('[^.]+')
129 else:
130 # Otherwise, '*' matches any dotless fragment.
131 frag = re.escape(frag)
132 pats.append(frag.replace(r'\*', '[^.]*'))
133 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
134
135
136def match_hostname(cert, hostname):
137 """Verify that *cert* (in decoded format as returned by
138 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
139 are mostly followed, but IP addresses are not accepted for *hostname*.
140
141 CertificateError is raised on failure. On success, the function
142 returns nothing.
143 """
144 if not cert:
145 raise ValueError("empty or no certificate")
146 dnsnames = []
147 san = cert.get('subjectAltName', ())
148 for key, value in san:
149 if key == 'DNS':
150 if _dnsname_to_pat(value).match(hostname):
151 return
152 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200153 if not dnsnames:
154 # The subject is only checked when there is no dNSName entry
155 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000156 for sub in cert.get('subject', ()):
157 for key, value in sub:
158 # XXX according to RFC 2818, the most specific Common Name
159 # must be used.
160 if key == 'commonName':
161 if _dnsname_to_pat(value).match(hostname):
162 return
163 dnsnames.append(value)
164 if len(dnsnames) > 1:
165 raise CertificateError("hostname %r "
166 "doesn't match either of %s"
167 % (hostname, ', '.join(map(repr, dnsnames))))
168 elif len(dnsnames) == 1:
169 raise CertificateError("hostname %r "
170 "doesn't match %r"
171 % (hostname, dnsnames[0]))
172 else:
173 raise CertificateError("no appropriate commonName or "
174 "subjectAltName fields were found")
175
176
Antoine Pitrou152efa22010-05-16 18:19:27 +0000177class SSLContext(_SSLContext):
178 """An SSLContext holds various SSL-related configuration options and
179 data, such as certificates and possibly a private key."""
180
181 __slots__ = ('protocol',)
182
183 def __new__(cls, protocol, *args, **kwargs):
184 return _SSLContext.__new__(cls, protocol)
185
186 def __init__(self, protocol):
187 self.protocol = protocol
188
189 def wrap_socket(self, sock, server_side=False,
190 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000191 suppress_ragged_eofs=True,
192 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000193 return SSLSocket(sock=sock, server_side=server_side,
194 do_handshake_on_connect=do_handshake_on_connect,
195 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000196 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197 _context=self)
198
199
200class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000201 """This class implements a subtype of socket.socket that wraps
202 the underlying OS socket in an SSL context when necessary, and
203 provides read and write methods over that channel."""
204
Bill Janssen6e027db2007-11-15 22:23:56 +0000205 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000206 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000207 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
208 do_handshake_on_connect=True,
209 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000211 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000213
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214 if _context:
215 self.context = _context
216 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000217 if server_side and not certfile:
218 raise ValueError("certfile must be specified for server-side "
219 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000220 if keyfile and not certfile:
221 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222 if certfile and not keyfile:
223 keyfile = certfile
224 self.context = SSLContext(ssl_version)
225 self.context.verify_mode = cert_reqs
226 if ca_certs:
227 self.context.load_verify_locations(ca_certs)
228 if certfile:
229 self.context.load_cert_chain(certfile, keyfile)
230 if ciphers:
231 self.context.set_ciphers(ciphers)
232 self.keyfile = keyfile
233 self.certfile = certfile
234 self.cert_reqs = cert_reqs
235 self.ssl_version = ssl_version
236 self.ca_certs = ca_certs
237 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000238 if server_side and server_hostname:
239 raise ValueError("server_hostname can only be specified "
240 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000241 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000242 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000243 self.do_handshake_on_connect = do_handshake_on_connect
244 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000245 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000246 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000247 socket.__init__(self,
248 family=sock.family,
249 type=sock.type,
250 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000251 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000252 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000253 # see if it's connected
254 try:
255 sock.getpeername()
256 except socket_error as e:
257 if e.errno != errno.ENOTCONN:
258 raise
259 else:
260 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000261 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000262 elif fileno is not None:
263 socket.__init__(self, fileno=fileno)
264 else:
265 socket.__init__(self, family=family, type=type, proto=proto)
266
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000267 self._closed = False
268 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000269 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000270 if connected:
271 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000273 self._sslobj = self.context._wrap_socket(self, server_side,
274 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000275 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000276 timeout = self.gettimeout()
277 if timeout == 0.0:
278 # non-blocking
279 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000280 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000281
Bill Janssen6e027db2007-11-15 22:23:56 +0000282 except socket_error as x:
283 self.close()
284 raise x
285
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000286 def dup(self):
287 raise NotImplemented("Can't dup() %s instances" %
288 self.__class__.__name__)
289
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 def _checkClosed(self, msg=None):
291 # raise an exception here if you wish to check for spurious closes
292 pass
293
Bill Janssen54cc54c2007-12-14 22:08:56 +0000294 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000295 """Read up to LEN bytes and return them.
296 Return zero-length string on EOF."""
297
Bill Janssen6e027db2007-11-15 22:23:56 +0000298 self._checkClosed()
299 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000300 if buffer is not None:
301 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000302 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000303 v = self._sslobj.read(len or 1024)
304 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000305 except SSLError as x:
306 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000307 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000308 return 0
309 else:
310 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000311 else:
312 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000313
314 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000315 """Write DATA to the underlying SSL channel. Returns
316 number of bytes of DATA actually transmitted."""
317
Bill Janssen6e027db2007-11-15 22:23:56 +0000318 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000319 return self._sslobj.write(data)
320
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000322 """Returns a formatted version of the data in the
323 certificate provided by the other end of the SSL channel.
324 Return None if no certificate was provided, {} if a
325 certificate was provided, but not validated."""
326
Bill Janssen6e027db2007-11-15 22:23:56 +0000327 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000328 return self._sslobj.peer_certificate(binary_form)
329
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000330 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000331 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000332 if not self._sslobj:
333 return None
334 else:
335 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100337 def compression(self):
338 self._checkClosed()
339 if not self._sslobj:
340 return None
341 else:
342 return self._sslobj.compression()
343
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000344 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000346 if self._sslobj:
347 if flags != 0:
348 raise ValueError(
349 "non-zero flags not allowed in calls to send() on %s" %
350 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 while True:
352 try:
353 v = self._sslobj.write(data)
354 except SSLError as x:
355 if x.args[0] == SSL_ERROR_WANT_READ:
356 return 0
357 elif x.args[0] == SSL_ERROR_WANT_WRITE:
358 return 0
359 else:
360 raise
361 else:
362 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000363 else:
364 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000365
Antoine Pitroua468adc2010-09-14 14:43:44 +0000366 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000367 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000368 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000369 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000370 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000371 elif addr is None:
372 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000373 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000374 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000375
Nick Coghlan513886a2011-08-28 00:00:27 +1000376 def sendmsg(self, *args, **kwargs):
377 # Ensure programs don't send data unencrypted if they try to
378 # use this method.
379 raise NotImplementedError("sendmsg not allowed on instances of %s" %
380 self.__class__)
381
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000382 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000383 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000384 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000385 if flags != 0:
386 raise ValueError(
387 "non-zero flags not allowed in calls to sendall() on %s" %
388 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 amount = len(data)
390 count = 0
391 while (count < amount):
392 v = self.send(data[count:])
393 count += v
394 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000395 else:
396 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000397
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000398 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000399 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000400 if self._sslobj:
401 if flags != 0:
402 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000403 "non-zero flags not allowed in calls to recv() on %s" %
404 self.__class__)
405 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000406 else:
407 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000408
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000409 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000410 self._checkClosed()
411 if buffer and (nbytes is None):
412 nbytes = len(buffer)
413 elif nbytes is None:
414 nbytes = 1024
415 if self._sslobj:
416 if flags != 0:
417 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000418 "non-zero flags not allowed in calls to recv_into() on %s" %
419 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000420 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000421 else:
422 return socket.recv_into(self, buffer, nbytes, flags)
423
Antoine Pitroua468adc2010-09-14 14:43:44 +0000424 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000425 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000426 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000427 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000428 self.__class__)
429 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000430 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000431
Bill Janssen58afe4c2008-09-08 16:45:19 +0000432 def recvfrom_into(self, buffer, nbytes=None, flags=0):
433 self._checkClosed()
434 if self._sslobj:
435 raise ValueError("recvfrom_into not allowed on instances of %s" %
436 self.__class__)
437 else:
438 return socket.recvfrom_into(self, buffer, nbytes, flags)
439
Nick Coghlan513886a2011-08-28 00:00:27 +1000440 def recvmsg(self, *args, **kwargs):
441 raise NotImplementedError("recvmsg not allowed on instances of %s" %
442 self.__class__)
443
444 def recvmsg_into(self, *args, **kwargs):
445 raise NotImplementedError("recvmsg_into not allowed on instances of "
446 "%s" % self.__class__)
447
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000448 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000449 self._checkClosed()
450 if self._sslobj:
451 return self._sslobj.pending()
452 else:
453 return 0
454
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000455 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000458 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000459
Ezio Melottidc55e672010-01-18 09:15:14 +0000460 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000461 if self._sslobj:
462 s = self._sslobj.shutdown()
463 self._sslobj = None
464 return s
465 else:
466 raise ValueError("No SSL wrapper around " + str(self))
467
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000468 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000469 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000470 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000471 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000472
Bill Janssen48dc27c2007-12-05 03:38:10 +0000473 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000474 """Perform a TLS/SSL handshake."""
475
Bill Janssen48dc27c2007-12-05 03:38:10 +0000476 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000477 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000478 if timeout == 0.0 and block:
479 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000480 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000481 finally:
482 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000483
Antoine Pitroub4410db2011-05-18 18:51:06 +0200484 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000485 if self.server_side:
486 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000487 # Here we assume that the socket is client-side, and not
488 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000489 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000491 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000492 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200493 if connect_ex:
494 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000495 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200496 rc = None
497 socket.connect(self, addr)
498 if not rc:
499 if self.do_handshake_on_connect:
500 self.do_handshake()
501 self._connected = True
502 return rc
503 except socket_error:
504 self._sslobj = None
505 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000506
507 def connect(self, addr):
508 """Connects to remote ADDR, and then wraps the connection in
509 an SSL channel."""
510 self._real_connect(addr, False)
511
512 def connect_ex(self, addr):
513 """Connects to remote ADDR, and then wraps the connection in
514 an SSL channel."""
515 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000516
517 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000518 """Accepts a new connection from a remote client, and returns
519 a tuple containing that new connection wrapped with a server-side
520 SSL channel, and the address of the remote client."""
521
522 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000523 return (SSLSocket(sock=newsock,
524 keyfile=self.keyfile, certfile=self.certfile,
525 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000526 cert_reqs=self.cert_reqs,
527 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000528 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000529 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000530 do_handshake_on_connect=
531 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000532 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000533
Antoine Pitroud6494802011-07-21 01:11:30 +0200534 def get_channel_binding(self, cb_type="tls-unique"):
535 """Get channel binding data for current connection. Raise ValueError
536 if the requested `cb_type` is not supported. Return bytes of the data
537 or None if the data is not available (e.g. before the handshake).
538 """
539 if cb_type not in CHANNEL_BINDING_TYPES:
540 raise ValueError("Unsupported channel binding type")
541 if cb_type != "tls-unique":
542 raise NotImplementedError(
543 "{0} channel binding type not implemented"
544 .format(cb_type))
545 if self._sslobj is None:
546 return None
547 return self._sslobj.tls_unique_cb()
548
Guido van Rossume6650f92007-12-06 19:05:55 +0000549 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000550 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000551 self._real_close()
552
Bill Janssen54cc54c2007-12-14 22:08:56 +0000553
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554def wrap_socket(sock, keyfile=None, certfile=None,
555 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000556 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000557 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000558 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Bill Janssen6e027db2007-11-15 22:23:56 +0000560 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000562 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000563 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000564 suppress_ragged_eofs=suppress_ragged_eofs,
565 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Thomas Woutersed03b412007-08-28 21:37:11 +0000567# some utility functions
568
569def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000570 """Takes a date-time string in standard ASN1_print form
571 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
572 a Python time value in seconds past the epoch."""
573
Thomas Woutersed03b412007-08-28 21:37:11 +0000574 import time
575 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
576
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577PEM_HEADER = "-----BEGIN CERTIFICATE-----"
578PEM_FOOTER = "-----END CERTIFICATE-----"
579
580def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581 """Takes a certificate in binary DER format and returns the
582 PEM version of it as a string."""
583
Bill Janssen6e027db2007-11-15 22:23:56 +0000584 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
585 return (PEM_HEADER + '\n' +
586 textwrap.fill(f, 64) + '\n' +
587 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
589def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590 """Takes a certificate in ASCII PEM format and returns the
591 DER-encoded version of it as a byte sequence"""
592
593 if not pem_cert_string.startswith(PEM_HEADER):
594 raise ValueError("Invalid PEM encoding; must start with %s"
595 % PEM_HEADER)
596 if not pem_cert_string.strip().endswith(PEM_FOOTER):
597 raise ValueError("Invalid PEM encoding; must end with %s"
598 % PEM_FOOTER)
599 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000600 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000602def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603 """Retrieve the certificate from the server at the specified address,
604 and return it as a PEM-encoded string.
605 If 'ca_certs' is specified, validate the server cert against it.
606 If 'ssl_version' is specified, use it in the connection attempt."""
607
608 host, port = addr
609 if (ca_certs is not None):
610 cert_reqs = CERT_REQUIRED
611 else:
612 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200613 s = create_connection(addr)
614 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616 dercert = s.getpeercert(True)
617 s.close()
618 return DER_cert_to_PEM_cert(dercert)
619
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000620def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200621 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')