blob: 813723171188488e0c2f74f1abb3dea011823c35 [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 Pitrou152efa22010-05-16 18:19:27 +000063from _ssl import _SSLContext, SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000064from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Antoine Pitroub5218772010-05-21 09:56:06 +000065from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000066from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000067from _ssl import (
68 SSL_ERROR_ZERO_RETURN,
69 SSL_ERROR_WANT_READ,
70 SSL_ERROR_WANT_WRITE,
71 SSL_ERROR_WANT_X509_LOOKUP,
72 SSL_ERROR_SYSCALL,
73 SSL_ERROR_SSL,
74 SSL_ERROR_WANT_CONNECT,
75 SSL_ERROR_EOF,
76 SSL_ERROR_INVALID_ERROR_CODE,
77 )
Antoine Pitroud5323212010-10-22 18:19:07 +000078from _ssl import HAS_SNI
Victor Stinneree18b6f2011-05-10 00:38:00 +020079from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020080from _ssl import _OPENSSL_API_VERSION
81
Victor Stinneree18b6f2011-05-10 00:38:00 +020082_PROTOCOL_NAMES = {
83 PROTOCOL_TLSv1: "TLSv1",
84 PROTOCOL_SSLv23: "SSLv23",
85 PROTOCOL_SSLv3: "SSLv3",
86}
87try:
88 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +010089 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinneree18b6f2011-05-10 00:38:00 +020090except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +010091 _SSLv2_IF_EXISTS = None
Victor Stinneree18b6f2011-05-10 00:38:00 +020092else:
93 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000094
Thomas Wouters47b49bf2007-08-30 22:15:33 +000095from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000096from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000097from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000099import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000100import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000101
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100102# Disable weak or insecure ciphers by default
103# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
104_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
105
Thomas Woutersed03b412007-08-28 21:37:11 +0000106
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000107class CertificateError(ValueError):
108 pass
109
110
111def _dnsname_to_pat(dn):
112 pats = []
113 for frag in dn.split(r'.'):
114 if frag == '*':
115 # When '*' is a fragment by itself, it matches a non-empty dotless
116 # fragment.
117 pats.append('[^.]+')
118 else:
119 # Otherwise, '*' matches any dotless fragment.
120 frag = re.escape(frag)
121 pats.append(frag.replace(r'\*', '[^.]*'))
122 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
123
124
125def match_hostname(cert, hostname):
126 """Verify that *cert* (in decoded format as returned by
127 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
128 are mostly followed, but IP addresses are not accepted for *hostname*.
129
130 CertificateError is raised on failure. On success, the function
131 returns nothing.
132 """
133 if not cert:
134 raise ValueError("empty or no certificate")
135 dnsnames = []
136 san = cert.get('subjectAltName', ())
137 for key, value in san:
138 if key == 'DNS':
139 if _dnsname_to_pat(value).match(hostname):
140 return
141 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200142 if not dnsnames:
143 # The subject is only checked when there is no dNSName entry
144 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000145 for sub in cert.get('subject', ()):
146 for key, value in sub:
147 # XXX according to RFC 2818, the most specific Common Name
148 # must be used.
149 if key == 'commonName':
150 if _dnsname_to_pat(value).match(hostname):
151 return
152 dnsnames.append(value)
153 if len(dnsnames) > 1:
154 raise CertificateError("hostname %r "
155 "doesn't match either of %s"
156 % (hostname, ', '.join(map(repr, dnsnames))))
157 elif len(dnsnames) == 1:
158 raise CertificateError("hostname %r "
159 "doesn't match %r"
160 % (hostname, dnsnames[0]))
161 else:
162 raise CertificateError("no appropriate commonName or "
163 "subjectAltName fields were found")
164
165
Antoine Pitrou152efa22010-05-16 18:19:27 +0000166class SSLContext(_SSLContext):
167 """An SSLContext holds various SSL-related configuration options and
168 data, such as certificates and possibly a private key."""
169
170 __slots__ = ('protocol',)
171
172 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100173 self = _SSLContext.__new__(cls, protocol)
174 if protocol != _SSLv2_IF_EXISTS:
175 self.set_ciphers(_DEFAULT_CIPHERS)
176 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000177
178 def __init__(self, protocol):
179 self.protocol = protocol
180
181 def wrap_socket(self, sock, server_side=False,
182 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000183 suppress_ragged_eofs=True,
184 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000185 return SSLSocket(sock=sock, server_side=server_side,
186 do_handshake_on_connect=do_handshake_on_connect,
187 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000188 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189 _context=self)
190
191
192class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000193 """This class implements a subtype of socket.socket that wraps
194 the underlying OS socket in an SSL context when necessary, and
195 provides read and write methods over that channel."""
196
Bill Janssen6e027db2007-11-15 22:23:56 +0000197 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000198 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000199 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
200 do_handshake_on_connect=True,
201 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000203 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000205
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 if _context:
207 self.context = _context
208 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000209 if server_side and not certfile:
210 raise ValueError("certfile must be specified for server-side "
211 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000212 if keyfile and not certfile:
213 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214 if certfile and not keyfile:
215 keyfile = certfile
216 self.context = SSLContext(ssl_version)
217 self.context.verify_mode = cert_reqs
218 if ca_certs:
219 self.context.load_verify_locations(ca_certs)
220 if certfile:
221 self.context.load_cert_chain(certfile, keyfile)
222 if ciphers:
223 self.context.set_ciphers(ciphers)
224 self.keyfile = keyfile
225 self.certfile = certfile
226 self.cert_reqs = cert_reqs
227 self.ssl_version = ssl_version
228 self.ca_certs = ca_certs
229 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000230 if server_side and server_hostname:
231 raise ValueError("server_hostname can only be specified "
232 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000233 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000234 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235 self.do_handshake_on_connect = do_handshake_on_connect
236 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000237 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000238 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000239 socket.__init__(self,
240 family=sock.family,
241 type=sock.type,
242 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000243 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000244 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000245 # see if it's connected
246 try:
247 sock.getpeername()
248 except socket_error as e:
249 if e.errno != errno.ENOTCONN:
250 raise
251 else:
252 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000253 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000254 elif fileno is not None:
255 socket.__init__(self, fileno=fileno)
256 else:
257 socket.__init__(self, family=family, type=type, proto=proto)
258
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000259 self._closed = False
260 self._sslobj = None
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000261 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000262 if connected:
263 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000265 self._sslobj = self.context._wrap_socket(self, server_side,
266 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000267 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000268 timeout = self.gettimeout()
269 if timeout == 0.0:
270 # non-blocking
271 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000273
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 except socket_error as x:
275 self.close()
276 raise x
277
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000278 def dup(self):
279 raise NotImplemented("Can't dup() %s instances" %
280 self.__class__.__name__)
281
Bill Janssen6e027db2007-11-15 22:23:56 +0000282 def _checkClosed(self, msg=None):
283 # raise an exception here if you wish to check for spurious closes
284 pass
285
Bill Janssen54cc54c2007-12-14 22:08:56 +0000286 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000287 """Read up to LEN bytes and return them.
288 Return zero-length string on EOF."""
289
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 self._checkClosed()
291 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000292 if buffer is not None:
293 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000294 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000295 v = self._sslobj.read(len or 1024)
296 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000297 except SSLError as x:
298 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000299 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000300 return 0
301 else:
302 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 else:
304 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000305
306 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000307 """Write DATA to the underlying SSL channel. Returns
308 number of bytes of DATA actually transmitted."""
309
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000311 return self._sslobj.write(data)
312
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000313 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000314 """Returns a formatted version of the data in the
315 certificate provided by the other end of the SSL channel.
316 Return None if no certificate was provided, {} if a
317 certificate was provided, but not validated."""
318
Bill Janssen6e027db2007-11-15 22:23:56 +0000319 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000320 return self._sslobj.peer_certificate(binary_form)
321
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000322 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000323 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000324 if not self._sslobj:
325 return None
326 else:
327 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000328
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000329 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000331 if self._sslobj:
332 if flags != 0:
333 raise ValueError(
334 "non-zero flags not allowed in calls to send() on %s" %
335 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000336 while True:
337 try:
338 v = self._sslobj.write(data)
339 except SSLError as x:
340 if x.args[0] == SSL_ERROR_WANT_READ:
341 return 0
342 elif x.args[0] == SSL_ERROR_WANT_WRITE:
343 return 0
344 else:
345 raise
346 else:
347 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 else:
349 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000350
Antoine Pitroua468adc2010-09-14 14:43:44 +0000351 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000352 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000353 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000354 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000356 elif addr is None:
357 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000358 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000359 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000360
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000361 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000362 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000363 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000364 if flags != 0:
365 raise ValueError(
366 "non-zero flags not allowed in calls to sendall() on %s" %
367 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000368 amount = len(data)
369 count = 0
370 while (count < amount):
371 v = self.send(data[count:])
372 count += v
373 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000374 else:
375 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000376
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000377 def recv(self, buflen=1024, 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(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000382 "non-zero flags not allowed in calls to recv() on %s" %
383 self.__class__)
384 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000385 else:
386 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000387
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000388 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 self._checkClosed()
390 if buffer and (nbytes is None):
391 nbytes = len(buffer)
392 elif nbytes is None:
393 nbytes = 1024
394 if self._sslobj:
395 if flags != 0:
396 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000397 "non-zero flags not allowed in calls to recv_into() on %s" %
398 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000399 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 else:
401 return socket.recv_into(self, buffer, nbytes, flags)
402
Antoine Pitroua468adc2010-09-14 14:43:44 +0000403 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000404 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000405 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000406 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000407 self.__class__)
408 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000409 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000410
Bill Janssen58afe4c2008-09-08 16:45:19 +0000411 def recvfrom_into(self, buffer, nbytes=None, flags=0):
412 self._checkClosed()
413 if self._sslobj:
414 raise ValueError("recvfrom_into not allowed on instances of %s" %
415 self.__class__)
416 else:
417 return socket.recvfrom_into(self, buffer, nbytes, flags)
418
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000419 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000420 self._checkClosed()
421 if self._sslobj:
422 return self._sslobj.pending()
423 else:
424 return 0
425
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000426 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000427 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000429 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000430
Ezio Melottidc55e672010-01-18 09:15:14 +0000431 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000432 if self._sslobj:
433 s = self._sslobj.shutdown()
434 self._sslobj = None
435 return s
436 else:
437 raise ValueError("No SSL wrapper around " + str(self))
438
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000439 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000441 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000442 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000443
Bill Janssen48dc27c2007-12-05 03:38:10 +0000444 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000445 """Perform a TLS/SSL handshake."""
446
Bill Janssen48dc27c2007-12-05 03:38:10 +0000447 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000448 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000449 if timeout == 0.0 and block:
450 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000451 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000452 finally:
453 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000454
Antoine Pitroub4410db2011-05-18 18:51:06 +0200455 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000456 if self.server_side:
457 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000458 # Here we assume that the socket is client-side, and not
459 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000460 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000462 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000463 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200464 if connect_ex:
465 rc = socket.connect_ex(self, addr)
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000466 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200467 rc = None
468 socket.connect(self, addr)
469 if not rc:
470 if self.do_handshake_on_connect:
471 self.do_handshake()
472 self._connected = True
473 return rc
474 except socket_error:
475 self._sslobj = None
476 raise
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000477
478 def connect(self, addr):
479 """Connects to remote ADDR, and then wraps the connection in
480 an SSL channel."""
481 self._real_connect(addr, False)
482
483 def connect_ex(self, addr):
484 """Connects to remote ADDR, and then wraps the connection in
485 an SSL channel."""
486 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000487
488 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000489 """Accepts a new connection from a remote client, and returns
490 a tuple containing that new connection wrapped with a server-side
491 SSL channel, and the address of the remote client."""
492
493 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000494 return (SSLSocket(sock=newsock,
495 keyfile=self.keyfile, certfile=self.certfile,
496 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000497 cert_reqs=self.cert_reqs,
498 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000499 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000500 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000501 do_handshake_on_connect=
502 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000503 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
Guido van Rossume6650f92007-12-06 19:05:55 +0000505 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000506 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000507 self._real_close()
508
Bill Janssen54cc54c2007-12-14 22:08:56 +0000509
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510def wrap_socket(sock, keyfile=None, certfile=None,
511 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000512 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000513 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000514 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Bill Janssen6e027db2007-11-15 22:23:56 +0000516 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000518 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000519 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000520 suppress_ragged_eofs=suppress_ragged_eofs,
521 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Thomas Woutersed03b412007-08-28 21:37:11 +0000523# some utility functions
524
525def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000526 """Takes a date-time string in standard ASN1_print form
527 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
528 a Python time value in seconds past the epoch."""
529
Thomas Woutersed03b412007-08-28 21:37:11 +0000530 import time
531 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
532
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000533PEM_HEADER = "-----BEGIN CERTIFICATE-----"
534PEM_FOOTER = "-----END CERTIFICATE-----"
535
536def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 """Takes a certificate in binary DER format and returns the
538 PEM version of it as a string."""
539
Bill Janssen6e027db2007-11-15 22:23:56 +0000540 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
541 return (PEM_HEADER + '\n' +
542 textwrap.fill(f, 64) + '\n' +
543 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
545def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546 """Takes a certificate in ASCII PEM format and returns the
547 DER-encoded version of it as a byte sequence"""
548
549 if not pem_cert_string.startswith(PEM_HEADER):
550 raise ValueError("Invalid PEM encoding; must start with %s"
551 % PEM_HEADER)
552 if not pem_cert_string.strip().endswith(PEM_FOOTER):
553 raise ValueError("Invalid PEM encoding; must end with %s"
554 % PEM_FOOTER)
555 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000556 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000558def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559 """Retrieve the certificate from the server at the specified address,
560 and return it as a PEM-encoded string.
561 If 'ca_certs' is specified, validate the server cert against it.
562 If 'ssl_version' is specified, use it in the connection attempt."""
563
564 host, port = addr
565 if (ca_certs is not None):
566 cert_reqs = CERT_REQUIRED
567 else:
568 cert_reqs = CERT_NONE
569 s = wrap_socket(socket(), ssl_version=ssl_version,
570 cert_reqs=cert_reqs, ca_certs=ca_certs)
571 s.connect(addr)
572 dercert = s.getpeercert(True)
573 s.close()
574 return DER_cert_to_PEM_cert(dercert)
575
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000576def get_protocol_name(protocol_code):
Victor Stinneree18b6f2011-05-10 00:38:00 +0200577 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')