1 # Wrapper module for _ssl, providing some additional facilities
2 # implemented in Python. Written by Bill Janssen.
5 This module provides some more Pythonic support for SSL.
9 SSLSocket -- subtype of socket.socket which does SSL over the socket
13 SSLError -- exception raised for I/O errors
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())
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.
31 SSL_ERROR_WANT_X509_LOOKUP
34 SSL_ERROR_WANT_CONNECT
37 SSL_ERROR_INVALID_ERROR_CODE
39 The following group define certificate requirements that one side is
40 allowing/requiring from the other side:
42 CERT_NONE - no certificates from the other side are required (or will
43 be looked at if provided)
44 CERT_OPTIONAL - certificates are not required, but if provided will be
45 validated, and if validation fails, the connection will
47 CERT_REQUIRED - certificates are required, and will be validated, and
48 if validation fails, the connection will also fail
50 The following constants identify various SSL protocol variants:
60 import _ssl # if we can't import it, let the error propagate
62 from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
63 from _ssl import SSLError
64 from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
65 from _ssl import RAND_status, RAND_egd, RAND_add
67 SSL_ERROR_ZERO_RETURN, \
68 SSL_ERROR_WANT_READ, \
69 SSL_ERROR_WANT_WRITE, \
70 SSL_ERROR_WANT_X509_LOOKUP, \
73 SSL_ERROR_WANT_CONNECT, \
75 SSL_ERROR_INVALID_ERROR_CODE
76 from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
78 PROTOCOL_TLSv1: "TLSv1",
79 PROTOCOL_SSLv23: "SSLv23",
80 PROTOCOL_SSLv3: "SSLv3",
83 from _ssl import PROTOCOL_SSLv2
84 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
86 _SSLv2_IF_EXISTS = None
88 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
90 from socket import socket, _fileobject, _delegate_methods, error as socket_error
91 from socket import getnameinfo as _getnameinfo
92 import base64 # for DER-to-PEM translation
95 # Disable weak or insecure ciphers by default
96 # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
97 _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
100 class SSLSocket(socket):
102 """This class implements a subtype of socket.socket that wraps
103 the underlying OS socket in an SSL context when necessary, and
104 provides read and write methods over that channel."""
106 def __init__(self, sock, keyfile=None, certfile=None,
107 server_side=False, cert_reqs=CERT_NONE,
108 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
109 do_handshake_on_connect=True,
110 suppress_ragged_eofs=True, ciphers=None):
111 socket.__init__(self, _sock=sock._sock)
112 # The initializer for socket overrides the methods send(), recv(), etc.
113 # in the instancce, which we don't need -- but we want to provide the
114 # methods defined in SSLSocket.
115 for attr in _delegate_methods:
118 except AttributeError:
121 if ciphers is None and ssl_version != _SSLv2_IF_EXISTS:
122 ciphers = _DEFAULT_CIPHERS
124 if certfile and not keyfile:
126 # see if it's connected
128 socket.getpeername(self)
129 except socket_error, e:
130 if e.errno != errno.ENOTCONN:
132 # no, no connection yet
133 self._connected = False
136 # yes, create the SSL object
137 self._connected = True
138 self._sslobj = _ssl.sslwrap(self._sock, server_side,
140 cert_reqs, ssl_version, ca_certs,
142 if do_handshake_on_connect:
144 self.keyfile = keyfile
145 self.certfile = certfile
146 self.cert_reqs = cert_reqs
147 self.ssl_version = ssl_version
148 self.ca_certs = ca_certs
149 self.ciphers = ciphers
150 self.do_handshake_on_connect = do_handshake_on_connect
151 self.suppress_ragged_eofs = suppress_ragged_eofs
152 self._makefile_refs = 0
154 def read(self, len=1024):
156 """Read up to LEN bytes and return them.
157 Return zero-length string on EOF."""
160 return self._sslobj.read(len)
162 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
167 def write(self, data):
169 """Write DATA to the underlying SSL channel. Returns
170 number of bytes of DATA actually transmitted."""
172 return self._sslobj.write(data)
174 def getpeercert(self, binary_form=False):
176 """Returns a formatted version of the data in the
177 certificate provided by the other end of the SSL channel.
178 Return None if no certificate was provided, {} if a
179 certificate was provided, but not validated."""
181 return self._sslobj.peer_certificate(binary_form)
188 return self._sslobj.cipher()
190 def send(self, data, flags=0):
194 "non-zero flags not allowed in calls to send() on %s" %
198 v = self._sslobj.write(data)
200 if x.args[0] == SSL_ERROR_WANT_READ:
202 elif x.args[0] == SSL_ERROR_WANT_WRITE:
209 return self._sock.send(data, flags)
211 def sendto(self, data, flags_or_addr, addr=None):
213 raise ValueError("sendto not allowed on instances of %s" %
216 return self._sock.sendto(data, flags_or_addr)
218 return self._sock.sendto(data, flags_or_addr, addr)
220 def sendall(self, data, flags=0):
224 "non-zero flags not allowed in calls to sendall() on %s" %
228 while (count < amount):
229 v = self.send(data[count:])
233 return socket.sendall(self, data, flags)
235 def recv(self, buflen=1024, flags=0):
239 "non-zero flags not allowed in calls to recv() on %s" %
241 return self.read(buflen)
243 return self._sock.recv(buflen, flags)
245 def recv_into(self, buffer, nbytes=None, flags=0):
246 if buffer and (nbytes is None):
253 "non-zero flags not allowed in calls to recv_into() on %s" %
255 tmp_buffer = self.read(nbytes)
257 buffer[:v] = tmp_buffer
260 return self._sock.recv_into(buffer, nbytes, flags)
262 def recvfrom(self, buflen=1024, flags=0):
264 raise ValueError("recvfrom not allowed on instances of %s" %
267 return self._sock.recvfrom(buflen, flags)
269 def recvfrom_into(self, buffer, nbytes=None, flags=0):
271 raise ValueError("recvfrom_into not allowed on instances of %s" %
274 return self._sock.recvfrom_into(buffer, nbytes, flags)
278 return self._sslobj.pending()
284 s = self._sslobj.shutdown()
288 raise ValueError("No SSL wrapper around " + str(self))
290 def shutdown(self, how):
292 socket.shutdown(self, how)
295 if self._makefile_refs < 1:
299 self._makefile_refs -= 1
301 def do_handshake(self):
303 """Perform a TLS/SSL handshake."""
305 self._sslobj.do_handshake()
307 def _real_connect(self, addr, return_errno):
308 # Here we assume that the socket is client-side, and not
309 # connected at the time of the call. We connect it, then wrap it.
311 raise ValueError("attempt to connect already-connected SSLSocket!")
312 self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
313 self.cert_reqs, self.ssl_version,
314 self.ca_certs, self.ciphers)
316 socket.connect(self, addr)
317 if self.do_handshake_on_connect:
319 except socket_error as e:
325 self._connected = True
328 def connect(self, addr):
329 """Connects to remote ADDR, and then wraps the connection in
331 self._real_connect(addr, False)
333 def connect_ex(self, addr):
334 """Connects to remote ADDR, and then wraps the connection in
336 return self._real_connect(addr, True)
340 """Accepts a new connection from a remote client, and returns
341 a tuple containing that new connection wrapped with a server-side
342 SSL channel, and the address of the remote client."""
344 newsock, addr = socket.accept(self)
345 return (SSLSocket(newsock,
346 keyfile=self.keyfile,
347 certfile=self.certfile,
349 cert_reqs=self.cert_reqs,
350 ssl_version=self.ssl_version,
351 ca_certs=self.ca_certs,
352 ciphers=self.ciphers,
353 do_handshake_on_connect=self.do_handshake_on_connect,
354 suppress_ragged_eofs=self.suppress_ragged_eofs),
357 def makefile(self, mode='r', bufsize=-1):
359 """Make and return a file-like object that
360 works with the SSL connection. Just use the code
361 from the socket module."""
363 self._makefile_refs += 1
364 # close=True so as to decrement the reference count when done with
365 # the file-like object.
366 return _fileobject(self, mode, bufsize, close=True)
370 def wrap_socket(sock, keyfile=None, certfile=None,
371 server_side=False, cert_reqs=CERT_NONE,
372 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
373 do_handshake_on_connect=True,
374 suppress_ragged_eofs=True, ciphers=None):
376 return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
377 server_side=server_side, cert_reqs=cert_reqs,
378 ssl_version=ssl_version, ca_certs=ca_certs,
379 do_handshake_on_connect=do_handshake_on_connect,
380 suppress_ragged_eofs=suppress_ragged_eofs,
384 # some utility functions
386 def cert_time_to_seconds(cert_time):
388 """Takes a date-time string in standard ASN1_print form
389 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
390 a Python time value in seconds past the epoch."""
393 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
395 PEM_HEADER = "-----BEGIN CERTIFICATE-----"
396 PEM_FOOTER = "-----END CERTIFICATE-----"
398 def DER_cert_to_PEM_cert(der_cert_bytes):
400 """Takes a certificate in binary DER format and returns the
401 PEM version of it as a string."""
403 if hasattr(base64, 'standard_b64encode'):
404 # preferred because older API gets line-length wrong
405 f = base64.standard_b64encode(der_cert_bytes)
406 return (PEM_HEADER + '\n' +
407 textwrap.fill(f, 64) + '\n' +
410 return (PEM_HEADER + '\n' +
411 base64.encodestring(der_cert_bytes) +
414 def PEM_cert_to_DER_cert(pem_cert_string):
416 """Takes a certificate in ASCII PEM format and returns the
417 DER-encoded version of it as a byte sequence"""
419 if not pem_cert_string.startswith(PEM_HEADER):
420 raise ValueError("Invalid PEM encoding; must start with %s"
422 if not pem_cert_string.strip().endswith(PEM_FOOTER):
423 raise ValueError("Invalid PEM encoding; must end with %s"
425 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
426 return base64.decodestring(d)
428 def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
430 """Retrieve the certificate from the server at the specified address,
431 and return it as a PEM-encoded string.
432 If 'ca_certs' is specified, validate the server cert against it.
433 If 'ssl_version' is specified, use it in the connection attempt."""
436 if (ca_certs is not None):
437 cert_reqs = CERT_REQUIRED
439 cert_reqs = CERT_NONE
440 s = wrap_socket(socket(), ssl_version=ssl_version,
441 cert_reqs=cert_reqs, ca_certs=ca_certs)
443 dercert = s.getpeercert(True)
445 return DER_cert_to_PEM_cert(dercert)
447 def get_protocol_name(protocol_code):
448 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
451 # a replacement for the old socket.ssl function
453 def sslwrap_simple(sock, keyfile=None, certfile=None):
455 """A replacement for the old socket.ssl function. Designed
456 for compability with Python 2.5 and earlier. Will disappear in
459 if hasattr(sock, "_sock"):
462 ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE,
463 PROTOCOL_SSLv23, None)
467 # no, no connection yet
470 # yes, do the handshake
471 ssl_sock.do_handshake()