blob: 1a7f599ea86cfd66499036afa6579b5499d1cd27 [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
Victor Stinner99c8b162011-05-24 12:05:19 +020066from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
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 Stinner3de49192011-05-09 00:42:58 +020079from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
80 PROTOCOL_TLSv1)
81_PROTOCOL_NAMES = {
82 PROTOCOL_TLSv1: "TLSv1",
83 PROTOCOL_SSLv23: "SSLv23",
84 PROTOCOL_SSLv3: "SSLv3",
85}
86try:
87 from _ssl import PROTOCOL_SSLv2
88except ImportError:
89 pass
90else:
91 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000092
Thomas Wouters47b49bf2007-08-30 22:15:33 +000093from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000094from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +020095from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000097import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000098import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000099
Thomas Woutersed03b412007-08-28 21:37:11 +0000100
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000101class CertificateError(ValueError):
102 pass
103
104
105def _dnsname_to_pat(dn):
106 pats = []
107 for frag in dn.split(r'.'):
108 if frag == '*':
109 # When '*' is a fragment by itself, it matches a non-empty dotless
110 # fragment.
111 pats.append('[^.]+')
112 else:
113 # Otherwise, '*' matches any dotless fragment.
114 frag = re.escape(frag)
115 pats.append(frag.replace(r'\*', '[^.]*'))
116 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
117
118
119def match_hostname(cert, hostname):
120 """Verify that *cert* (in decoded format as returned by
121 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
122 are mostly followed, but IP addresses are not accepted for *hostname*.
123
124 CertificateError is raised on failure. On success, the function
125 returns nothing.
126 """
127 if not cert:
128 raise ValueError("empty or no certificate")
129 dnsnames = []
130 san = cert.get('subjectAltName', ())
131 for key, value in san:
132 if key == 'DNS':
133 if _dnsname_to_pat(value).match(hostname):
134 return
135 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200136 if not dnsnames:
137 # The subject is only checked when there is no dNSName entry
138 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000139 for sub in cert.get('subject', ()):
140 for key, value in sub:
141 # XXX according to RFC 2818, the most specific Common Name
142 # must be used.
143 if key == 'commonName':
144 if _dnsname_to_pat(value).match(hostname):
145 return
146 dnsnames.append(value)
147 if len(dnsnames) > 1:
148 raise CertificateError("hostname %r "
149 "doesn't match either of %s"
150 % (hostname, ', '.join(map(repr, dnsnames))))
151 elif len(dnsnames) == 1:
152 raise CertificateError("hostname %r "
153 "doesn't match %r"
154 % (hostname, dnsnames[0]))
155 else:
156 raise CertificateError("no appropriate commonName or "
157 "subjectAltName fields were found")
158
159
Antoine Pitrou152efa22010-05-16 18:19:27 +0000160class SSLContext(_SSLContext):
161 """An SSLContext holds various SSL-related configuration options and
162 data, such as certificates and possibly a private key."""
163
164 __slots__ = ('protocol',)
165
166 def __new__(cls, protocol, *args, **kwargs):
167 return _SSLContext.__new__(cls, protocol)
168
169 def __init__(self, protocol):
170 self.protocol = protocol
171
172 def wrap_socket(self, sock, server_side=False,
173 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000174 suppress_ragged_eofs=True,
175 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000176 return SSLSocket(sock=sock, server_side=server_side,
177 do_handshake_on_connect=do_handshake_on_connect,
178 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000179 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000180 _context=self)
181
182
183class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000184 """This class implements a subtype of socket.socket that wraps
185 the underlying OS socket in an SSL context when necessary, and
186 provides read and write methods over that channel."""
187
Bill Janssen6e027db2007-11-15 22:23:56 +0000188 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000189 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000190 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
191 do_handshake_on_connect=True,
192 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000193 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000194 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000195 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000196
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197 if _context:
198 self.context = _context
199 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000200 if server_side and not certfile:
201 raise ValueError("certfile must be specified for server-side "
202 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000203 if keyfile and not certfile:
204 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000205 if certfile and not keyfile:
206 keyfile = certfile
207 self.context = SSLContext(ssl_version)
208 self.context.verify_mode = cert_reqs
209 if ca_certs:
210 self.context.load_verify_locations(ca_certs)
211 if certfile:
212 self.context.load_cert_chain(certfile, keyfile)
213 if ciphers:
214 self.context.set_ciphers(ciphers)
215 self.keyfile = keyfile
216 self.certfile = certfile
217 self.cert_reqs = cert_reqs
218 self.ssl_version = ssl_version
219 self.ca_certs = ca_certs
220 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000221 if server_side and server_hostname:
222 raise ValueError("server_hostname can only be specified "
223 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000224 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000225 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000226 self.do_handshake_on_connect = do_handshake_on_connect
227 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000228 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000229 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000230 socket.__init__(self,
231 family=sock.family,
232 type=sock.type,
233 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000234 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000235 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000236 # see if it's connected
237 try:
238 sock.getpeername()
239 except socket_error as e:
240 if e.errno != errno.ENOTCONN:
241 raise
242 else:
243 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000244 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000245 elif fileno is not None:
246 socket.__init__(self, fileno=fileno)
247 else:
248 socket.__init__(self, family=family, type=type, proto=proto)
249
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000250 self._closed = False
251 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000252 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000253 if connected:
254 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000255 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000256 self._sslobj = self.context._wrap_socket(self, server_side,
257 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000258 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000259 timeout = self.gettimeout()
260 if timeout == 0.0:
261 # non-blocking
262 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000263 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000264
Bill Janssen6e027db2007-11-15 22:23:56 +0000265 except socket_error as x:
266 self.close()
267 raise x
268
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000269 def dup(self):
270 raise NotImplemented("Can't dup() %s instances" %
271 self.__class__.__name__)
272
Bill Janssen6e027db2007-11-15 22:23:56 +0000273 def _checkClosed(self, msg=None):
274 # raise an exception here if you wish to check for spurious closes
275 pass
276
Bill Janssen54cc54c2007-12-14 22:08:56 +0000277 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000278 """Read up to LEN bytes and return them.
279 Return zero-length string on EOF."""
280
Bill Janssen6e027db2007-11-15 22:23:56 +0000281 self._checkClosed()
282 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000283 if buffer is not None:
284 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000285 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000286 v = self._sslobj.read(len or 1024)
287 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 except SSLError as x:
289 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000290 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000291 return 0
292 else:
293 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000294 else:
295 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000296
297 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000298 """Write DATA to the underlying SSL channel. Returns
299 number of bytes of DATA actually transmitted."""
300
Bill Janssen6e027db2007-11-15 22:23:56 +0000301 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000302 return self._sslobj.write(data)
303
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000305 """Returns a formatted version of the data in the
306 certificate provided by the other end of the SSL channel.
307 Return None if no certificate was provided, {} if a
308 certificate was provided, but not validated."""
309
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000311 return self._sslobj.peer_certificate(binary_form)
312
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000313 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000314 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000315 if not self._sslobj:
316 return None
317 else:
318 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000319
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000320 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000321 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000322 if self._sslobj:
323 if flags != 0:
324 raise ValueError(
325 "non-zero flags not allowed in calls to send() on %s" %
326 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000327 while True:
328 try:
329 v = self._sslobj.write(data)
330 except SSLError as x:
331 if x.args[0] == SSL_ERROR_WANT_READ:
332 return 0
333 elif x.args[0] == SSL_ERROR_WANT_WRITE:
334 return 0
335 else:
336 raise
337 else:
338 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000339 else:
340 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000341
Antoine Pitroua468adc2010-09-14 14:43:44 +0000342 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000343 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000344 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000345 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000346 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000347 elif addr is None:
348 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000349 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000350 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000351
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000352 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000353 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000354 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000355 if flags != 0:
356 raise ValueError(
357 "non-zero flags not allowed in calls to sendall() on %s" %
358 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000359 amount = len(data)
360 count = 0
361 while (count < amount):
362 v = self.send(data[count:])
363 count += v
364 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000365 else:
366 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000368 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000370 if self._sslobj:
371 if flags != 0:
372 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000373 "non-zero flags not allowed in calls to recv() on %s" %
374 self.__class__)
375 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376 else:
377 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000378
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000379 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000380 self._checkClosed()
381 if buffer and (nbytes is None):
382 nbytes = len(buffer)
383 elif nbytes is None:
384 nbytes = 1024
385 if self._sslobj:
386 if flags != 0:
387 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000388 "non-zero flags not allowed in calls to recv_into() on %s" %
389 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000390 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000391 else:
392 return socket.recv_into(self, buffer, nbytes, flags)
393
Antoine Pitroua468adc2010-09-14 14:43:44 +0000394 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000395 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000396 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000397 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000398 self.__class__)
399 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000400 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000401
Bill Janssen58afe4c2008-09-08 16:45:19 +0000402 def recvfrom_into(self, buffer, nbytes=None, flags=0):
403 self._checkClosed()
404 if self._sslobj:
405 raise ValueError("recvfrom_into not allowed on instances of %s" %
406 self.__class__)
407 else:
408 return socket.recvfrom_into(self, buffer, nbytes, flags)
409
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000410 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000411 self._checkClosed()
412 if self._sslobj:
413 return self._sslobj.pending()
414 else:
415 return 0
416
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000417 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000418 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000419 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000420 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000421
Ezio Melottidc55e672010-01-18 09:15:14 +0000422 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000423 if self._sslobj:
424 s = self._sslobj.shutdown()
425 self._sslobj = None
426 return s
427 else:
428 raise ValueError("No SSL wrapper around " + str(self))
429
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000430 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000432 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000433 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000434
Bill Janssen48dc27c2007-12-05 03:38:10 +0000435 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000436 """Perform a TLS/SSL handshake."""
437
Bill Janssen48dc27c2007-12-05 03:38:10 +0000438 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000439 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000440 if timeout == 0.0 and block:
441 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000442 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000443 finally:
444 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000445
Antoine Pitroub4410db2011-05-18 18:51:06 +0200446 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000447 if self.server_side:
448 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000449 # Here we assume that the socket is client-side, and not
450 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000451 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000453 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000454 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200455 if connect_ex:
456 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000457 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200458 rc = None
459 socket.connect(self, addr)
460 if not rc:
461 if self.do_handshake_on_connect:
462 self.do_handshake()
463 self._connected = True
464 return rc
465 except socket_error:
466 self._sslobj = None
467 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000468
469 def connect(self, addr):
470 """Connects to remote ADDR, and then wraps the connection in
471 an SSL channel."""
472 self._real_connect(addr, False)
473
474 def connect_ex(self, addr):
475 """Connects to remote ADDR, and then wraps the connection in
476 an SSL channel."""
477 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000478
479 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000480 """Accepts a new connection from a remote client, and returns
481 a tuple containing that new connection wrapped with a server-side
482 SSL channel, and the address of the remote client."""
483
484 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000485 return (SSLSocket(sock=newsock,
486 keyfile=self.keyfile, certfile=self.certfile,
487 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000488 cert_reqs=self.cert_reqs,
489 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000490 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000491 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000492 do_handshake_on_connect=
493 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000494 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Guido van Rossume6650f92007-12-06 19:05:55 +0000496 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000497 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000498 self._real_close()
499
Bill Janssen54cc54c2007-12-14 22:08:56 +0000500
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501def wrap_socket(sock, keyfile=None, certfile=None,
502 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000503 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000504 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000505 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Bill Janssen6e027db2007-11-15 22:23:56 +0000507 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000509 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000510 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000511 suppress_ragged_eofs=suppress_ragged_eofs,
512 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513
Thomas Woutersed03b412007-08-28 21:37:11 +0000514# some utility functions
515
516def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000517 """Takes a date-time string in standard ASN1_print form
518 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
519 a Python time value in seconds past the epoch."""
520
Thomas Woutersed03b412007-08-28 21:37:11 +0000521 import time
522 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
523
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524PEM_HEADER = "-----BEGIN CERTIFICATE-----"
525PEM_FOOTER = "-----END CERTIFICATE-----"
526
527def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 """Takes a certificate in binary DER format and returns the
529 PEM version of it as a string."""
530
Bill Janssen6e027db2007-11-15 22:23:56 +0000531 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
532 return (PEM_HEADER + '\n' +
533 textwrap.fill(f, 64) + '\n' +
534 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
536def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 """Takes a certificate in ASCII PEM format and returns the
538 DER-encoded version of it as a byte sequence"""
539
540 if not pem_cert_string.startswith(PEM_HEADER):
541 raise ValueError("Invalid PEM encoding; must start with %s"
542 % PEM_HEADER)
543 if not pem_cert_string.strip().endswith(PEM_FOOTER):
544 raise ValueError("Invalid PEM encoding; must end with %s"
545 % PEM_FOOTER)
546 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000547 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000549def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550 """Retrieve the certificate from the server at the specified address,
551 and return it as a PEM-encoded string.
552 If 'ca_certs' is specified, validate the server cert against it.
553 If 'ssl_version' is specified, use it in the connection attempt."""
554
555 host, port = addr
556 if (ca_certs is not None):
557 cert_reqs = CERT_REQUIRED
558 else:
559 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200560 s = create_connection(addr)
561 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 dercert = s.getpeercert(True)
564 s.close()
565 return DER_cert_to_PEM_cert(dercert)
566
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000567def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200568 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')