blob: 3ee3d6ac0b2c7d2b22c65d88721f802e4659c98e [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
4"""\
5This module provides some more Pythonic support for SSL.
6
7Object types:
8
Bill Janssen98d19da2007-09-10 21:51:02 +00009 SSLSocket -- subtype of socket.socket which does SSL over the socket
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000010
11Exceptions:
12
Bill Janssen98d19da2007-09-10 21:51:02 +000013 SSLError -- exception raised for I/O errors
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000014
15Functions:
16
17 cert_time_to_seconds -- convert time string used for certificate
18 notBefore and notAfter functions to integer
19 seconds past the Epoch (the time values
20 returned from time.time())
21
22 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
23 by the server running on HOST at port PORT. No
24 validation of the certificate is performed.
25
26Integer constants:
27
28SSL_ERROR_ZERO_RETURN
29SSL_ERROR_WANT_READ
30SSL_ERROR_WANT_WRITE
31SSL_ERROR_WANT_X509_LOOKUP
32SSL_ERROR_SYSCALL
33SSL_ERROR_SSL
34SSL_ERROR_WANT_CONNECT
35
36SSL_ERROR_EOF
37SSL_ERROR_INVALID_ERROR_CODE
38
39The following group define certificate requirements that one side is
40allowing/requiring from the other side:
41
42CERT_NONE - no certificates from the other side are required (or will
43 be looked at if provided)
44CERT_OPTIONAL - certificates are not required, but if provided will be
45 validated, and if validation fails, the connection will
46 also fail
47CERT_REQUIRED - certificates are required, and will be validated, and
48 if validation fails, the connection will also fail
49
50The following constants identify various SSL protocol variants:
51
52PROTOCOL_SSLv2
53PROTOCOL_SSLv3
54PROTOCOL_SSLv23
55PROTOCOL_TLSv1
56"""
57
Christian Heimesc5f05e42008-02-23 17:40:11 +000058import textwrap
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000059
60import _ssl # if we can't import it, let the error propagate
Bill Janssen98d19da2007-09-10 21:51:02 +000061
62from _ssl import SSLError
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000063from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
64from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Bill Janssen98d19da2007-09-10 21:51:02 +000065from _ssl import RAND_status, RAND_egd, RAND_add
Bill Janssen426ea0a2007-08-29 22:35:05 +000066from _ssl import \
67 SSL_ERROR_ZERO_RETURN, \
68 SSL_ERROR_WANT_READ, \
69 SSL_ERROR_WANT_WRITE, \
70 SSL_ERROR_WANT_X509_LOOKUP, \
71 SSL_ERROR_SYSCALL, \
72 SSL_ERROR_SSL, \
73 SSL_ERROR_WANT_CONNECT, \
74 SSL_ERROR_EOF, \
75 SSL_ERROR_INVALID_ERROR_CODE
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000076
Antoine Pitrou3df58d12010-04-23 23:07:37 +000077from socket import socket, _fileobject, _delegate_methods
Bill Janssen426ea0a2007-08-29 22:35:05 +000078from socket import getnameinfo as _getnameinfo
Bill Janssen296a59d2007-09-16 22:06:00 +000079import base64 # for DER-to-PEM translation
Bill Janssen98d19da2007-09-10 21:51:02 +000080
Ezio Melotti259ea732010-01-18 09:12:06 +000081class SSLSocket(socket):
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000082
Bill Janssen426ea0a2007-08-29 22:35:05 +000083 """This class implements a subtype of socket.socket that wraps
84 the underlying OS socket in an SSL context when necessary, and
85 provides read and write methods over that channel."""
86
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000087 def __init__(self, sock, keyfile=None, certfile=None,
88 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen934b16d2008-06-28 22:19:33 +000089 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
90 do_handshake_on_connect=True,
91 suppress_ragged_eofs=True):
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000092 socket.__init__(self, _sock=sock._sock)
Antoine Pitrou3df58d12010-04-23 23:07:37 +000093 # The initializer for socket overrides the methods send(), recv(), etc.
94 # in the instancce, which we don't need -- but we want to provide the
95 # methods defined in SSLSocket.
96 for attr in _delegate_methods:
97 try:
98 delattr(self, attr)
99 except AttributeError:
100 pass
Bill Janssen934b16d2008-06-28 22:19:33 +0000101
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000102 if certfile and not keyfile:
103 keyfile = certfile
Bill Janssen426ea0a2007-08-29 22:35:05 +0000104 # see if it's connected
105 try:
106 socket.getpeername(self)
107 except:
108 # no, no connection yet
109 self._sslobj = None
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000110 else:
Bill Janssen426ea0a2007-08-29 22:35:05 +0000111 # yes, create the SSL object
112 self._sslobj = _ssl.sslwrap(self._sock, server_side,
113 keyfile, certfile,
114 cert_reqs, ssl_version, ca_certs)
Bill Janssen934b16d2008-06-28 22:19:33 +0000115 if do_handshake_on_connect:
116 timeout = self.gettimeout()
117 try:
118 self.settimeout(None)
119 self.do_handshake()
120 finally:
121 self.settimeout(timeout)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000122 self.keyfile = keyfile
123 self.certfile = certfile
124 self.cert_reqs = cert_reqs
125 self.ssl_version = ssl_version
126 self.ca_certs = ca_certs
Bill Janssen934b16d2008-06-28 22:19:33 +0000127 self.do_handshake_on_connect = do_handshake_on_connect
128 self.suppress_ragged_eofs = suppress_ragged_eofs
129 self._makefile_refs = 0
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000130
131 def read(self, len=1024):
Bill Janssen24bccf22007-08-30 17:07:28 +0000132
133 """Read up to LEN bytes and return them.
134 Return zero-length string on EOF."""
135
Bill Janssen934b16d2008-06-28 22:19:33 +0000136 try:
137 return self._sslobj.read(len)
138 except SSLError, x:
139 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
140 return ''
141 else:
142 raise
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000143
144 def write(self, data):
Bill Janssen24bccf22007-08-30 17:07:28 +0000145
146 """Write DATA to the underlying SSL channel. Returns
147 number of bytes of DATA actually transmitted."""
148
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000149 return self._sslobj.write(data)
150
Bill Janssen98d19da2007-09-10 21:51:02 +0000151 def getpeercert(self, binary_form=False):
Bill Janssen24bccf22007-08-30 17:07:28 +0000152
153 """Returns a formatted version of the data in the
154 certificate provided by the other end of the SSL channel.
155 Return None if no certificate was provided, {} if a
156 certificate was provided, but not validated."""
157
Bill Janssen98d19da2007-09-10 21:51:02 +0000158 return self._sslobj.peer_certificate(binary_form)
159
Ezio Melotti259ea732010-01-18 09:12:06 +0000160 def cipher(self):
Bill Janssen98d19da2007-09-10 21:51:02 +0000161
162 if not self._sslobj:
163 return None
164 else:
165 return self._sslobj.cipher()
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000166
Ezio Melotti259ea732010-01-18 09:12:06 +0000167 def send(self, data, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000168 if self._sslobj:
169 if flags != 0:
170 raise ValueError(
171 "non-zero flags not allowed in calls to send() on %s" %
172 self.__class__)
Bill Janssen934b16d2008-06-28 22:19:33 +0000173 while True:
174 try:
175 v = self._sslobj.write(data)
176 except SSLError, x:
177 if x.args[0] == SSL_ERROR_WANT_READ:
178 return 0
179 elif x.args[0] == SSL_ERROR_WANT_WRITE:
180 return 0
181 else:
182 raise
183 else:
184 return v
Bill Janssen426ea0a2007-08-29 22:35:05 +0000185 else:
186 return socket.send(self, data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000187
Ezio Melotti259ea732010-01-18 09:12:06 +0000188 def sendto(self, data, addr, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000189 if self._sslobj:
Bill Janssen934b16d2008-06-28 22:19:33 +0000190 raise ValueError("sendto not allowed on instances of %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000191 self.__class__)
192 else:
Bill Janssen934b16d2008-06-28 22:19:33 +0000193 return socket.sendto(self, data, addr, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000194
Ezio Melotti259ea732010-01-18 09:12:06 +0000195 def sendall(self, data, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000196 if self._sslobj:
197 if flags != 0:
198 raise ValueError(
199 "non-zero flags not allowed in calls to sendall() on %s" %
200 self.__class__)
Bill Janssen934b16d2008-06-28 22:19:33 +0000201 amount = len(data)
202 count = 0
203 while (count < amount):
204 v = self.send(data[count:])
205 count += v
206 return amount
Bill Janssen426ea0a2007-08-29 22:35:05 +0000207 else:
208 return socket.sendall(self, data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000209
Ezio Melotti259ea732010-01-18 09:12:06 +0000210 def recv(self, buflen=1024, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000211 if self._sslobj:
212 if flags != 0:
213 raise ValueError(
Antoine Pitrou498c4382010-03-22 15:12:58 +0000214 "non-zero flags not allowed in calls to recv() on %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000215 self.__class__)
Antoine Pitrou498c4382010-03-22 15:12:58 +0000216 return self.read(buflen)
Bill Janssen426ea0a2007-08-29 22:35:05 +0000217 else:
218 return socket.recv(self, buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000219
Ezio Melotti259ea732010-01-18 09:12:06 +0000220 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen61c001a2008-09-08 16:37:24 +0000221 if buffer and (nbytes is None):
222 nbytes = len(buffer)
223 elif nbytes is None:
224 nbytes = 1024
225 if self._sslobj:
226 if flags != 0:
227 raise ValueError(
228 "non-zero flags not allowed in calls to recv_into() on %s" %
229 self.__class__)
Antoine Pitrou498c4382010-03-22 15:12:58 +0000230 tmp_buffer = self.read(nbytes)
231 v = len(tmp_buffer)
232 buffer[:v] = tmp_buffer
233 return v
Bill Janssen61c001a2008-09-08 16:37:24 +0000234 else:
235 return socket.recv_into(self, buffer, nbytes, flags)
236
Ezio Melotti259ea732010-01-18 09:12:06 +0000237 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000238 if self._sslobj:
Bill Janssen934b16d2008-06-28 22:19:33 +0000239 raise ValueError("recvfrom not allowed on instances of %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000240 self.__class__)
241 else:
Bill Janssen934b16d2008-06-28 22:19:33 +0000242 return socket.recvfrom(self, addr, buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000243
Ezio Melotti259ea732010-01-18 09:12:06 +0000244 def recvfrom_into(self, buffer, nbytes=None, flags=0):
Bill Janssen61c001a2008-09-08 16:37:24 +0000245 if self._sslobj:
246 raise ValueError("recvfrom_into not allowed on instances of %s" %
247 self.__class__)
248 else:
249 return socket.recvfrom_into(self, buffer, nbytes, flags)
250
Ezio Melotti259ea732010-01-18 09:12:06 +0000251 def pending(self):
Bill Janssen934b16d2008-06-28 22:19:33 +0000252 if self._sslobj:
253 return self._sslobj.pending()
254 else:
255 return 0
256
Ezio Melotti259ea732010-01-18 09:12:06 +0000257 def unwrap(self):
Bill Janssen39295c22008-08-12 16:31:21 +0000258 if self._sslobj:
259 s = self._sslobj.shutdown()
260 self._sslobj = None
261 return s
262 else:
263 raise ValueError("No SSL wrapper around " + str(self))
264
Ezio Melotti259ea732010-01-18 09:12:06 +0000265 def shutdown(self, how):
Bill Janssen296a59d2007-09-16 22:06:00 +0000266 self._sslobj = None
Bill Janssen426ea0a2007-08-29 22:35:05 +0000267 socket.shutdown(self, how)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000268
Ezio Melotti259ea732010-01-18 09:12:06 +0000269 def close(self):
Bill Janssen934b16d2008-06-28 22:19:33 +0000270 if self._makefile_refs < 1:
271 self._sslobj = None
272 socket.close(self)
273 else:
274 self._makefile_refs -= 1
275
Ezio Melotti259ea732010-01-18 09:12:06 +0000276 def do_handshake(self):
Bill Janssen934b16d2008-06-28 22:19:33 +0000277
278 """Perform a TLS/SSL handshake."""
279
280 self._sslobj.do_handshake()
281
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000282 def connect(self, addr):
Bill Janssen24bccf22007-08-30 17:07:28 +0000283
284 """Connects to remote ADDR, and then wraps the connection in
285 an SSL channel."""
286
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000287 # Here we assume that the socket is client-side, and not
288 # connected at the time of the call. We connect it, then wrap it.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000289 if self._sslobj:
Bill Janssen98d19da2007-09-10 21:51:02 +0000290 raise ValueError("attempt to connect already-connected SSLSocket!")
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000291 socket.connect(self, addr)
Bill Janssen426ea0a2007-08-29 22:35:05 +0000292 self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000293 self.cert_reqs, self.ssl_version,
294 self.ca_certs)
Bill Janssen934b16d2008-06-28 22:19:33 +0000295 if self.do_handshake_on_connect:
296 self.do_handshake()
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000297
298 def accept(self):
Bill Janssen24bccf22007-08-30 17:07:28 +0000299
300 """Accepts a new connection from a remote client, and returns
301 a tuple containing that new connection wrapped with a server-side
302 SSL channel, and the address of the remote client."""
303
Bill Janssen426ea0a2007-08-29 22:35:05 +0000304 newsock, addr = socket.accept(self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000305 return (SSLSocket(newsock,
306 keyfile=self.keyfile,
307 certfile=self.certfile,
308 server_side=True,
309 cert_reqs=self.cert_reqs,
310 ssl_version=self.ssl_version,
311 ca_certs=self.ca_certs,
312 do_handshake_on_connect=self.do_handshake_on_connect,
313 suppress_ragged_eofs=self.suppress_ragged_eofs),
314 addr)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000315
Bill Janssen296a59d2007-09-16 22:06:00 +0000316 def makefile(self, mode='r', bufsize=-1):
317
Bill Janssen61c001a2008-09-08 16:37:24 +0000318 """Make and return a file-like object that
319 works with the SSL connection. Just use the code
320 from the socket module."""
Bill Janssen296a59d2007-09-16 22:06:00 +0000321
Bill Janssen934b16d2008-06-28 22:19:33 +0000322 self._makefile_refs += 1
Antoine Pitroud4030da2010-04-23 23:35:01 +0000323 # close=True so as to decrement the reference count when done with
324 # the file-like object.
325 return _fileobject(self, mode, bufsize, close=True)
Bill Janssen296a59d2007-09-16 22:06:00 +0000326
327
328
Bill Janssen98d19da2007-09-10 21:51:02 +0000329def wrap_socket(sock, keyfile=None, certfile=None,
330 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen934b16d2008-06-28 22:19:33 +0000331 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
332 do_handshake_on_connect=True,
333 suppress_ragged_eofs=True):
Bill Janssen98d19da2007-09-10 21:51:02 +0000334
335 return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
336 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen934b16d2008-06-28 22:19:33 +0000337 ssl_version=ssl_version, ca_certs=ca_certs,
338 do_handshake_on_connect=do_handshake_on_connect,
339 suppress_ragged_eofs=suppress_ragged_eofs)
340
Bill Janssen98d19da2007-09-10 21:51:02 +0000341
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000342# some utility functions
343
344def cert_time_to_seconds(cert_time):
Bill Janssen24bccf22007-08-30 17:07:28 +0000345
346 """Takes a date-time string in standard ASN1_print form
347 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
348 a Python time value in seconds past the epoch."""
349
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000350 import time
351 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
352
Bill Janssen296a59d2007-09-16 22:06:00 +0000353PEM_HEADER = "-----BEGIN CERTIFICATE-----"
354PEM_FOOTER = "-----END CERTIFICATE-----"
355
356def DER_cert_to_PEM_cert(der_cert_bytes):
357
358 """Takes a certificate in binary DER format and returns the
359 PEM version of it as a string."""
360
361 if hasattr(base64, 'standard_b64encode'):
362 # preferred because older API gets line-length wrong
363 f = base64.standard_b64encode(der_cert_bytes)
364 return (PEM_HEADER + '\n' +
365 textwrap.fill(f, 64) +
366 PEM_FOOTER + '\n')
367 else:
368 return (PEM_HEADER + '\n' +
369 base64.encodestring(der_cert_bytes) +
370 PEM_FOOTER + '\n')
371
372def PEM_cert_to_DER_cert(pem_cert_string):
373
374 """Takes a certificate in ASCII PEM format and returns the
375 DER-encoded version of it as a byte sequence"""
376
377 if not pem_cert_string.startswith(PEM_HEADER):
378 raise ValueError("Invalid PEM encoding; must start with %s"
379 % PEM_HEADER)
380 if not pem_cert_string.strip().endswith(PEM_FOOTER):
381 raise ValueError("Invalid PEM encoding; must end with %s"
382 % PEM_FOOTER)
383 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
384 return base64.decodestring(d)
385
Ezio Melotti259ea732010-01-18 09:12:06 +0000386def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Bill Janssen296a59d2007-09-16 22:06:00 +0000387
388 """Retrieve the certificate from the server at the specified address,
389 and return it as a PEM-encoded string.
390 If 'ca_certs' is specified, validate the server cert against it.
391 If 'ssl_version' is specified, use it in the connection attempt."""
392
393 host, port = addr
394 if (ca_certs is not None):
395 cert_reqs = CERT_REQUIRED
396 else:
397 cert_reqs = CERT_NONE
398 s = wrap_socket(socket(), ssl_version=ssl_version,
399 cert_reqs=cert_reqs, ca_certs=ca_certs)
400 s.connect(addr)
401 dercert = s.getpeercert(True)
402 s.close()
403 return DER_cert_to_PEM_cert(dercert)
404
Ezio Melotti259ea732010-01-18 09:12:06 +0000405def get_protocol_name(protocol_code):
Bill Janssen296a59d2007-09-16 22:06:00 +0000406 if protocol_code == PROTOCOL_TLSv1:
407 return "TLSv1"
408 elif protocol_code == PROTOCOL_SSLv23:
409 return "SSLv23"
410 elif protocol_code == PROTOCOL_SSLv2:
411 return "SSLv2"
412 elif protocol_code == PROTOCOL_SSLv3:
413 return "SSLv3"
414 else:
415 return "<unknown>"
416
417
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000418# a replacement for the old socket.ssl function
419
Ezio Melotti259ea732010-01-18 09:12:06 +0000420def sslwrap_simple(sock, keyfile=None, certfile=None):
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000421
Bill Janssen24bccf22007-08-30 17:07:28 +0000422 """A replacement for the old socket.ssl function. Designed
423 for compability with Python 2.5 and earlier. Will disappear in
424 Python 3.0."""
425
Bill Jansseneb257ac2008-09-29 18:56:38 +0000426 if hasattr(sock, "_sock"):
427 sock = sock._sock
428
429 ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE,
Bill Janssen934b16d2008-06-28 22:19:33 +0000430 PROTOCOL_SSLv23, None)
Bill Jansseneb257ac2008-09-29 18:56:38 +0000431 try:
432 sock.getpeername()
433 except:
434 # no, no connection yet
435 pass
436 else:
437 # yes, do the handshake
438 ssl_sock.do_handshake()
439
Bill Janssen934b16d2008-06-28 22:19:33 +0000440 return ssl_sock