blob: b12b9fd1e6497b9f1e5ddf788432e170b85a3802 [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
80_PROTOCOL_NAMES = {
81 PROTOCOL_TLSv1: "TLSv1",
82 PROTOCOL_SSLv23: "SSLv23",
83 PROTOCOL_SSLv3: "SSLv3",
84}
85try:
86 from _ssl import PROTOCOL_SSLv2
87except ImportError:
88 pass
89else:
90 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000091
Thomas Wouters47b49bf2007-08-30 22:15:33 +000092from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000093from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000094from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000095import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000096import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000097import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000098
Thomas Woutersed03b412007-08-28 21:37:11 +000099
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000100class CertificateError(ValueError):
101 pass
102
103
104def _dnsname_to_pat(dn):
105 pats = []
106 for frag in dn.split(r'.'):
107 if frag == '*':
108 # When '*' is a fragment by itself, it matches a non-empty dotless
109 # fragment.
110 pats.append('[^.]+')
111 else:
112 # Otherwise, '*' matches any dotless fragment.
113 frag = re.escape(frag)
114 pats.append(frag.replace(r'\*', '[^.]*'))
115 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
116
117
118def match_hostname(cert, hostname):
119 """Verify that *cert* (in decoded format as returned by
120 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
121 are mostly followed, but IP addresses are not accepted for *hostname*.
122
123 CertificateError is raised on failure. On success, the function
124 returns nothing.
125 """
126 if not cert:
127 raise ValueError("empty or no certificate")
128 dnsnames = []
129 san = cert.get('subjectAltName', ())
130 for key, value in san:
131 if key == 'DNS':
132 if _dnsname_to_pat(value).match(hostname):
133 return
134 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200135 if not dnsnames:
136 # The subject is only checked when there is no dNSName entry
137 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000138 for sub in cert.get('subject', ()):
139 for key, value in sub:
140 # XXX according to RFC 2818, the most specific Common Name
141 # must be used.
142 if key == 'commonName':
143 if _dnsname_to_pat(value).match(hostname):
144 return
145 dnsnames.append(value)
146 if len(dnsnames) > 1:
147 raise CertificateError("hostname %r "
148 "doesn't match either of %s"
149 % (hostname, ', '.join(map(repr, dnsnames))))
150 elif len(dnsnames) == 1:
151 raise CertificateError("hostname %r "
152 "doesn't match %r"
153 % (hostname, dnsnames[0]))
154 else:
155 raise CertificateError("no appropriate commonName or "
156 "subjectAltName fields were found")
157
158
Antoine Pitrou152efa22010-05-16 18:19:27 +0000159class SSLContext(_SSLContext):
160 """An SSLContext holds various SSL-related configuration options and
161 data, such as certificates and possibly a private key."""
162
163 __slots__ = ('protocol',)
164
165 def __new__(cls, protocol, *args, **kwargs):
166 return _SSLContext.__new__(cls, protocol)
167
168 def __init__(self, protocol):
169 self.protocol = protocol
170
171 def wrap_socket(self, sock, server_side=False,
172 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000173 suppress_ragged_eofs=True,
174 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000175 return SSLSocket(sock=sock, server_side=server_side,
176 do_handshake_on_connect=do_handshake_on_connect,
177 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000178 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000179 _context=self)
180
181
182class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000183 """This class implements a subtype of socket.socket that wraps
184 the underlying OS socket in an SSL context when necessary, and
185 provides read and write methods over that channel."""
186
Bill Janssen6e027db2007-11-15 22:23:56 +0000187 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000188 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000189 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
190 do_handshake_on_connect=True,
191 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000192 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000193 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000195
Antoine Pitrou152efa22010-05-16 18:19:27 +0000196 if _context:
197 self.context = _context
198 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000199 if server_side and not certfile:
200 raise ValueError("certfile must be specified for server-side "
201 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000202 if keyfile and not certfile:
203 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204 if certfile and not keyfile:
205 keyfile = certfile
206 self.context = SSLContext(ssl_version)
207 self.context.verify_mode = cert_reqs
208 if ca_certs:
209 self.context.load_verify_locations(ca_certs)
210 if certfile:
211 self.context.load_cert_chain(certfile, keyfile)
212 if ciphers:
213 self.context.set_ciphers(ciphers)
214 self.keyfile = keyfile
215 self.certfile = certfile
216 self.cert_reqs = cert_reqs
217 self.ssl_version = ssl_version
218 self.ca_certs = ca_certs
219 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000220 if server_side and server_hostname:
221 raise ValueError("server_hostname can only be specified "
222 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000223 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000224 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225 self.do_handshake_on_connect = do_handshake_on_connect
226 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000227 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000228 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000229 socket.__init__(self,
230 family=sock.family,
231 type=sock.type,
232 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000233 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000234 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000235 # see if it's connected
236 try:
237 sock.getpeername()
238 except socket_error as e:
239 if e.errno != errno.ENOTCONN:
240 raise
241 else:
242 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000243 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000244 elif fileno is not None:
245 socket.__init__(self, fileno=fileno)
246 else:
247 socket.__init__(self, family=family, type=type, proto=proto)
248
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000249 self._closed = False
250 self._sslobj = None
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000251 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000252 if connected:
253 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000254 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000255 self._sslobj = self.context._wrap_socket(self, server_side,
256 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000257 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000258 timeout = self.gettimeout()
259 if timeout == 0.0:
260 # non-blocking
261 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000262 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000263
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 except socket_error as x:
265 self.close()
266 raise x
267
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000268 def dup(self):
269 raise NotImplemented("Can't dup() %s instances" %
270 self.__class__.__name__)
271
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 def _checkClosed(self, msg=None):
273 # raise an exception here if you wish to check for spurious closes
274 pass
275
Bill Janssen54cc54c2007-12-14 22:08:56 +0000276 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000277 """Read up to LEN bytes and return them.
278 Return zero-length string on EOF."""
279
Bill Janssen6e027db2007-11-15 22:23:56 +0000280 self._checkClosed()
281 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000282 if buffer is not None:
283 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000284 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000285 v = self._sslobj.read(len or 1024)
286 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000287 except SSLError as x:
288 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000289 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000290 return 0
291 else:
292 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000293 else:
294 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000295
296 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000297 """Write DATA to the underlying SSL channel. Returns
298 number of bytes of DATA actually transmitted."""
299
Bill Janssen6e027db2007-11-15 22:23:56 +0000300 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000301 return self._sslobj.write(data)
302
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000304 """Returns a formatted version of the data in the
305 certificate provided by the other end of the SSL channel.
306 Return None if no certificate was provided, {} if a
307 certificate was provided, but not validated."""
308
Bill Janssen6e027db2007-11-15 22:23:56 +0000309 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310 return self._sslobj.peer_certificate(binary_form)
311
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000312 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000313 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000314 if not self._sslobj:
315 return None
316 else:
317 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000318
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000319 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000320 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000321 if self._sslobj:
322 if flags != 0:
323 raise ValueError(
324 "non-zero flags not allowed in calls to send() on %s" %
325 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 while True:
327 try:
328 v = self._sslobj.write(data)
329 except SSLError as x:
330 if x.args[0] == SSL_ERROR_WANT_READ:
331 return 0
332 elif x.args[0] == SSL_ERROR_WANT_WRITE:
333 return 0
334 else:
335 raise
336 else:
337 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000338 else:
339 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000340
Antoine Pitroua468adc2010-09-14 14:43:44 +0000341 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000342 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000344 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000345 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000346 elif addr is None:
347 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000349 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000350
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000351 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000352 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000353 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000354 if flags != 0:
355 raise ValueError(
356 "non-zero flags not allowed in calls to sendall() on %s" %
357 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 amount = len(data)
359 count = 0
360 while (count < amount):
361 v = self.send(data[count:])
362 count += v
363 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000364 else:
365 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000366
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000367 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000368 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000369 if self._sslobj:
370 if flags != 0:
371 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000372 "non-zero flags not allowed in calls to recv() on %s" %
373 self.__class__)
374 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000375 else:
376 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000377
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000378 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000379 self._checkClosed()
380 if buffer and (nbytes is None):
381 nbytes = len(buffer)
382 elif nbytes is None:
383 nbytes = 1024
384 if self._sslobj:
385 if flags != 0:
386 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000387 "non-zero flags not allowed in calls to recv_into() on %s" %
388 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000389 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000390 else:
391 return socket.recv_into(self, buffer, nbytes, flags)
392
Antoine Pitroua468adc2010-09-14 14:43:44 +0000393 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000394 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000395 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000396 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000397 self.__class__)
398 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000399 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000400
Bill Janssen58afe4c2008-09-08 16:45:19 +0000401 def recvfrom_into(self, buffer, nbytes=None, flags=0):
402 self._checkClosed()
403 if self._sslobj:
404 raise ValueError("recvfrom_into not allowed on instances of %s" %
405 self.__class__)
406 else:
407 return socket.recvfrom_into(self, buffer, nbytes, flags)
408
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000409 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000410 self._checkClosed()
411 if self._sslobj:
412 return self._sslobj.pending()
413 else:
414 return 0
415
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000416 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000417 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000418 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000419 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000420
Ezio Melottidc55e672010-01-18 09:15:14 +0000421 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000422 if self._sslobj:
423 s = self._sslobj.shutdown()
424 self._sslobj = None
425 return s
426 else:
427 raise ValueError("No SSL wrapper around " + str(self))
428
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000429 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000430 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000431 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000432 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000433
Bill Janssen48dc27c2007-12-05 03:38:10 +0000434 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000435 """Perform a TLS/SSL handshake."""
436
Bill Janssen48dc27c2007-12-05 03:38:10 +0000437 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000438 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000439 if timeout == 0.0 and block:
440 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000441 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000442 finally:
443 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000444
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000445 def _real_connect(self, addr, return_errno):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000446 if self.server_side:
447 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000448 # Here we assume that the socket is client-side, and not
449 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000450 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000452 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000453 try:
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000454 socket.connect(self, addr)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000455 if self.do_handshake_on_connect:
456 self.do_handshake()
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000457 except socket_error as e:
458 if return_errno:
459 return e.errno
460 else:
461 self._sslobj = None
462 raise e
463 self._connected = True
464 return 0
465
466 def connect(self, addr):
467 """Connects to remote ADDR, and then wraps the connection in
468 an SSL channel."""
469 self._real_connect(addr, False)
470
471 def connect_ex(self, addr):
472 """Connects to remote ADDR, and then wraps the connection in
473 an SSL channel."""
474 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000475
476 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000477 """Accepts a new connection from a remote client, and returns
478 a tuple containing that new connection wrapped with a server-side
479 SSL channel, and the address of the remote client."""
480
481 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000482 return (SSLSocket(sock=newsock,
483 keyfile=self.keyfile, certfile=self.certfile,
484 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000485 cert_reqs=self.cert_reqs,
486 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000487 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000488 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000489 do_handshake_on_connect=
490 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000491 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492
Guido van Rossume6650f92007-12-06 19:05:55 +0000493 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000494 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000495 self._real_close()
496
Bill Janssen54cc54c2007-12-14 22:08:56 +0000497
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498def wrap_socket(sock, keyfile=None, certfile=None,
499 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000500 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000501 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000502 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Bill Janssen6e027db2007-11-15 22:23:56 +0000504 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000506 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000507 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000508 suppress_ragged_eofs=suppress_ragged_eofs,
509 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Thomas Woutersed03b412007-08-28 21:37:11 +0000511# some utility functions
512
513def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000514 """Takes a date-time string in standard ASN1_print form
515 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
516 a Python time value in seconds past the epoch."""
517
Thomas Woutersed03b412007-08-28 21:37:11 +0000518 import time
519 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
520
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521PEM_HEADER = "-----BEGIN CERTIFICATE-----"
522PEM_FOOTER = "-----END CERTIFICATE-----"
523
524def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525 """Takes a certificate in binary DER format and returns the
526 PEM version of it as a string."""
527
Bill Janssen6e027db2007-11-15 22:23:56 +0000528 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
529 return (PEM_HEADER + '\n' +
530 textwrap.fill(f, 64) + '\n' +
531 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
533def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534 """Takes a certificate in ASCII PEM format and returns the
535 DER-encoded version of it as a byte sequence"""
536
537 if not pem_cert_string.startswith(PEM_HEADER):
538 raise ValueError("Invalid PEM encoding; must start with %s"
539 % PEM_HEADER)
540 if not pem_cert_string.strip().endswith(PEM_FOOTER):
541 raise ValueError("Invalid PEM encoding; must end with %s"
542 % PEM_FOOTER)
543 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000544 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000546def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547 """Retrieve the certificate from the server at the specified address,
548 and return it as a PEM-encoded string.
549 If 'ca_certs' is specified, validate the server cert against it.
550 If 'ssl_version' is specified, use it in the connection attempt."""
551
552 host, port = addr
553 if (ca_certs is not None):
554 cert_reqs = CERT_REQUIRED
555 else:
556 cert_reqs = CERT_NONE
557 s = wrap_socket(socket(), ssl_version=ssl_version,
558 cert_reqs=cert_reqs, ca_certs=ca_certs)
559 s.connect(addr)
560 dercert = s.getpeercert(True)
561 s.close()
562 return DER_cert_to_PEM_cert(dercert)
563
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000564def get_protocol_name(protocol_code):
Victor Stinneree18b6f2011-05-10 00:38:00 +0200565 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')