blob: acbc7008f8132c2390ef5a2b06fcdea65f7ead71 [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
Antoine Pitrou15399c32011-04-28 19:23:55 +0200112from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000113import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000114import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000115import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000116
Andrew Svetlov0832af62012-12-18 23:10:48 +0200117
118socket_error = OSError # keep that public name in module namespace
119
Antoine Pitroud6494802011-07-21 01:11:30 +0200120if _ssl.HAS_TLS_UNIQUE:
121 CHANNEL_BINDING_TYPES = ['tls-unique']
122else:
123 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000124
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100125# Disable weak or insecure ciphers by default
126# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
127_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
128
Thomas Woutersed03b412007-08-28 21:37:11 +0000129
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000130class CertificateError(ValueError):
131 pass
132
133
134def _dnsname_to_pat(dn):
135 pats = []
136 for frag in dn.split(r'.'):
137 if frag == '*':
138 # When '*' is a fragment by itself, it matches a non-empty dotless
139 # fragment.
140 pats.append('[^.]+')
141 else:
142 # Otherwise, '*' matches any dotless fragment.
143 frag = re.escape(frag)
144 pats.append(frag.replace(r'\*', '[^.]*'))
145 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
146
147
148def match_hostname(cert, hostname):
149 """Verify that *cert* (in decoded format as returned by
150 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
151 are mostly followed, but IP addresses are not accepted for *hostname*.
152
153 CertificateError is raised on failure. On success, the function
154 returns nothing.
155 """
156 if not cert:
157 raise ValueError("empty or no certificate")
158 dnsnames = []
159 san = cert.get('subjectAltName', ())
160 for key, value in san:
161 if key == 'DNS':
162 if _dnsname_to_pat(value).match(hostname):
163 return
164 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200165 if not dnsnames:
166 # The subject is only checked when there is no dNSName entry
167 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000168 for sub in cert.get('subject', ()):
169 for key, value in sub:
170 # XXX according to RFC 2818, the most specific Common Name
171 # must be used.
172 if key == 'commonName':
173 if _dnsname_to_pat(value).match(hostname):
174 return
175 dnsnames.append(value)
176 if len(dnsnames) > 1:
177 raise CertificateError("hostname %r "
178 "doesn't match either of %s"
179 % (hostname, ', '.join(map(repr, dnsnames))))
180 elif len(dnsnames) == 1:
181 raise CertificateError("hostname %r "
182 "doesn't match %r"
183 % (hostname, dnsnames[0]))
184 else:
185 raise CertificateError("no appropriate commonName or "
186 "subjectAltName fields were found")
187
188
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189class SSLContext(_SSLContext):
190 """An SSLContext holds various SSL-related configuration options and
191 data, such as certificates and possibly a private key."""
192
193 __slots__ = ('protocol',)
194
195 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100196 self = _SSLContext.__new__(cls, protocol)
197 if protocol != _SSLv2_IF_EXISTS:
198 self.set_ciphers(_DEFAULT_CIPHERS)
199 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000200
201 def __init__(self, protocol):
202 self.protocol = protocol
203
204 def wrap_socket(self, sock, server_side=False,
205 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000206 suppress_ragged_eofs=True,
207 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000208 return SSLSocket(sock=sock, server_side=server_side,
209 do_handshake_on_connect=do_handshake_on_connect,
210 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000211 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212 _context=self)
213
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100214 def set_npn_protocols(self, npn_protocols):
215 protos = bytearray()
216 for protocol in npn_protocols:
217 b = bytes(protocol, 'ascii')
218 if len(b) == 0 or len(b) > 255:
219 raise SSLError('NPN protocols must be 1 to 255 in length')
220 protos.append(len(b))
221 protos.extend(b)
222
223 self._set_npn_protocols(protos)
224
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225
226class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000227 """This class implements a subtype of socket.socket that wraps
228 the underlying OS socket in an SSL context when necessary, and
229 provides read and write methods over that channel."""
230
Bill Janssen6e027db2007-11-15 22:23:56 +0000231 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000232 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000233 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
234 do_handshake_on_connect=True,
235 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100236 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000237 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000238 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000239
Antoine Pitrou152efa22010-05-16 18:19:27 +0000240 if _context:
241 self.context = _context
242 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000243 if server_side and not certfile:
244 raise ValueError("certfile must be specified for server-side "
245 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000246 if keyfile and not certfile:
247 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000248 if certfile and not keyfile:
249 keyfile = certfile
250 self.context = SSLContext(ssl_version)
251 self.context.verify_mode = cert_reqs
252 if ca_certs:
253 self.context.load_verify_locations(ca_certs)
254 if certfile:
255 self.context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100256 if npn_protocols:
257 self.context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000258 if ciphers:
259 self.context.set_ciphers(ciphers)
260 self.keyfile = keyfile
261 self.certfile = certfile
262 self.cert_reqs = cert_reqs
263 self.ssl_version = ssl_version
264 self.ca_certs = ca_certs
265 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000266 if server_side and server_hostname:
267 raise ValueError("server_hostname can only be specified "
268 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000269 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000270 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000271 self.do_handshake_on_connect = do_handshake_on_connect
272 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000273 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000275 socket.__init__(self,
276 family=sock.family,
277 type=sock.type,
278 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000279 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000280 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000281 # see if it's connected
282 try:
283 sock.getpeername()
Andrew Svetlov0832af62012-12-18 23:10:48 +0200284 except OSError as e:
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000285 if e.errno != errno.ENOTCONN:
286 raise
287 else:
288 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000289 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 elif fileno is not None:
291 socket.__init__(self, fileno=fileno)
292 else:
293 socket.__init__(self, family=family, type=type, proto=proto)
294
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000295 self._closed = False
296 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000297 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000298 if connected:
299 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000300 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000301 self._sslobj = self.context._wrap_socket(self, server_side,
302 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000304 timeout = self.gettimeout()
305 if timeout == 0.0:
306 # non-blocking
307 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000308 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000309
Andrew Svetlov0832af62012-12-18 23:10:48 +0200310 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000311 self.close()
312 raise x
313
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000314 def dup(self):
315 raise NotImplemented("Can't dup() %s instances" %
316 self.__class__.__name__)
317
Bill Janssen6e027db2007-11-15 22:23:56 +0000318 def _checkClosed(self, msg=None):
319 # raise an exception here if you wish to check for spurious closes
320 pass
321
Bill Janssen54cc54c2007-12-14 22:08:56 +0000322 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000323 """Read up to LEN bytes and return them.
324 Return zero-length string on EOF."""
325
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 self._checkClosed()
327 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000328 if buffer is not None:
329 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000331 v = self._sslobj.read(len or 1024)
332 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 except SSLError as x:
334 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000335 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000336 return 0
337 else:
338 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000339 else:
340 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000341
342 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 """Write DATA to the underlying SSL channel. Returns
344 number of bytes of DATA actually transmitted."""
345
Bill Janssen6e027db2007-11-15 22:23:56 +0000346 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000347 return self._sslobj.write(data)
348
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000349 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000350 """Returns a formatted version of the data in the
351 certificate provided by the other end of the SSL channel.
352 Return None if no certificate was provided, {} if a
353 certificate was provided, but not validated."""
354
Bill Janssen6e027db2007-11-15 22:23:56 +0000355 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000356 return self._sslobj.peer_certificate(binary_form)
357
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100358 def selected_npn_protocol(self):
359 self._checkClosed()
360 if not self._sslobj or not _ssl.HAS_NPN:
361 return None
362 else:
363 return self._sslobj.selected_npn_protocol()
364
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000365 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000366 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000367 if not self._sslobj:
368 return None
369 else:
370 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000371
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100372 def compression(self):
373 self._checkClosed()
374 if not self._sslobj:
375 return None
376 else:
377 return self._sslobj.compression()
378
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000379 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000380 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000381 if self._sslobj:
382 if flags != 0:
383 raise ValueError(
384 "non-zero flags not allowed in calls to send() on %s" %
385 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000386 while True:
387 try:
388 v = self._sslobj.write(data)
389 except SSLError as x:
390 if x.args[0] == SSL_ERROR_WANT_READ:
391 return 0
392 elif x.args[0] == SSL_ERROR_WANT_WRITE:
393 return 0
394 else:
395 raise
396 else:
397 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000398 else:
399 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000400
Antoine Pitroua468adc2010-09-14 14:43:44 +0000401 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000402 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000403 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000404 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000405 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000406 elif addr is None:
407 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000408 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000409 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000410
Nick Coghlan513886a2011-08-28 00:00:27 +1000411 def sendmsg(self, *args, **kwargs):
412 # Ensure programs don't send data unencrypted if they try to
413 # use this method.
414 raise NotImplementedError("sendmsg not allowed on instances of %s" %
415 self.__class__)
416
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000417 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000418 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000419 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000420 if flags != 0:
421 raise ValueError(
422 "non-zero flags not allowed in calls to sendall() on %s" %
423 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000424 amount = len(data)
425 count = 0
426 while (count < amount):
427 v = self.send(data[count:])
428 count += v
429 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000430 else:
431 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000432
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000433 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000434 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000435 if self._sslobj:
436 if flags != 0:
437 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000438 "non-zero flags not allowed in calls to recv() on %s" %
439 self.__class__)
440 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000441 else:
442 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000443
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000444 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000445 self._checkClosed()
446 if buffer and (nbytes is None):
447 nbytes = len(buffer)
448 elif nbytes is None:
449 nbytes = 1024
450 if self._sslobj:
451 if flags != 0:
452 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000453 "non-zero flags not allowed in calls to recv_into() on %s" %
454 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000455 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 else:
457 return socket.recv_into(self, buffer, nbytes, flags)
458
Antoine Pitroua468adc2010-09-14 14:43:44 +0000459 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000460 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000461 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000462 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000463 self.__class__)
464 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000465 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000466
Bill Janssen58afe4c2008-09-08 16:45:19 +0000467 def recvfrom_into(self, buffer, nbytes=None, flags=0):
468 self._checkClosed()
469 if self._sslobj:
470 raise ValueError("recvfrom_into not allowed on instances of %s" %
471 self.__class__)
472 else:
473 return socket.recvfrom_into(self, buffer, nbytes, flags)
474
Nick Coghlan513886a2011-08-28 00:00:27 +1000475 def recvmsg(self, *args, **kwargs):
476 raise NotImplementedError("recvmsg not allowed on instances of %s" %
477 self.__class__)
478
479 def recvmsg_into(self, *args, **kwargs):
480 raise NotImplementedError("recvmsg_into not allowed on instances of "
481 "%s" % self.__class__)
482
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000483 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000484 self._checkClosed()
485 if self._sslobj:
486 return self._sslobj.pending()
487 else:
488 return 0
489
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000490 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000491 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000493 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000494
Ezio Melottidc55e672010-01-18 09:15:14 +0000495 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000496 if self._sslobj:
497 s = self._sslobj.shutdown()
498 self._sslobj = None
499 return s
500 else:
501 raise ValueError("No SSL wrapper around " + str(self))
502
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000503 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000505 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000506 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000507
Bill Janssen48dc27c2007-12-05 03:38:10 +0000508 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000509 """Perform a TLS/SSL handshake."""
510
Bill Janssen48dc27c2007-12-05 03:38:10 +0000511 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000512 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000513 if timeout == 0.0 and block:
514 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000515 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000516 finally:
517 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000518
Antoine Pitroub4410db2011-05-18 18:51:06 +0200519 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000520 if self.server_side:
521 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000522 # Here we assume that the socket is client-side, and not
523 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000524 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000526 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000527 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200528 if connect_ex:
529 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000530 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200531 rc = None
532 socket.connect(self, addr)
533 if not rc:
534 if self.do_handshake_on_connect:
535 self.do_handshake()
536 self._connected = True
537 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200538 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200539 self._sslobj = None
540 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000541
542 def connect(self, addr):
543 """Connects to remote ADDR, and then wraps the connection in
544 an SSL channel."""
545 self._real_connect(addr, False)
546
547 def connect_ex(self, addr):
548 """Connects to remote ADDR, and then wraps the connection in
549 an SSL channel."""
550 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000551
552 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000553 """Accepts a new connection from a remote client, and returns
554 a tuple containing that new connection wrapped with a server-side
555 SSL channel, and the address of the remote client."""
556
557 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100558 newsock = self.context.wrap_socket(newsock,
559 do_handshake_on_connect=self.do_handshake_on_connect,
560 suppress_ragged_eofs=self.suppress_ragged_eofs,
561 server_side=True)
562 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563
Antoine Pitroud6494802011-07-21 01:11:30 +0200564 def get_channel_binding(self, cb_type="tls-unique"):
565 """Get channel binding data for current connection. Raise ValueError
566 if the requested `cb_type` is not supported. Return bytes of the data
567 or None if the data is not available (e.g. before the handshake).
568 """
569 if cb_type not in CHANNEL_BINDING_TYPES:
570 raise ValueError("Unsupported channel binding type")
571 if cb_type != "tls-unique":
572 raise NotImplementedError(
573 "{0} channel binding type not implemented"
574 .format(cb_type))
575 if self._sslobj is None:
576 return None
577 return self._sslobj.tls_unique_cb()
578
Guido van Rossume6650f92007-12-06 19:05:55 +0000579 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000580 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000581 self._real_close()
582
Bill Janssen54cc54c2007-12-14 22:08:56 +0000583
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584def wrap_socket(sock, keyfile=None, certfile=None,
585 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000586 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000587 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100588 suppress_ragged_eofs=True,
589 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Bill Janssen6e027db2007-11-15 22:23:56 +0000591 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000593 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000594 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000595 suppress_ragged_eofs=suppress_ragged_eofs,
596 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Thomas Woutersed03b412007-08-28 21:37:11 +0000598# some utility functions
599
600def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000601 """Takes a date-time string in standard ASN1_print form
602 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
603 a Python time value in seconds past the epoch."""
604
Thomas Woutersed03b412007-08-28 21:37:11 +0000605 import time
606 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
607
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608PEM_HEADER = "-----BEGIN CERTIFICATE-----"
609PEM_FOOTER = "-----END CERTIFICATE-----"
610
611def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612 """Takes a certificate in binary DER format and returns the
613 PEM version of it as a string."""
614
Bill Janssen6e027db2007-11-15 22:23:56 +0000615 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
616 return (PEM_HEADER + '\n' +
617 textwrap.fill(f, 64) + '\n' +
618 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
620def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621 """Takes a certificate in ASCII PEM format and returns the
622 DER-encoded version of it as a byte sequence"""
623
624 if not pem_cert_string.startswith(PEM_HEADER):
625 raise ValueError("Invalid PEM encoding; must start with %s"
626 % PEM_HEADER)
627 if not pem_cert_string.strip().endswith(PEM_FOOTER):
628 raise ValueError("Invalid PEM encoding; must end with %s"
629 % PEM_FOOTER)
630 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000631 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000633def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634 """Retrieve the certificate from the server at the specified address,
635 and return it as a PEM-encoded string.
636 If 'ca_certs' is specified, validate the server cert against it.
637 If 'ssl_version' is specified, use it in the connection attempt."""
638
639 host, port = addr
640 if (ca_certs is not None):
641 cert_reqs = CERT_REQUIRED
642 else:
643 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200644 s = create_connection(addr)
645 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647 dercert = s.getpeercert(True)
648 s.close()
649 return DER_cert_to_PEM_cert(dercert)
650
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000651def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200652 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')