blob: a634442e13c82ec7dff40185237dba446ba192bb [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
Thomas Woutersed03b412007-08-28 21:37:11 +000058
59import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000060
Antoine Pitrou04f6a322010-04-05 21:40:07 +000061from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou152efa22010-05-16 18:19:27 +000062from _ssl import _SSLContext, SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000063from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Guido van Rossum5b8b1552007-11-16 00:06:11 +000064from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23,
65 PROTOCOL_TLSv1)
Antoine Pitroub5218772010-05-21 09:56:06 +000066from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000067from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000068from _ssl import (
69 SSL_ERROR_ZERO_RETURN,
70 SSL_ERROR_WANT_READ,
71 SSL_ERROR_WANT_WRITE,
72 SSL_ERROR_WANT_X509_LOOKUP,
73 SSL_ERROR_SYSCALL,
74 SSL_ERROR_SSL,
75 SSL_ERROR_WANT_CONNECT,
76 SSL_ERROR_EOF,
77 SSL_ERROR_INVALID_ERROR_CODE,
78 )
Thomas Woutersed03b412007-08-28 21:37:11 +000079
Thomas Wouters47b49bf2007-08-30 22:15:33 +000080from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000081from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000082from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000083import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000084import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000085import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000086
Thomas Woutersed03b412007-08-28 21:37:11 +000087
Antoine Pitrou152efa22010-05-16 18:19:27 +000088class SSLContext(_SSLContext):
89 """An SSLContext holds various SSL-related configuration options and
90 data, such as certificates and possibly a private key."""
91
92 __slots__ = ('protocol',)
93
94 def __new__(cls, protocol, *args, **kwargs):
95 return _SSLContext.__new__(cls, protocol)
96
97 def __init__(self, protocol):
98 self.protocol = protocol
99
100 def wrap_socket(self, sock, server_side=False,
101 do_handshake_on_connect=True,
102 suppress_ragged_eofs=True):
103 return SSLSocket(sock=sock, server_side=server_side,
104 do_handshake_on_connect=do_handshake_on_connect,
105 suppress_ragged_eofs=suppress_ragged_eofs,
106 _context=self)
107
108
109class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000110 """This class implements a subtype of socket.socket that wraps
111 the underlying OS socket in an SSL context when necessary, and
112 provides read and write methods over that channel."""
113
Bill Janssen6e027db2007-11-15 22:23:56 +0000114 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000115 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000116 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
117 do_handshake_on_connect=True,
118 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000119 suppress_ragged_eofs=True, ciphers=None,
120 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000121
Antoine Pitrou152efa22010-05-16 18:19:27 +0000122 if _context:
123 self.context = _context
124 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000125 if server_side and not certfile:
126 raise ValueError("certfile must be specified for server-side "
127 "operations")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000128 if certfile and not keyfile:
129 keyfile = certfile
130 self.context = SSLContext(ssl_version)
131 self.context.verify_mode = cert_reqs
132 if ca_certs:
133 self.context.load_verify_locations(ca_certs)
134 if certfile:
135 self.context.load_cert_chain(certfile, keyfile)
136 if ciphers:
137 self.context.set_ciphers(ciphers)
138 self.keyfile = keyfile
139 self.certfile = certfile
140 self.cert_reqs = cert_reqs
141 self.ssl_version = ssl_version
142 self.ca_certs = ca_certs
143 self.ciphers = ciphers
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000144 self.server_side = server_side
Antoine Pitrou152efa22010-05-16 18:19:27 +0000145 self.do_handshake_on_connect = do_handshake_on_connect
146 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000147 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000148 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000149 socket.__init__(self,
150 family=sock.family,
151 type=sock.type,
152 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000153 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000154 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000155 # see if it's connected
156 try:
157 sock.getpeername()
158 except socket_error as e:
159 if e.errno != errno.ENOTCONN:
160 raise
161 else:
162 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000163 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000164 elif fileno is not None:
165 socket.__init__(self, fileno=fileno)
166 else:
167 socket.__init__(self, family=family, type=type, proto=proto)
168
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000169 self._closed = False
170 self._sslobj = None
171 if connected:
172 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000173 try:
Antoine Pitrou152efa22010-05-16 18:19:27 +0000174 self._sslobj = self.context._wrap_socket(self, server_side)
Bill Janssen6e027db2007-11-15 22:23:56 +0000175 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000176 timeout = self.gettimeout()
177 if timeout == 0.0:
178 # non-blocking
179 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000180 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000181
Bill Janssen6e027db2007-11-15 22:23:56 +0000182 except socket_error as x:
183 self.close()
184 raise x
185
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000186 def dup(self):
187 raise NotImplemented("Can't dup() %s instances" %
188 self.__class__.__name__)
189
Bill Janssen6e027db2007-11-15 22:23:56 +0000190 def _checkClosed(self, msg=None):
191 # raise an exception here if you wish to check for spurious closes
192 pass
193
Bill Janssen54cc54c2007-12-14 22:08:56 +0000194 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000195 """Read up to LEN bytes and return them.
196 Return zero-length string on EOF."""
197
Bill Janssen6e027db2007-11-15 22:23:56 +0000198 self._checkClosed()
199 try:
200 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000201 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000202 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000203 v = self._sslobj.read(len or 1024)
204 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000205 except SSLError as x:
206 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000207 if buffer:
208 return 0
209 else:
210 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000211 else:
212 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000213
214 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000215 """Write DATA to the underlying SSL channel. Returns
216 number of bytes of DATA actually transmitted."""
217
Bill Janssen6e027db2007-11-15 22:23:56 +0000218 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000219 return self._sslobj.write(data)
220
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000221 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000222 """Returns a formatted version of the data in the
223 certificate provided by the other end of the SSL channel.
224 Return None if no certificate was provided, {} if a
225 certificate was provided, but not validated."""
226
Bill Janssen6e027db2007-11-15 22:23:56 +0000227 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000228 return self._sslobj.peer_certificate(binary_form)
229
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000230 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000231 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000232 if not self._sslobj:
233 return None
234 else:
235 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000236
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000237 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000238 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000239 if self._sslobj:
240 if flags != 0:
241 raise ValueError(
242 "non-zero flags not allowed in calls to send() on %s" %
243 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000244 while True:
245 try:
246 v = self._sslobj.write(data)
247 except SSLError as x:
248 if x.args[0] == SSL_ERROR_WANT_READ:
249 return 0
250 elif x.args[0] == SSL_ERROR_WANT_WRITE:
251 return 0
252 else:
253 raise
254 else:
255 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000256 else:
257 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000258
Bill Janssen980f3142008-06-29 00:05:51 +0000259 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000260 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000261 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000262 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000263 self.__class__)
264 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000265 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000266
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000267 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000268 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000269 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000270 if flags != 0:
271 raise ValueError(
272 "non-zero flags not allowed in calls to sendall() on %s" %
273 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 amount = len(data)
275 count = 0
276 while (count < amount):
277 v = self.send(data[count:])
278 count += v
279 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000280 else:
281 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000282
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000283 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000284 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000285 if self._sslobj:
286 if flags != 0:
287 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000288 "non-zero flags not allowed in calls to recv() on %s" %
289 self.__class__)
290 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000291 else:
292 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000293
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000294 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000295 self._checkClosed()
296 if buffer and (nbytes is None):
297 nbytes = len(buffer)
298 elif nbytes is None:
299 nbytes = 1024
300 if self._sslobj:
301 if flags != 0:
302 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000303 "non-zero flags not allowed in calls to recv_into() on %s" %
304 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000305 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000306 else:
307 return socket.recv_into(self, buffer, nbytes, flags)
308
Bill Janssen980f3142008-06-29 00:05:51 +0000309 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000311 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000312 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000313 self.__class__)
314 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000315 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000316
Bill Janssen58afe4c2008-09-08 16:45:19 +0000317 def recvfrom_into(self, buffer, nbytes=None, flags=0):
318 self._checkClosed()
319 if self._sslobj:
320 raise ValueError("recvfrom_into not allowed on instances of %s" %
321 self.__class__)
322 else:
323 return socket.recvfrom_into(self, buffer, nbytes, flags)
324
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000325 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 self._checkClosed()
327 if self._sslobj:
328 return self._sslobj.pending()
329 else:
330 return 0
331
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000332 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000335 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
Ezio Melottidc55e672010-01-18 09:15:14 +0000337 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000338 if self._sslobj:
339 s = self._sslobj.shutdown()
340 self._sslobj = None
341 return s
342 else:
343 raise ValueError("No SSL wrapper around " + str(self))
344
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000345 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000346 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000347 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000348 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000349
Bill Janssen48dc27c2007-12-05 03:38:10 +0000350 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 """Perform a TLS/SSL handshake."""
352
Bill Janssen48dc27c2007-12-05 03:38:10 +0000353 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000354 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000355 if timeout == 0.0 and block:
356 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000357 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000358 finally:
359 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000360
361 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000362 """Connects to remote ADDR, and then wraps the connection in
363 an SSL channel."""
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000364 if self.server_side:
365 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000366 # Here we assume that the socket is client-side, and not
367 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000368 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000369 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000370 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000371 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000372 try:
373 if self.do_handshake_on_connect:
374 self.do_handshake()
375 except:
376 self._sslobj = None
377 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000378
379 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000380 """Accepts a new connection from a remote client, and returns
381 a tuple containing that new connection wrapped with a server-side
382 SSL channel, and the address of the remote client."""
383
384 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000385 return (SSLSocket(sock=newsock,
386 keyfile=self.keyfile, certfile=self.certfile,
387 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000388 cert_reqs=self.cert_reqs,
389 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000390 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000391 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000392 do_handshake_on_connect=
393 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000394 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395
Guido van Rossume6650f92007-12-06 19:05:55 +0000396 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000397 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000398 self._real_close()
399
Bill Janssen54cc54c2007-12-14 22:08:56 +0000400
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401def wrap_socket(sock, keyfile=None, certfile=None,
402 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000403 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000404 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000405 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406
Bill Janssen6e027db2007-11-15 22:23:56 +0000407 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000409 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000410 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000411 suppress_ragged_eofs=suppress_ragged_eofs,
412 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413
Thomas Woutersed03b412007-08-28 21:37:11 +0000414# some utility functions
415
416def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000417 """Takes a date-time string in standard ASN1_print form
418 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
419 a Python time value in seconds past the epoch."""
420
Thomas Woutersed03b412007-08-28 21:37:11 +0000421 import time
422 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
423
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000424PEM_HEADER = "-----BEGIN CERTIFICATE-----"
425PEM_FOOTER = "-----END CERTIFICATE-----"
426
427def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428 """Takes a certificate in binary DER format and returns the
429 PEM version of it as a string."""
430
Bill Janssen6e027db2007-11-15 22:23:56 +0000431 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
432 return (PEM_HEADER + '\n' +
433 textwrap.fill(f, 64) + '\n' +
434 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435
436def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437 """Takes a certificate in ASCII PEM format and returns the
438 DER-encoded version of it as a byte sequence"""
439
440 if not pem_cert_string.startswith(PEM_HEADER):
441 raise ValueError("Invalid PEM encoding; must start with %s"
442 % PEM_HEADER)
443 if not pem_cert_string.strip().endswith(PEM_FOOTER):
444 raise ValueError("Invalid PEM encoding; must end with %s"
445 % PEM_FOOTER)
446 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000447 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000448
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000449def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450 """Retrieve the certificate from the server at the specified address,
451 and return it as a PEM-encoded string.
452 If 'ca_certs' is specified, validate the server cert against it.
453 If 'ssl_version' is specified, use it in the connection attempt."""
454
455 host, port = addr
456 if (ca_certs is not None):
457 cert_reqs = CERT_REQUIRED
458 else:
459 cert_reqs = CERT_NONE
460 s = wrap_socket(socket(), ssl_version=ssl_version,
461 cert_reqs=cert_reqs, ca_certs=ca_certs)
462 s.connect(addr)
463 dercert = s.getpeercert(True)
464 s.close()
465 return DER_cert_to_PEM_cert(dercert)
466
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000467def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468 if protocol_code == PROTOCOL_TLSv1:
469 return "TLSv1"
470 elif protocol_code == PROTOCOL_SSLv23:
471 return "SSLv23"
472 elif protocol_code == PROTOCOL_SSLv2:
473 return "SSLv2"
474 elif protocol_code == PROTOCOL_SSLv3:
475 return "SSLv3"
476 else:
477 return "<unknown>"