blob: 3162f56a37249b4a2dff18020d72fefe6b4f030e [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
132def _dnsname_to_pat(dn):
133 pats = []
134 for frag in dn.split(r'.'):
135 if frag == '*':
136 # When '*' is a fragment by itself, it matches a non-empty dotless
137 # fragment.
138 pats.append('[^.]+')
139 else:
140 # Otherwise, '*' matches any dotless fragment.
141 frag = re.escape(frag)
142 pats.append(frag.replace(r'\*', '[^.]*'))
143 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
144
145
146def match_hostname(cert, hostname):
147 """Verify that *cert* (in decoded format as returned by
148 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
149 are mostly followed, but IP addresses are not accepted for *hostname*.
150
151 CertificateError is raised on failure. On success, the function
152 returns nothing.
153 """
154 if not cert:
155 raise ValueError("empty or no certificate")
156 dnsnames = []
157 san = cert.get('subjectAltName', ())
158 for key, value in san:
159 if key == 'DNS':
160 if _dnsname_to_pat(value).match(hostname):
161 return
162 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200163 if not dnsnames:
164 # The subject is only checked when there is no dNSName entry
165 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000166 for sub in cert.get('subject', ()):
167 for key, value in sub:
168 # XXX according to RFC 2818, the most specific Common Name
169 # must be used.
170 if key == 'commonName':
171 if _dnsname_to_pat(value).match(hostname):
172 return
173 dnsnames.append(value)
174 if len(dnsnames) > 1:
175 raise CertificateError("hostname %r "
176 "doesn't match either of %s"
177 % (hostname, ', '.join(map(repr, dnsnames))))
178 elif len(dnsnames) == 1:
179 raise CertificateError("hostname %r "
180 "doesn't match %r"
181 % (hostname, dnsnames[0]))
182 else:
183 raise CertificateError("no appropriate commonName or "
184 "subjectAltName fields were found")
185
186
Antoine Pitrou152efa22010-05-16 18:19:27 +0000187class SSLContext(_SSLContext):
188 """An SSLContext holds various SSL-related configuration options and
189 data, such as certificates and possibly a private key."""
190
191 __slots__ = ('protocol',)
192
193 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100194 self = _SSLContext.__new__(cls, protocol)
195 if protocol != _SSLv2_IF_EXISTS:
196 self.set_ciphers(_DEFAULT_CIPHERS)
197 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000198
199 def __init__(self, protocol):
200 self.protocol = protocol
201
202 def wrap_socket(self, sock, server_side=False,
203 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000204 suppress_ragged_eofs=True,
205 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 return SSLSocket(sock=sock, server_side=server_side,
207 do_handshake_on_connect=do_handshake_on_connect,
208 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000209 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210 _context=self)
211
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100212 def set_npn_protocols(self, npn_protocols):
213 protos = bytearray()
214 for protocol in npn_protocols:
215 b = bytes(protocol, 'ascii')
216 if len(b) == 0 or len(b) > 255:
217 raise SSLError('NPN protocols must be 1 to 255 in length')
218 protos.append(len(b))
219 protos.extend(b)
220
221 self._set_npn_protocols(protos)
222
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223
224class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000225 """This class implements a subtype of socket.socket that wraps
226 the underlying OS socket in an SSL context when necessary, and
227 provides read and write methods over that channel."""
228
Bill Janssen6e027db2007-11-15 22:23:56 +0000229 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000230 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000231 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
232 do_handshake_on_connect=True,
233 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100234 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000235 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000236 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000237
Antoine Pitrou152efa22010-05-16 18:19:27 +0000238 if _context:
239 self.context = _context
240 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000241 if server_side and not certfile:
242 raise ValueError("certfile must be specified for server-side "
243 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000244 if keyfile and not certfile:
245 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000246 if certfile and not keyfile:
247 keyfile = certfile
248 self.context = SSLContext(ssl_version)
249 self.context.verify_mode = cert_reqs
250 if ca_certs:
251 self.context.load_verify_locations(ca_certs)
252 if certfile:
253 self.context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100254 if npn_protocols:
255 self.context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000256 if ciphers:
257 self.context.set_ciphers(ciphers)
258 self.keyfile = keyfile
259 self.certfile = certfile
260 self.cert_reqs = cert_reqs
261 self.ssl_version = ssl_version
262 self.ca_certs = ca_certs
263 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000264 if server_side and server_hostname:
265 raise ValueError("server_hostname can only be specified "
266 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000267 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000268 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000269 self.do_handshake_on_connect = do_handshake_on_connect
270 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000271 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000273 socket.__init__(self,
274 family=sock.family,
275 type=sock.type,
276 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000277 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000278 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000279 # see if it's connected
280 try:
281 sock.getpeername()
282 except socket_error as e:
283 if e.errno != errno.ENOTCONN:
284 raise
285 else:
286 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000287 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 elif fileno is not None:
289 socket.__init__(self, fileno=fileno)
290 else:
291 socket.__init__(self, family=family, type=type, proto=proto)
292
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000293 self._closed = False
294 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000295 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000296 if connected:
297 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000298 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000299 self._sslobj = self.context._wrap_socket(self, server_side,
300 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000301 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000302 timeout = self.gettimeout()
303 if timeout == 0.0:
304 # non-blocking
305 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000306 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000307
Bill Janssen6e027db2007-11-15 22:23:56 +0000308 except socket_error as x:
309 self.close()
310 raise x
311
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000312 def dup(self):
313 raise NotImplemented("Can't dup() %s instances" %
314 self.__class__.__name__)
315
Bill Janssen6e027db2007-11-15 22:23:56 +0000316 def _checkClosed(self, msg=None):
317 # raise an exception here if you wish to check for spurious closes
318 pass
319
Bill Janssen54cc54c2007-12-14 22:08:56 +0000320 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000321 """Read up to LEN bytes and return them.
322 Return zero-length string on EOF."""
323
Bill Janssen6e027db2007-11-15 22:23:56 +0000324 self._checkClosed()
325 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000326 if buffer is not None:
327 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000328 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000329 v = self._sslobj.read(len or 1024)
330 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000331 except SSLError as x:
332 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000333 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000334 return 0
335 else:
336 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 else:
338 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000339
340 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 """Write DATA to the underlying SSL channel. Returns
342 number of bytes of DATA actually transmitted."""
343
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000345 return self._sslobj.write(data)
346
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000347 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 """Returns a formatted version of the data in the
349 certificate provided by the other end of the SSL channel.
350 Return None if no certificate was provided, {} if a
351 certificate was provided, but not validated."""
352
Bill Janssen6e027db2007-11-15 22:23:56 +0000353 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354 return self._sslobj.peer_certificate(binary_form)
355
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100356 def selected_npn_protocol(self):
357 self._checkClosed()
358 if not self._sslobj or not _ssl.HAS_NPN:
359 return None
360 else:
361 return self._sslobj.selected_npn_protocol()
362
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000363 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000364 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365 if not self._sslobj:
366 return None
367 else:
368 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000369
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100370 def compression(self):
371 self._checkClosed()
372 if not self._sslobj:
373 return None
374 else:
375 return self._sslobj.compression()
376
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000377 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000378 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000379 if self._sslobj:
380 if flags != 0:
381 raise ValueError(
382 "non-zero flags not allowed in calls to send() on %s" %
383 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000384 while True:
385 try:
386 v = self._sslobj.write(data)
387 except SSLError as x:
388 if x.args[0] == SSL_ERROR_WANT_READ:
389 return 0
390 elif x.args[0] == SSL_ERROR_WANT_WRITE:
391 return 0
392 else:
393 raise
394 else:
395 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000396 else:
397 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000398
Antoine Pitroua468adc2010-09-14 14:43:44 +0000399 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000401 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000402 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000403 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000404 elif addr is None:
405 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000406 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000407 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000408
Nick Coghlan513886a2011-08-28 00:00:27 +1000409 def sendmsg(self, *args, **kwargs):
410 # Ensure programs don't send data unencrypted if they try to
411 # use this method.
412 raise NotImplementedError("sendmsg not allowed on instances of %s" %
413 self.__class__)
414
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000415 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000416 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000417 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000418 if flags != 0:
419 raise ValueError(
420 "non-zero flags not allowed in calls to sendall() on %s" %
421 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000422 amount = len(data)
423 count = 0
424 while (count < amount):
425 v = self.send(data[count:])
426 count += v
427 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000428 else:
429 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000430
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000431 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000432 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000433 if self._sslobj:
434 if flags != 0:
435 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000436 "non-zero flags not allowed in calls to recv() on %s" %
437 self.__class__)
438 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000439 else:
440 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000441
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000442 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000443 self._checkClosed()
444 if buffer and (nbytes is None):
445 nbytes = len(buffer)
446 elif nbytes is None:
447 nbytes = 1024
448 if self._sslobj:
449 if flags != 0:
450 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000451 "non-zero flags not allowed in calls to recv_into() on %s" %
452 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000453 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000454 else:
455 return socket.recv_into(self, buffer, nbytes, flags)
456
Antoine Pitroua468adc2010-09-14 14:43:44 +0000457 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000458 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000459 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000460 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000461 self.__class__)
462 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000463 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000464
Bill Janssen58afe4c2008-09-08 16:45:19 +0000465 def recvfrom_into(self, buffer, nbytes=None, flags=0):
466 self._checkClosed()
467 if self._sslobj:
468 raise ValueError("recvfrom_into not allowed on instances of %s" %
469 self.__class__)
470 else:
471 return socket.recvfrom_into(self, buffer, nbytes, flags)
472
Nick Coghlan513886a2011-08-28 00:00:27 +1000473 def recvmsg(self, *args, **kwargs):
474 raise NotImplementedError("recvmsg not allowed on instances of %s" %
475 self.__class__)
476
477 def recvmsg_into(self, *args, **kwargs):
478 raise NotImplementedError("recvmsg_into not allowed on instances of "
479 "%s" % self.__class__)
480
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000481 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000482 self._checkClosed()
483 if self._sslobj:
484 return self._sslobj.pending()
485 else:
486 return 0
487
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000488 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000489 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000491 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000492
Ezio Melottidc55e672010-01-18 09:15:14 +0000493 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000494 if self._sslobj:
495 s = self._sslobj.shutdown()
496 self._sslobj = None
497 return s
498 else:
499 raise ValueError("No SSL wrapper around " + str(self))
500
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000501 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000503 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000504 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000505
Bill Janssen48dc27c2007-12-05 03:38:10 +0000506 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000507 """Perform a TLS/SSL handshake."""
508
Bill Janssen48dc27c2007-12-05 03:38:10 +0000509 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000510 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000511 if timeout == 0.0 and block:
512 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000513 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000514 finally:
515 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000516
Antoine Pitroub4410db2011-05-18 18:51:06 +0200517 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000518 if self.server_side:
519 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000520 # Here we assume that the socket is client-side, and not
521 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000522 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000524 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000525 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200526 if connect_ex:
527 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000528 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200529 rc = None
530 socket.connect(self, addr)
531 if not rc:
532 if self.do_handshake_on_connect:
533 self.do_handshake()
534 self._connected = True
535 return rc
536 except socket_error:
537 self._sslobj = None
538 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000539
540 def connect(self, addr):
541 """Connects to remote ADDR, and then wraps the connection in
542 an SSL channel."""
543 self._real_connect(addr, False)
544
545 def connect_ex(self, addr):
546 """Connects to remote ADDR, and then wraps the connection in
547 an SSL channel."""
548 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000549
550 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000551 """Accepts a new connection from a remote client, and returns
552 a tuple containing that new connection wrapped with a server-side
553 SSL channel, and the address of the remote client."""
554
555 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000556 return (SSLSocket(sock=newsock,
557 keyfile=self.keyfile, certfile=self.certfile,
558 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000559 cert_reqs=self.cert_reqs,
560 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000561 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000562 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000563 do_handshake_on_connect=
564 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000565 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Antoine Pitroud6494802011-07-21 01:11:30 +0200567 def get_channel_binding(self, cb_type="tls-unique"):
568 """Get channel binding data for current connection. Raise ValueError
569 if the requested `cb_type` is not supported. Return bytes of the data
570 or None if the data is not available (e.g. before the handshake).
571 """
572 if cb_type not in CHANNEL_BINDING_TYPES:
573 raise ValueError("Unsupported channel binding type")
574 if cb_type != "tls-unique":
575 raise NotImplementedError(
576 "{0} channel binding type not implemented"
577 .format(cb_type))
578 if self._sslobj is None:
579 return None
580 return self._sslobj.tls_unique_cb()
581
Guido van Rossume6650f92007-12-06 19:05:55 +0000582 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000583 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000584 self._real_close()
585
Bill Janssen54cc54c2007-12-14 22:08:56 +0000586
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587def wrap_socket(sock, keyfile=None, certfile=None,
588 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000589 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000590 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100591 suppress_ragged_eofs=True,
592 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Bill Janssen6e027db2007-11-15 22:23:56 +0000594 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000596 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000597 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000598 suppress_ragged_eofs=suppress_ragged_eofs,
599 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Thomas Woutersed03b412007-08-28 21:37:11 +0000601# some utility functions
602
603def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000604 """Takes a date-time string in standard ASN1_print form
605 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
606 a Python time value in seconds past the epoch."""
607
Thomas Woutersed03b412007-08-28 21:37:11 +0000608 import time
609 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
610
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611PEM_HEADER = "-----BEGIN CERTIFICATE-----"
612PEM_FOOTER = "-----END CERTIFICATE-----"
613
614def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615 """Takes a certificate in binary DER format and returns the
616 PEM version of it as a string."""
617
Bill Janssen6e027db2007-11-15 22:23:56 +0000618 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
619 return (PEM_HEADER + '\n' +
620 textwrap.fill(f, 64) + '\n' +
621 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622
623def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624 """Takes a certificate in ASCII PEM format and returns the
625 DER-encoded version of it as a byte sequence"""
626
627 if not pem_cert_string.startswith(PEM_HEADER):
628 raise ValueError("Invalid PEM encoding; must start with %s"
629 % PEM_HEADER)
630 if not pem_cert_string.strip().endswith(PEM_FOOTER):
631 raise ValueError("Invalid PEM encoding; must end with %s"
632 % PEM_FOOTER)
633 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000634 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000636def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637 """Retrieve the certificate from the server at the specified address,
638 and return it as a PEM-encoded string.
639 If 'ca_certs' is specified, validate the server cert against it.
640 If 'ssl_version' is specified, use it in the connection attempt."""
641
642 host, port = addr
643 if (ca_certs is not None):
644 cert_reqs = CERT_REQUIRED
645 else:
646 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200647 s = create_connection(addr)
648 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650 dercert = s.getpeercert(True)
651 s.close()
652 return DER_cert_to_PEM_cert(dercert)
653
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000654def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200655 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')