blob: 30ee13b20700acb4796fa0cee231bb31f5c0d282 [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 Pitroua9bf2ac2012-02-17 18:47:54 +010071 OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_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
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +010077try:
78 from _ssl import OP_SINGLE_ECDH_USE
79except ImportError:
80 pass
Victor Stinner99c8b162011-05-24 12:05:19 +020081from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Guido van Rossum5b8b1552007-11-16 00:06:11 +000082from _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 Pitroud5d17eb2012-03-22 00:23:03 +010093from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Victor Stinner3de49192011-05-09 00:42:58 +020094from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
95 PROTOCOL_TLSv1)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020096from _ssl import _OPENSSL_API_VERSION
97
Victor Stinner3de49192011-05-09 00:42:58 +020098_PROTOCOL_NAMES = {
99 PROTOCOL_TLSv1: "TLSv1",
100 PROTOCOL_SSLv23: "SSLv23",
101 PROTOCOL_SSLv3: "SSLv3",
102}
103try:
104 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100105 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinner3de49192011-05-09 00:42:58 +0200106except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100107 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200108else:
109 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000110
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000111from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +0000112from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +0200113from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000114import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000115import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000116import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000117
Antoine Pitroud6494802011-07-21 01:11:30 +0200118if _ssl.HAS_TLS_UNIQUE:
119 CHANNEL_BINDING_TYPES = ['tls-unique']
120else:
121 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000122
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100123# Disable weak or insecure ciphers by default
124# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
125_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
126
Thomas Woutersed03b412007-08-28 21:37:11 +0000127
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000128class CertificateError(ValueError):
129 pass
130
131
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200132def _dnsname_to_pat(dn, max_wildcards=1):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000133 pats = []
134 for frag in dn.split(r'.'):
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200135 if frag.count('*') > max_wildcards:
136 # Issue #17980: avoid denials of service by refusing more
137 # than one wildcard per fragment. A survery of established
138 # policy among SSL implementations showed it to be a
139 # reasonable choice.
140 raise CertificateError(
141 "too many wildcards in certificate DNS name: " + repr(dn))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000142 if frag == '*':
143 # When '*' is a fragment by itself, it matches a non-empty dotless
144 # fragment.
145 pats.append('[^.]+')
146 else:
147 # Otherwise, '*' matches any dotless fragment.
148 frag = re.escape(frag)
149 pats.append(frag.replace(r'\*', '[^.]*'))
150 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
151
152
153def match_hostname(cert, hostname):
154 """Verify that *cert* (in decoded format as returned by
155 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
156 are mostly followed, but IP addresses are not accepted for *hostname*.
157
158 CertificateError is raised on failure. On success, the function
159 returns nothing.
160 """
161 if not cert:
162 raise ValueError("empty or no certificate")
163 dnsnames = []
164 san = cert.get('subjectAltName', ())
165 for key, value in san:
166 if key == 'DNS':
167 if _dnsname_to_pat(value).match(hostname):
168 return
169 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200170 if not dnsnames:
171 # The subject is only checked when there is no dNSName entry
172 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000173 for sub in cert.get('subject', ()):
174 for key, value in sub:
175 # XXX according to RFC 2818, the most specific Common Name
176 # must be used.
177 if key == 'commonName':
178 if _dnsname_to_pat(value).match(hostname):
179 return
180 dnsnames.append(value)
181 if len(dnsnames) > 1:
182 raise CertificateError("hostname %r "
183 "doesn't match either of %s"
184 % (hostname, ', '.join(map(repr, dnsnames))))
185 elif len(dnsnames) == 1:
186 raise CertificateError("hostname %r "
187 "doesn't match %r"
188 % (hostname, dnsnames[0]))
189 else:
190 raise CertificateError("no appropriate commonName or "
191 "subjectAltName fields were found")
192
193
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194class SSLContext(_SSLContext):
195 """An SSLContext holds various SSL-related configuration options and
196 data, such as certificates and possibly a private key."""
197
198 __slots__ = ('protocol',)
199
200 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100201 self = _SSLContext.__new__(cls, protocol)
202 if protocol != _SSLv2_IF_EXISTS:
203 self.set_ciphers(_DEFAULT_CIPHERS)
204 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000205
206 def __init__(self, protocol):
207 self.protocol = protocol
208
209 def wrap_socket(self, sock, server_side=False,
210 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000211 suppress_ragged_eofs=True,
212 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000213 return SSLSocket(sock=sock, server_side=server_side,
214 do_handshake_on_connect=do_handshake_on_connect,
215 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000216 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000217 _context=self)
218
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100219 def set_npn_protocols(self, npn_protocols):
220 protos = bytearray()
221 for protocol in npn_protocols:
222 b = bytes(protocol, 'ascii')
223 if len(b) == 0 or len(b) > 255:
224 raise SSLError('NPN protocols must be 1 to 255 in length')
225 protos.append(len(b))
226 protos.extend(b)
227
228 self._set_npn_protocols(protos)
229
Antoine Pitrou152efa22010-05-16 18:19:27 +0000230
231class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000232 """This class implements a subtype of socket.socket that wraps
233 the underlying OS socket in an SSL context when necessary, and
234 provides read and write methods over that channel."""
235
Bill Janssen6e027db2007-11-15 22:23:56 +0000236 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000237 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000238 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
239 do_handshake_on_connect=True,
240 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100241 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000242 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000243 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000244
Antoine Pitrou152efa22010-05-16 18:19:27 +0000245 if _context:
246 self.context = _context
247 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000248 if server_side and not certfile:
249 raise ValueError("certfile must be specified for server-side "
250 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000251 if keyfile and not certfile:
252 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000253 if certfile and not keyfile:
254 keyfile = certfile
255 self.context = SSLContext(ssl_version)
256 self.context.verify_mode = cert_reqs
257 if ca_certs:
258 self.context.load_verify_locations(ca_certs)
259 if certfile:
260 self.context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100261 if npn_protocols:
262 self.context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000263 if ciphers:
264 self.context.set_ciphers(ciphers)
265 self.keyfile = keyfile
266 self.certfile = certfile
267 self.cert_reqs = cert_reqs
268 self.ssl_version = ssl_version
269 self.ca_certs = ca_certs
270 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000271 if server_side and server_hostname:
272 raise ValueError("server_hostname can only be specified "
273 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000274 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000275 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000276 self.do_handshake_on_connect = do_handshake_on_connect
277 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000278 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000279 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000280 socket.__init__(self,
281 family=sock.family,
282 type=sock.type,
283 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000284 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000285 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000286 # see if it's connected
287 try:
288 sock.getpeername()
289 except socket_error as e:
290 if e.errno != errno.ENOTCONN:
291 raise
292 else:
293 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000294 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000295 elif fileno is not None:
296 socket.__init__(self, fileno=fileno)
297 else:
298 socket.__init__(self, family=family, type=type, proto=proto)
299
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000300 self._closed = False
301 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000302 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000303 if connected:
304 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000305 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000306 self._sslobj = self.context._wrap_socket(self, server_side,
307 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000308 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000309 timeout = self.gettimeout()
310 if timeout == 0.0:
311 # non-blocking
312 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000313 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000314
Bill Janssen6e027db2007-11-15 22:23:56 +0000315 except socket_error as x:
316 self.close()
317 raise x
318
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000319 def dup(self):
320 raise NotImplemented("Can't dup() %s instances" %
321 self.__class__.__name__)
322
Bill Janssen6e027db2007-11-15 22:23:56 +0000323 def _checkClosed(self, msg=None):
324 # raise an exception here if you wish to check for spurious closes
325 pass
326
Bill Janssen54cc54c2007-12-14 22:08:56 +0000327 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000328 """Read up to LEN bytes and return them.
329 Return zero-length string on EOF."""
330
Bill Janssen6e027db2007-11-15 22:23:56 +0000331 self._checkClosed()
332 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000333 if buffer is not None:
334 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000335 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000336 v = self._sslobj.read(len or 1024)
337 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000338 except SSLError as x:
339 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000340 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000341 return 0
342 else:
343 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 else:
345 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000346
347 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 """Write DATA to the underlying SSL channel. Returns
349 number of bytes of DATA actually transmitted."""
350
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000352 return self._sslobj.write(data)
353
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 """Returns a formatted version of the data in the
356 certificate provided by the other end of the SSL channel.
357 Return None if no certificate was provided, {} if a
358 certificate was provided, but not validated."""
359
Bill Janssen6e027db2007-11-15 22:23:56 +0000360 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000361 return self._sslobj.peer_certificate(binary_form)
362
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100363 def selected_npn_protocol(self):
364 self._checkClosed()
365 if not self._sslobj or not _ssl.HAS_NPN:
366 return None
367 else:
368 return self._sslobj.selected_npn_protocol()
369
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000370 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000371 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000372 if not self._sslobj:
373 return None
374 else:
375 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000376
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100377 def compression(self):
378 self._checkClosed()
379 if not self._sslobj:
380 return None
381 else:
382 return self._sslobj.compression()
383
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000384 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000385 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000386 if self._sslobj:
387 if flags != 0:
388 raise ValueError(
389 "non-zero flags not allowed in calls to send() on %s" %
390 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000391 while True:
392 try:
393 v = self._sslobj.write(data)
394 except SSLError as x:
395 if x.args[0] == SSL_ERROR_WANT_READ:
396 return 0
397 elif x.args[0] == SSL_ERROR_WANT_WRITE:
398 return 0
399 else:
400 raise
401 else:
402 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000403 else:
404 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000405
Antoine Pitroua468adc2010-09-14 14:43:44 +0000406 def sendto(self, data, flags_or_addr, addr=None):
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("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000410 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000411 elif addr is None:
412 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000413 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000414 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000415
Nick Coghlan513886a2011-08-28 00:00:27 +1000416 def sendmsg(self, *args, **kwargs):
417 # Ensure programs don't send data unencrypted if they try to
418 # use this method.
419 raise NotImplementedError("sendmsg not allowed on instances of %s" %
420 self.__class__)
421
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000422 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000423 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000424 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000425 if flags != 0:
426 raise ValueError(
427 "non-zero flags not allowed in calls to sendall() on %s" %
428 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000429 amount = len(data)
430 count = 0
431 while (count < amount):
432 v = self.send(data[count:])
433 count += v
434 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000435 else:
436 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000437
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000438 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000439 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000440 if self._sslobj:
441 if flags != 0:
442 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000443 "non-zero flags not allowed in calls to recv() on %s" %
444 self.__class__)
445 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000446 else:
447 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000448
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000449 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000450 self._checkClosed()
451 if buffer and (nbytes is None):
452 nbytes = len(buffer)
453 elif nbytes is None:
454 nbytes = 1024
455 if self._sslobj:
456 if flags != 0:
457 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000458 "non-zero flags not allowed in calls to recv_into() on %s" %
459 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000460 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000461 else:
462 return socket.recv_into(self, buffer, nbytes, flags)
463
Antoine Pitroua468adc2010-09-14 14:43:44 +0000464 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000465 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000466 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000467 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000468 self.__class__)
469 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000470 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000471
Bill Janssen58afe4c2008-09-08 16:45:19 +0000472 def recvfrom_into(self, buffer, nbytes=None, flags=0):
473 self._checkClosed()
474 if self._sslobj:
475 raise ValueError("recvfrom_into not allowed on instances of %s" %
476 self.__class__)
477 else:
478 return socket.recvfrom_into(self, buffer, nbytes, flags)
479
Nick Coghlan513886a2011-08-28 00:00:27 +1000480 def recvmsg(self, *args, **kwargs):
481 raise NotImplementedError("recvmsg not allowed on instances of %s" %
482 self.__class__)
483
484 def recvmsg_into(self, *args, **kwargs):
485 raise NotImplementedError("recvmsg_into not allowed on instances of "
486 "%s" % self.__class__)
487
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000488 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000489 self._checkClosed()
490 if self._sslobj:
491 return self._sslobj.pending()
492 else:
493 return 0
494
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000495 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000496 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000498 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000499
Ezio Melottidc55e672010-01-18 09:15:14 +0000500 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000501 if self._sslobj:
502 s = self._sslobj.shutdown()
503 self._sslobj = None
504 return s
505 else:
506 raise ValueError("No SSL wrapper around " + str(self))
507
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000508 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000510 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000511 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000512
Bill Janssen48dc27c2007-12-05 03:38:10 +0000513 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000514 """Perform a TLS/SSL handshake."""
515
Bill Janssen48dc27c2007-12-05 03:38:10 +0000516 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000517 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000518 if timeout == 0.0 and block:
519 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000520 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000521 finally:
522 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000523
Antoine Pitroub4410db2011-05-18 18:51:06 +0200524 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000525 if self.server_side:
526 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000527 # Here we assume that the socket is client-side, and not
528 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000529 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000531 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000532 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200533 if connect_ex:
534 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000535 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200536 rc = None
537 socket.connect(self, addr)
538 if not rc:
539 if self.do_handshake_on_connect:
540 self.do_handshake()
541 self._connected = True
542 return rc
543 except socket_error:
544 self._sslobj = None
545 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000546
547 def connect(self, addr):
548 """Connects to remote ADDR, and then wraps the connection in
549 an SSL channel."""
550 self._real_connect(addr, False)
551
552 def connect_ex(self, addr):
553 """Connects to remote ADDR, and then wraps the connection in
554 an SSL channel."""
555 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000556
557 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000558 """Accepts a new connection from a remote client, and returns
559 a tuple containing that new connection wrapped with a server-side
560 SSL channel, and the address of the remote client."""
561
562 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100563 newsock = self.context.wrap_socket(newsock,
564 do_handshake_on_connect=self.do_handshake_on_connect,
565 suppress_ragged_eofs=self.suppress_ragged_eofs,
566 server_side=True)
567 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Antoine Pitroud6494802011-07-21 01:11:30 +0200569 def get_channel_binding(self, cb_type="tls-unique"):
570 """Get channel binding data for current connection. Raise ValueError
571 if the requested `cb_type` is not supported. Return bytes of the data
572 or None if the data is not available (e.g. before the handshake).
573 """
574 if cb_type not in CHANNEL_BINDING_TYPES:
575 raise ValueError("Unsupported channel binding type")
576 if cb_type != "tls-unique":
577 raise NotImplementedError(
578 "{0} channel binding type not implemented"
579 .format(cb_type))
580 if self._sslobj is None:
581 return None
582 return self._sslobj.tls_unique_cb()
583
Bill Janssen54cc54c2007-12-14 22:08:56 +0000584
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585def wrap_socket(sock, keyfile=None, certfile=None,
586 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000587 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000588 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100589 suppress_ragged_eofs=True,
590 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Bill Janssen6e027db2007-11-15 22:23:56 +0000592 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000594 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000595 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000596 suppress_ragged_eofs=suppress_ragged_eofs,
597 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Thomas Woutersed03b412007-08-28 21:37:11 +0000599# some utility functions
600
601def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000602 """Takes a date-time string in standard ASN1_print form
603 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
604 a Python time value in seconds past the epoch."""
605
Thomas Woutersed03b412007-08-28 21:37:11 +0000606 import time
607 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
608
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609PEM_HEADER = "-----BEGIN CERTIFICATE-----"
610PEM_FOOTER = "-----END CERTIFICATE-----"
611
612def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613 """Takes a certificate in binary DER format and returns the
614 PEM version of it as a string."""
615
Bill Janssen6e027db2007-11-15 22:23:56 +0000616 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
617 return (PEM_HEADER + '\n' +
618 textwrap.fill(f, 64) + '\n' +
619 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620
621def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622 """Takes a certificate in ASCII PEM format and returns the
623 DER-encoded version of it as a byte sequence"""
624
625 if not pem_cert_string.startswith(PEM_HEADER):
626 raise ValueError("Invalid PEM encoding; must start with %s"
627 % PEM_HEADER)
628 if not pem_cert_string.strip().endswith(PEM_FOOTER):
629 raise ValueError("Invalid PEM encoding; must end with %s"
630 % PEM_FOOTER)
631 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000632 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000634def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635 """Retrieve the certificate from the server at the specified address,
636 and return it as a PEM-encoded string.
637 If 'ca_certs' is specified, validate the server cert against it.
638 If 'ssl_version' is specified, use it in the connection attempt."""
639
640 host, port = addr
641 if (ca_certs is not None):
642 cert_reqs = CERT_REQUIRED
643 else:
644 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200645 s = create_connection(addr)
646 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648 dercert = s.getpeercert(True)
649 s.close()
650 return DER_cert_to_PEM_cert(dercert)
651
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000652def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200653 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')