blob: 0282ee924a092e61af185b1c8c94ce15c1604797 [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 Pitrou0e576f12011-12-22 10:03:38 +010071 OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, 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 Pitrou501da612011-12-21 09:27:41 +010089from _ssl import HAS_SNI, HAS_ECDH
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
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100101 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinner3de49192011-05-09 00:42:58 +0200102except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100103 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200104else:
105 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000106
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000107from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +0000108from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +0200109from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000110import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000111import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000112import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000113
Antoine Pitroud6494802011-07-21 01:11:30 +0200114if _ssl.HAS_TLS_UNIQUE:
115 CHANNEL_BINDING_TYPES = ['tls-unique']
116else:
117 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000118
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100119# Disable weak or insecure ciphers by default
120# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
121_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
122
Thomas Woutersed03b412007-08-28 21:37:11 +0000123
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000124class CertificateError(ValueError):
125 pass
126
127
128def _dnsname_to_pat(dn):
129 pats = []
130 for frag in dn.split(r'.'):
131 if frag == '*':
132 # When '*' is a fragment by itself, it matches a non-empty dotless
133 # fragment.
134 pats.append('[^.]+')
135 else:
136 # Otherwise, '*' matches any dotless fragment.
137 frag = re.escape(frag)
138 pats.append(frag.replace(r'\*', '[^.]*'))
139 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
140
141
142def match_hostname(cert, hostname):
143 """Verify that *cert* (in decoded format as returned by
144 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
145 are mostly followed, but IP addresses are not accepted for *hostname*.
146
147 CertificateError is raised on failure. On success, the function
148 returns nothing.
149 """
150 if not cert:
151 raise ValueError("empty or no certificate")
152 dnsnames = []
153 san = cert.get('subjectAltName', ())
154 for key, value in san:
155 if key == 'DNS':
156 if _dnsname_to_pat(value).match(hostname):
157 return
158 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200159 if not dnsnames:
160 # The subject is only checked when there is no dNSName entry
161 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000162 for sub in cert.get('subject', ()):
163 for key, value in sub:
164 # XXX according to RFC 2818, the most specific Common Name
165 # must be used.
166 if key == 'commonName':
167 if _dnsname_to_pat(value).match(hostname):
168 return
169 dnsnames.append(value)
170 if len(dnsnames) > 1:
171 raise CertificateError("hostname %r "
172 "doesn't match either of %s"
173 % (hostname, ', '.join(map(repr, dnsnames))))
174 elif len(dnsnames) == 1:
175 raise CertificateError("hostname %r "
176 "doesn't match %r"
177 % (hostname, dnsnames[0]))
178 else:
179 raise CertificateError("no appropriate commonName or "
180 "subjectAltName fields were found")
181
182
Antoine Pitrou152efa22010-05-16 18:19:27 +0000183class SSLContext(_SSLContext):
184 """An SSLContext holds various SSL-related configuration options and
185 data, such as certificates and possibly a private key."""
186
187 __slots__ = ('protocol',)
188
189 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100190 self = _SSLContext.__new__(cls, protocol)
191 if protocol != _SSLv2_IF_EXISTS:
192 self.set_ciphers(_DEFAULT_CIPHERS)
193 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194
195 def __init__(self, protocol):
196 self.protocol = protocol
197
198 def wrap_socket(self, sock, server_side=False,
199 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000200 suppress_ragged_eofs=True,
201 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202 return SSLSocket(sock=sock, server_side=server_side,
203 do_handshake_on_connect=do_handshake_on_connect,
204 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000205 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 _context=self)
207
208
209class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000210 """This class implements a subtype of socket.socket that wraps
211 the underlying OS socket in an SSL context when necessary, and
212 provides read and write methods over that channel."""
213
Bill Janssen6e027db2007-11-15 22:23:56 +0000214 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000215 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000216 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
217 do_handshake_on_connect=True,
218 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000220 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000221 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000222
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223 if _context:
224 self.context = _context
225 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000226 if server_side and not certfile:
227 raise ValueError("certfile must be specified for server-side "
228 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000229 if keyfile and not certfile:
230 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000231 if certfile and not keyfile:
232 keyfile = certfile
233 self.context = SSLContext(ssl_version)
234 self.context.verify_mode = cert_reqs
235 if ca_certs:
236 self.context.load_verify_locations(ca_certs)
237 if certfile:
238 self.context.load_cert_chain(certfile, keyfile)
239 if ciphers:
240 self.context.set_ciphers(ciphers)
241 self.keyfile = keyfile
242 self.certfile = certfile
243 self.cert_reqs = cert_reqs
244 self.ssl_version = ssl_version
245 self.ca_certs = ca_certs
246 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000247 if server_side and server_hostname:
248 raise ValueError("server_hostname can only be specified "
249 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000250 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000251 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000252 self.do_handshake_on_connect = do_handshake_on_connect
253 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000254 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000255 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000256 socket.__init__(self,
257 family=sock.family,
258 type=sock.type,
259 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000260 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000261 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000262 # see if it's connected
263 try:
264 sock.getpeername()
265 except socket_error as e:
266 if e.errno != errno.ENOTCONN:
267 raise
268 else:
269 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000270 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000271 elif fileno is not None:
272 socket.__init__(self, fileno=fileno)
273 else:
274 socket.__init__(self, family=family, type=type, proto=proto)
275
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000276 self._closed = False
277 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000278 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000279 if connected:
280 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000281 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000282 self._sslobj = self.context._wrap_socket(self, server_side,
283 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000284 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000285 timeout = self.gettimeout()
286 if timeout == 0.0:
287 # non-blocking
288 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000290
Bill Janssen6e027db2007-11-15 22:23:56 +0000291 except socket_error as x:
292 self.close()
293 raise x
294
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000295 def dup(self):
296 raise NotImplemented("Can't dup() %s instances" %
297 self.__class__.__name__)
298
Bill Janssen6e027db2007-11-15 22:23:56 +0000299 def _checkClosed(self, msg=None):
300 # raise an exception here if you wish to check for spurious closes
301 pass
302
Bill Janssen54cc54c2007-12-14 22:08:56 +0000303 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000304 """Read up to LEN bytes and return them.
305 Return zero-length string on EOF."""
306
Bill Janssen6e027db2007-11-15 22:23:56 +0000307 self._checkClosed()
308 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000309 if buffer is not None:
310 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000311 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000312 v = self._sslobj.read(len or 1024)
313 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000314 except SSLError as x:
315 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000316 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000317 return 0
318 else:
319 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000320 else:
321 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000322
323 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000324 """Write DATA to the underlying SSL channel. Returns
325 number of bytes of DATA actually transmitted."""
326
Bill Janssen6e027db2007-11-15 22:23:56 +0000327 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 return self._sslobj.write(data)
329
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000331 """Returns a formatted version of the data in the
332 certificate provided by the other end of the SSL channel.
333 Return None if no certificate was provided, {} if a
334 certificate was provided, but not validated."""
335
Bill Janssen6e027db2007-11-15 22:23:56 +0000336 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000337 return self._sslobj.peer_certificate(binary_form)
338
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000339 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000340 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000341 if not self._sslobj:
342 return None
343 else:
344 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000345
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100346 def compression(self):
347 self._checkClosed()
348 if not self._sslobj:
349 return None
350 else:
351 return self._sslobj.compression()
352
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000353 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000354 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 if self._sslobj:
356 if flags != 0:
357 raise ValueError(
358 "non-zero flags not allowed in calls to send() on %s" %
359 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000360 while True:
361 try:
362 v = self._sslobj.write(data)
363 except SSLError as x:
364 if x.args[0] == SSL_ERROR_WANT_READ:
365 return 0
366 elif x.args[0] == SSL_ERROR_WANT_WRITE:
367 return 0
368 else:
369 raise
370 else:
371 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000372 else:
373 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
Antoine Pitroua468adc2010-09-14 14:43:44 +0000375 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000376 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000377 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000378 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000379 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000380 elif addr is None:
381 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000382 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000383 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000384
Nick Coghlan513886a2011-08-28 00:00:27 +1000385 def sendmsg(self, *args, **kwargs):
386 # Ensure programs don't send data unencrypted if they try to
387 # use this method.
388 raise NotImplementedError("sendmsg not allowed on instances of %s" %
389 self.__class__)
390
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000391 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000392 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000393 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000394 if flags != 0:
395 raise ValueError(
396 "non-zero flags not allowed in calls to sendall() on %s" %
397 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000398 amount = len(data)
399 count = 0
400 while (count < amount):
401 v = self.send(data[count:])
402 count += v
403 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000404 else:
405 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000406
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000407 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000408 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000409 if self._sslobj:
410 if flags != 0:
411 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000412 "non-zero flags not allowed in calls to recv() on %s" %
413 self.__class__)
414 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000415 else:
416 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000417
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000418 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000419 self._checkClosed()
420 if buffer and (nbytes is None):
421 nbytes = len(buffer)
422 elif nbytes is None:
423 nbytes = 1024
424 if self._sslobj:
425 if flags != 0:
426 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000427 "non-zero flags not allowed in calls to recv_into() on %s" %
428 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000429 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000430 else:
431 return socket.recv_into(self, buffer, nbytes, flags)
432
Antoine Pitroua468adc2010-09-14 14:43:44 +0000433 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000434 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000435 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000436 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000437 self.__class__)
438 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000439 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000440
Bill Janssen58afe4c2008-09-08 16:45:19 +0000441 def recvfrom_into(self, buffer, nbytes=None, flags=0):
442 self._checkClosed()
443 if self._sslobj:
444 raise ValueError("recvfrom_into not allowed on instances of %s" %
445 self.__class__)
446 else:
447 return socket.recvfrom_into(self, buffer, nbytes, flags)
448
Nick Coghlan513886a2011-08-28 00:00:27 +1000449 def recvmsg(self, *args, **kwargs):
450 raise NotImplementedError("recvmsg not allowed on instances of %s" %
451 self.__class__)
452
453 def recvmsg_into(self, *args, **kwargs):
454 raise NotImplementedError("recvmsg_into not allowed on instances of "
455 "%s" % self.__class__)
456
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000457 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000458 self._checkClosed()
459 if self._sslobj:
460 return self._sslobj.pending()
461 else:
462 return 0
463
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000464 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000465 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000467 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000468
Ezio Melottidc55e672010-01-18 09:15:14 +0000469 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000470 if self._sslobj:
471 s = self._sslobj.shutdown()
472 self._sslobj = None
473 return s
474 else:
475 raise ValueError("No SSL wrapper around " + str(self))
476
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000477 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000479 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000480 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000481
Bill Janssen48dc27c2007-12-05 03:38:10 +0000482 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000483 """Perform a TLS/SSL handshake."""
484
Bill Janssen48dc27c2007-12-05 03:38:10 +0000485 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000486 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000487 if timeout == 0.0 and block:
488 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000489 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000490 finally:
491 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000492
Antoine Pitroub4410db2011-05-18 18:51:06 +0200493 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000494 if self.server_side:
495 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000496 # Here we assume that the socket is client-side, and not
497 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000498 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000500 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000501 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200502 if connect_ex:
503 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000504 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200505 rc = None
506 socket.connect(self, addr)
507 if not rc:
508 if self.do_handshake_on_connect:
509 self.do_handshake()
510 self._connected = True
511 return rc
512 except socket_error:
513 self._sslobj = None
514 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000515
516 def connect(self, addr):
517 """Connects to remote ADDR, and then wraps the connection in
518 an SSL channel."""
519 self._real_connect(addr, False)
520
521 def connect_ex(self, addr):
522 """Connects to remote ADDR, and then wraps the connection in
523 an SSL channel."""
524 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000525
526 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000527 """Accepts a new connection from a remote client, and returns
528 a tuple containing that new connection wrapped with a server-side
529 SSL channel, and the address of the remote client."""
530
531 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000532 return (SSLSocket(sock=newsock,
533 keyfile=self.keyfile, certfile=self.certfile,
534 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000535 cert_reqs=self.cert_reqs,
536 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000537 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000538 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000539 do_handshake_on_connect=
540 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000541 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
Antoine Pitroud6494802011-07-21 01:11:30 +0200543 def get_channel_binding(self, cb_type="tls-unique"):
544 """Get channel binding data for current connection. Raise ValueError
545 if the requested `cb_type` is not supported. Return bytes of the data
546 or None if the data is not available (e.g. before the handshake).
547 """
548 if cb_type not in CHANNEL_BINDING_TYPES:
549 raise ValueError("Unsupported channel binding type")
550 if cb_type != "tls-unique":
551 raise NotImplementedError(
552 "{0} channel binding type not implemented"
553 .format(cb_type))
554 if self._sslobj is None:
555 return None
556 return self._sslobj.tls_unique_cb()
557
Guido van Rossume6650f92007-12-06 19:05:55 +0000558 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000559 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000560 self._real_close()
561
Bill Janssen54cc54c2007-12-14 22:08:56 +0000562
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563def wrap_socket(sock, keyfile=None, certfile=None,
564 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000565 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000566 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000567 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Bill Janssen6e027db2007-11-15 22:23:56 +0000569 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000571 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000572 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000573 suppress_ragged_eofs=suppress_ragged_eofs,
574 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000575
Thomas Woutersed03b412007-08-28 21:37:11 +0000576# some utility functions
577
578def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000579 """Takes a date-time string in standard ASN1_print form
580 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
581 a Python time value in seconds past the epoch."""
582
Thomas Woutersed03b412007-08-28 21:37:11 +0000583 import time
584 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
585
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586PEM_HEADER = "-----BEGIN CERTIFICATE-----"
587PEM_FOOTER = "-----END CERTIFICATE-----"
588
589def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590 """Takes a certificate in binary DER format and returns the
591 PEM version of it as a string."""
592
Bill Janssen6e027db2007-11-15 22:23:56 +0000593 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
594 return (PEM_HEADER + '\n' +
595 textwrap.fill(f, 64) + '\n' +
596 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
598def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599 """Takes a certificate in ASCII PEM format and returns the
600 DER-encoded version of it as a byte sequence"""
601
602 if not pem_cert_string.startswith(PEM_HEADER):
603 raise ValueError("Invalid PEM encoding; must start with %s"
604 % PEM_HEADER)
605 if not pem_cert_string.strip().endswith(PEM_FOOTER):
606 raise ValueError("Invalid PEM encoding; must end with %s"
607 % PEM_FOOTER)
608 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000609 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000611def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612 """Retrieve the certificate from the server at the specified address,
613 and return it as a PEM-encoded string.
614 If 'ca_certs' is specified, validate the server cert against it.
615 If 'ssl_version' is specified, use it in the connection attempt."""
616
617 host, port = addr
618 if (ca_certs is not None):
619 cert_reqs = CERT_REQUIRED
620 else:
621 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200622 s = create_connection(addr)
623 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625 dercert = s.getpeercert(True)
626 s.close()
627 return DER_cert_to_PEM_cert(dercert)
628
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000629def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200630 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')