blob: 06437b3046b9e9e70f60545df7b02f63ad98a815 [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
Georg Brandl72c98d32013-10-27 07:16:53 +0100132def _dnsname_match(dn, hostname, max_wildcards=1):
133 """Matching according to RFC 6125, section 6.4.3
134
135 http://tools.ietf.org/html/rfc6125#section-6.4.3
136 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000137 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100138 if not dn:
139 return False
140
141 leftmost, *remainder = dn.split(r'.')
142
143 wildcards = leftmost.count('*')
144 if wildcards > max_wildcards:
145 # Issue #17980: avoid denials of service by refusing more
146 # than one wildcard per fragment. A survery of established
147 # policy among SSL implementations showed it to be a
148 # reasonable choice.
149 raise CertificateError(
150 "too many wildcards in certificate DNS name: " + repr(dn))
151
152 # speed up common case w/o wildcards
153 if not wildcards:
154 return dn.lower() == hostname.lower()
155
156 # RFC 6125, section 6.4.3, subitem 1.
157 # The client SHOULD NOT attempt to match a presented identifier in which
158 # the wildcard character comprises a label other than the left-most label.
159 if leftmost == '*':
160 # When '*' is a fragment by itself, it matches a non-empty dotless
161 # fragment.
162 pats.append('[^.]+')
163 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
164 # RFC 6125, section 6.4.3, subitem 3.
165 # The client SHOULD NOT attempt to match a presented identifier
166 # where the wildcard character is embedded within an A-label or
167 # U-label of an internationalized domain name.
168 pats.append(re.escape(leftmost))
169 else:
170 # Otherwise, '*' matches any dotless string, e.g. www*
171 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
172
173 # add the remaining fragments, ignore any wildcards
174 for frag in remainder:
175 pats.append(re.escape(frag))
176
177 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
178 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000179
180
181def match_hostname(cert, hostname):
182 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100183 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
184 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000185
186 CertificateError is raised on failure. On success, the function
187 returns nothing.
188 """
189 if not cert:
190 raise ValueError("empty or no certificate")
191 dnsnames = []
192 san = cert.get('subjectAltName', ())
193 for key, value in san:
194 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100195 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000196 return
197 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200198 if not dnsnames:
199 # The subject is only checked when there is no dNSName entry
200 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000201 for sub in cert.get('subject', ()):
202 for key, value in sub:
203 # XXX according to RFC 2818, the most specific Common Name
204 # must be used.
205 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100206 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000207 return
208 dnsnames.append(value)
209 if len(dnsnames) > 1:
210 raise CertificateError("hostname %r "
211 "doesn't match either of %s"
212 % (hostname, ', '.join(map(repr, dnsnames))))
213 elif len(dnsnames) == 1:
214 raise CertificateError("hostname %r "
215 "doesn't match %r"
216 % (hostname, dnsnames[0]))
217 else:
218 raise CertificateError("no appropriate commonName or "
219 "subjectAltName fields were found")
220
221
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222class SSLContext(_SSLContext):
223 """An SSLContext holds various SSL-related configuration options and
224 data, such as certificates and possibly a private key."""
225
226 __slots__ = ('protocol',)
227
228 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100229 self = _SSLContext.__new__(cls, protocol)
230 if protocol != _SSLv2_IF_EXISTS:
231 self.set_ciphers(_DEFAULT_CIPHERS)
232 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000233
234 def __init__(self, protocol):
235 self.protocol = protocol
236
237 def wrap_socket(self, sock, server_side=False,
238 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000239 suppress_ragged_eofs=True,
240 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000241 return SSLSocket(sock=sock, server_side=server_side,
242 do_handshake_on_connect=do_handshake_on_connect,
243 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000244 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000245 _context=self)
246
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100247 def set_npn_protocols(self, npn_protocols):
248 protos = bytearray()
249 for protocol in npn_protocols:
250 b = bytes(protocol, 'ascii')
251 if len(b) == 0 or len(b) > 255:
252 raise SSLError('NPN protocols must be 1 to 255 in length')
253 protos.append(len(b))
254 protos.extend(b)
255
256 self._set_npn_protocols(protos)
257
Antoine Pitrou152efa22010-05-16 18:19:27 +0000258
259class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000260 """This class implements a subtype of socket.socket that wraps
261 the underlying OS socket in an SSL context when necessary, and
262 provides read and write methods over that channel."""
263
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000265 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000266 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
267 do_handshake_on_connect=True,
268 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100269 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000270 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000271 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000272
Antoine Pitrou152efa22010-05-16 18:19:27 +0000273 if _context:
274 self.context = _context
275 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000276 if server_side and not certfile:
277 raise ValueError("certfile must be specified for server-side "
278 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000279 if keyfile and not certfile:
280 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000281 if certfile and not keyfile:
282 keyfile = certfile
283 self.context = SSLContext(ssl_version)
284 self.context.verify_mode = cert_reqs
285 if ca_certs:
286 self.context.load_verify_locations(ca_certs)
287 if certfile:
288 self.context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100289 if npn_protocols:
290 self.context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291 if ciphers:
292 self.context.set_ciphers(ciphers)
293 self.keyfile = keyfile
294 self.certfile = certfile
295 self.cert_reqs = cert_reqs
296 self.ssl_version = ssl_version
297 self.ca_certs = ca_certs
298 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000299 if server_side and server_hostname:
300 raise ValueError("server_hostname can only be specified "
301 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000302 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000303 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000304 self.do_handshake_on_connect = do_handshake_on_connect
305 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000306 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000307 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000308 socket.__init__(self,
309 family=sock.family,
310 type=sock.type,
311 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000312 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000313 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000314 # see if it's connected
315 try:
316 sock.getpeername()
317 except socket_error as e:
318 if e.errno != errno.ENOTCONN:
319 raise
320 else:
321 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000322 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000323 elif fileno is not None:
324 socket.__init__(self, fileno=fileno)
325 else:
326 socket.__init__(self, family=family, type=type, proto=proto)
327
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000328 self._closed = False
329 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000330 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000331 if connected:
332 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000334 self._sslobj = self.context._wrap_socket(self, server_side,
335 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000336 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000337 timeout = self.gettimeout()
338 if timeout == 0.0:
339 # non-blocking
340 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000341 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000342
Bill Janssen6e027db2007-11-15 22:23:56 +0000343 except socket_error as x:
344 self.close()
345 raise x
346
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000347 def dup(self):
348 raise NotImplemented("Can't dup() %s instances" %
349 self.__class__.__name__)
350
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 def _checkClosed(self, msg=None):
352 # raise an exception here if you wish to check for spurious closes
353 pass
354
Bill Janssen54cc54c2007-12-14 22:08:56 +0000355 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000356 """Read up to LEN bytes and return them.
357 Return zero-length string on EOF."""
358
Bill Janssen6e027db2007-11-15 22:23:56 +0000359 self._checkClosed()
360 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000361 if buffer is not None:
362 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000363 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000364 v = self._sslobj.read(len or 1024)
365 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000366 except SSLError as x:
367 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000368 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000369 return 0
370 else:
371 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000372 else:
373 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
375 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376 """Write DATA to the underlying SSL channel. Returns
377 number of bytes of DATA actually transmitted."""
378
Bill Janssen6e027db2007-11-15 22:23:56 +0000379 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000380 return self._sslobj.write(data)
381
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000383 """Returns a formatted version of the data in the
384 certificate provided by the other end of the SSL channel.
385 Return None if no certificate was provided, {} if a
386 certificate was provided, but not validated."""
387
Bill Janssen6e027db2007-11-15 22:23:56 +0000388 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389 return self._sslobj.peer_certificate(binary_form)
390
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100391 def selected_npn_protocol(self):
392 self._checkClosed()
393 if not self._sslobj or not _ssl.HAS_NPN:
394 return None
395 else:
396 return self._sslobj.selected_npn_protocol()
397
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000398 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000399 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400 if not self._sslobj:
401 return None
402 else:
403 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000404
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100405 def compression(self):
406 self._checkClosed()
407 if not self._sslobj:
408 return None
409 else:
410 return self._sslobj.compression()
411
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000412 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000413 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000414 if self._sslobj:
415 if flags != 0:
416 raise ValueError(
417 "non-zero flags not allowed in calls to send() on %s" %
418 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000419 while True:
420 try:
421 v = self._sslobj.write(data)
422 except SSLError as x:
423 if x.args[0] == SSL_ERROR_WANT_READ:
424 return 0
425 elif x.args[0] == SSL_ERROR_WANT_WRITE:
426 return 0
427 else:
428 raise
429 else:
430 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000431 else:
432 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000433
Antoine Pitroua468adc2010-09-14 14:43:44 +0000434 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000435 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000436 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000437 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000438 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000439 elif addr is None:
440 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000441 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000442 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000443
Nick Coghlan513886a2011-08-28 00:00:27 +1000444 def sendmsg(self, *args, **kwargs):
445 # Ensure programs don't send data unencrypted if they try to
446 # use this method.
447 raise NotImplementedError("sendmsg not allowed on instances of %s" %
448 self.__class__)
449
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000450 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000451 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000452 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000453 if flags != 0:
454 raise ValueError(
455 "non-zero flags not allowed in calls to sendall() on %s" %
456 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000457 amount = len(data)
458 count = 0
459 while (count < amount):
460 v = self.send(data[count:])
461 count += v
462 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000463 else:
464 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000465
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000466 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000467 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000468 if self._sslobj:
469 if flags != 0:
470 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000471 "non-zero flags not allowed in calls to recv() on %s" %
472 self.__class__)
473 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000474 else:
475 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000476
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000477 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000478 self._checkClosed()
479 if buffer and (nbytes is None):
480 nbytes = len(buffer)
481 elif nbytes is None:
482 nbytes = 1024
483 if self._sslobj:
484 if flags != 0:
485 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000486 "non-zero flags not allowed in calls to recv_into() on %s" %
487 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000488 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000489 else:
490 return socket.recv_into(self, buffer, nbytes, flags)
491
Antoine Pitroua468adc2010-09-14 14:43:44 +0000492 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000493 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000494 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000495 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000496 self.__class__)
497 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000498 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000499
Bill Janssen58afe4c2008-09-08 16:45:19 +0000500 def recvfrom_into(self, buffer, nbytes=None, flags=0):
501 self._checkClosed()
502 if self._sslobj:
503 raise ValueError("recvfrom_into not allowed on instances of %s" %
504 self.__class__)
505 else:
506 return socket.recvfrom_into(self, buffer, nbytes, flags)
507
Nick Coghlan513886a2011-08-28 00:00:27 +1000508 def recvmsg(self, *args, **kwargs):
509 raise NotImplementedError("recvmsg not allowed on instances of %s" %
510 self.__class__)
511
512 def recvmsg_into(self, *args, **kwargs):
513 raise NotImplementedError("recvmsg_into not allowed on instances of "
514 "%s" % self.__class__)
515
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000516 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000517 self._checkClosed()
518 if self._sslobj:
519 return self._sslobj.pending()
520 else:
521 return 0
522
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000523 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000524 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000526 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000527
Ezio Melottidc55e672010-01-18 09:15:14 +0000528 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000529 if self._sslobj:
530 s = self._sslobj.shutdown()
531 self._sslobj = None
532 return s
533 else:
534 raise ValueError("No SSL wrapper around " + str(self))
535
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000536 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000538 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000539 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000540
Bill Janssen48dc27c2007-12-05 03:38:10 +0000541 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000542 """Perform a TLS/SSL handshake."""
543
Bill Janssen48dc27c2007-12-05 03:38:10 +0000544 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000545 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000546 if timeout == 0.0 and block:
547 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000548 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000549 finally:
550 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000551
Antoine Pitroub4410db2011-05-18 18:51:06 +0200552 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000553 if self.server_side:
554 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000555 # Here we assume that the socket is client-side, and not
556 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000557 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000559 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000560 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200561 if connect_ex:
562 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000563 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200564 rc = None
565 socket.connect(self, addr)
566 if not rc:
567 if self.do_handshake_on_connect:
568 self.do_handshake()
569 self._connected = True
570 return rc
571 except socket_error:
572 self._sslobj = None
573 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000574
575 def connect(self, addr):
576 """Connects to remote ADDR, and then wraps the connection in
577 an SSL channel."""
578 self._real_connect(addr, False)
579
580 def connect_ex(self, addr):
581 """Connects to remote ADDR, and then wraps the connection in
582 an SSL channel."""
583 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000584
585 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000586 """Accepts a new connection from a remote client, and returns
587 a tuple containing that new connection wrapped with a server-side
588 SSL channel, and the address of the remote client."""
589
590 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100591 newsock = self.context.wrap_socket(newsock,
592 do_handshake_on_connect=self.do_handshake_on_connect,
593 suppress_ragged_eofs=self.suppress_ragged_eofs,
594 server_side=True)
595 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Antoine Pitroud6494802011-07-21 01:11:30 +0200597 def get_channel_binding(self, cb_type="tls-unique"):
598 """Get channel binding data for current connection. Raise ValueError
599 if the requested `cb_type` is not supported. Return bytes of the data
600 or None if the data is not available (e.g. before the handshake).
601 """
602 if cb_type not in CHANNEL_BINDING_TYPES:
603 raise ValueError("Unsupported channel binding type")
604 if cb_type != "tls-unique":
605 raise NotImplementedError(
606 "{0} channel binding type not implemented"
607 .format(cb_type))
608 if self._sslobj is None:
609 return None
610 return self._sslobj.tls_unique_cb()
611
Bill Janssen54cc54c2007-12-14 22:08:56 +0000612
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613def wrap_socket(sock, keyfile=None, certfile=None,
614 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000615 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000616 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100617 suppress_ragged_eofs=True,
618 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Bill Janssen6e027db2007-11-15 22:23:56 +0000620 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000622 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000623 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000624 suppress_ragged_eofs=suppress_ragged_eofs,
625 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Thomas Woutersed03b412007-08-28 21:37:11 +0000627# some utility functions
628
629def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000630 """Takes a date-time string in standard ASN1_print form
631 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
632 a Python time value in seconds past the epoch."""
633
Thomas Woutersed03b412007-08-28 21:37:11 +0000634 import time
635 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
636
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637PEM_HEADER = "-----BEGIN CERTIFICATE-----"
638PEM_FOOTER = "-----END CERTIFICATE-----"
639
640def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641 """Takes a certificate in binary DER format and returns the
642 PEM version of it as a string."""
643
Bill Janssen6e027db2007-11-15 22:23:56 +0000644 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
645 return (PEM_HEADER + '\n' +
646 textwrap.fill(f, 64) + '\n' +
647 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648
649def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650 """Takes a certificate in ASCII PEM format and returns the
651 DER-encoded version of it as a byte sequence"""
652
653 if not pem_cert_string.startswith(PEM_HEADER):
654 raise ValueError("Invalid PEM encoding; must start with %s"
655 % PEM_HEADER)
656 if not pem_cert_string.strip().endswith(PEM_FOOTER):
657 raise ValueError("Invalid PEM encoding; must end with %s"
658 % PEM_FOOTER)
659 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000660 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000662def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663 """Retrieve the certificate from the server at the specified address,
664 and return it as a PEM-encoded string.
665 If 'ca_certs' is specified, validate the server cert against it.
666 If 'ssl_version' is specified, use it in the connection attempt."""
667
668 host, port = addr
669 if (ca_certs is not None):
670 cert_reqs = CERT_REQUIRED
671 else:
672 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200673 s = create_connection(addr)
674 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676 dercert = s.getpeercert(True)
677 s.close()
678 return DER_cert_to_PEM_cert(dercert)
679
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000680def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200681 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')