blob: d5e48748c7c2cc7a73839a4c53663a3b8f13885c [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")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000128 if keyfile and not certfile:
129 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000130 if certfile and not keyfile:
131 keyfile = certfile
132 self.context = SSLContext(ssl_version)
133 self.context.verify_mode = cert_reqs
134 if ca_certs:
135 self.context.load_verify_locations(ca_certs)
136 if certfile:
137 self.context.load_cert_chain(certfile, keyfile)
138 if ciphers:
139 self.context.set_ciphers(ciphers)
140 self.keyfile = keyfile
141 self.certfile = certfile
142 self.cert_reqs = cert_reqs
143 self.ssl_version = ssl_version
144 self.ca_certs = ca_certs
145 self.ciphers = ciphers
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000146 self.server_side = server_side
Antoine Pitrou152efa22010-05-16 18:19:27 +0000147 self.do_handshake_on_connect = do_handshake_on_connect
148 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000149 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000150 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000151 socket.__init__(self,
152 family=sock.family,
153 type=sock.type,
154 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000155 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000156 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000157 # see if it's connected
158 try:
159 sock.getpeername()
160 except socket_error as e:
161 if e.errno != errno.ENOTCONN:
162 raise
163 else:
164 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000165 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000166 elif fileno is not None:
167 socket.__init__(self, fileno=fileno)
168 else:
169 socket.__init__(self, family=family, type=type, proto=proto)
170
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000171 self._closed = False
172 self._sslobj = None
173 if connected:
174 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000175 try:
Antoine Pitrou152efa22010-05-16 18:19:27 +0000176 self._sslobj = self.context._wrap_socket(self, server_side)
Bill Janssen6e027db2007-11-15 22:23:56 +0000177 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000178 timeout = self.gettimeout()
179 if timeout == 0.0:
180 # non-blocking
181 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000182 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000183
Bill Janssen6e027db2007-11-15 22:23:56 +0000184 except socket_error as x:
185 self.close()
186 raise x
187
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000188 def dup(self):
189 raise NotImplemented("Can't dup() %s instances" %
190 self.__class__.__name__)
191
Bill Janssen6e027db2007-11-15 22:23:56 +0000192 def _checkClosed(self, msg=None):
193 # raise an exception here if you wish to check for spurious closes
194 pass
195
Bill Janssen54cc54c2007-12-14 22:08:56 +0000196 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000197 """Read up to LEN bytes and return them.
198 Return zero-length string on EOF."""
199
Bill Janssen6e027db2007-11-15 22:23:56 +0000200 self._checkClosed()
201 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000202 if buffer is not None:
203 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000204 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000205 v = self._sslobj.read(len or 1024)
206 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000207 except SSLError as x:
208 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000209 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000210 return 0
211 else:
212 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000213 else:
214 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000215
216 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000217 """Write DATA to the underlying SSL channel. Returns
218 number of bytes of DATA actually transmitted."""
219
Bill Janssen6e027db2007-11-15 22:23:56 +0000220 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000221 return self._sslobj.write(data)
222
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000223 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000224 """Returns a formatted version of the data in the
225 certificate provided by the other end of the SSL channel.
226 Return None if no certificate was provided, {} if a
227 certificate was provided, but not validated."""
228
Bill Janssen6e027db2007-11-15 22:23:56 +0000229 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000230 return self._sslobj.peer_certificate(binary_form)
231
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000232 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000233 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000234 if not self._sslobj:
235 return None
236 else:
237 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000238
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000239 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000240 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000241 if self._sslobj:
242 if flags != 0:
243 raise ValueError(
244 "non-zero flags not allowed in calls to send() on %s" %
245 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000246 while True:
247 try:
248 v = self._sslobj.write(data)
249 except SSLError as x:
250 if x.args[0] == SSL_ERROR_WANT_READ:
251 return 0
252 elif x.args[0] == SSL_ERROR_WANT_WRITE:
253 return 0
254 else:
255 raise
256 else:
257 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000258 else:
259 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000260
Antoine Pitroua468adc2010-09-14 14:43:44 +0000261 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000262 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000263 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000264 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000265 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000266 elif addr is None:
267 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000268 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000269 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000270
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000271 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000273 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000274 if flags != 0:
275 raise ValueError(
276 "non-zero flags not allowed in calls to sendall() on %s" %
277 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000278 amount = len(data)
279 count = 0
280 while (count < amount):
281 v = self.send(data[count:])
282 count += v
283 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000284 else:
285 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000286
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000287 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000289 if self._sslobj:
290 if flags != 0:
291 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000292 "non-zero flags not allowed in calls to recv() on %s" %
293 self.__class__)
294 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000295 else:
296 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000297
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000298 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000299 self._checkClosed()
300 if buffer and (nbytes is None):
301 nbytes = len(buffer)
302 elif nbytes is None:
303 nbytes = 1024
304 if self._sslobj:
305 if flags != 0:
306 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000307 "non-zero flags not allowed in calls to recv_into() on %s" %
308 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000309 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 else:
311 return socket.recv_into(self, buffer, nbytes, flags)
312
Antoine Pitroua468adc2010-09-14 14:43:44 +0000313 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000314 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000315 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000316 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000317 self.__class__)
318 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000319 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000320
Bill Janssen58afe4c2008-09-08 16:45:19 +0000321 def recvfrom_into(self, buffer, nbytes=None, flags=0):
322 self._checkClosed()
323 if self._sslobj:
324 raise ValueError("recvfrom_into not allowed on instances of %s" %
325 self.__class__)
326 else:
327 return socket.recvfrom_into(self, buffer, nbytes, flags)
328
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000329 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 self._checkClosed()
331 if self._sslobj:
332 return self._sslobj.pending()
333 else:
334 return 0
335
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000336 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000338 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000339 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000340
Ezio Melottidc55e672010-01-18 09:15:14 +0000341 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000342 if self._sslobj:
343 s = self._sslobj.shutdown()
344 self._sslobj = None
345 return s
346 else:
347 raise ValueError("No SSL wrapper around " + str(self))
348
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000349 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000350 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000352 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000353
Bill Janssen48dc27c2007-12-05 03:38:10 +0000354 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000355 """Perform a TLS/SSL handshake."""
356
Bill Janssen48dc27c2007-12-05 03:38:10 +0000357 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000359 if timeout == 0.0 and block:
360 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000361 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000362 finally:
363 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000364
365 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000366 """Connects to remote ADDR, and then wraps the connection in
367 an SSL channel."""
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000368 if self.server_side:
369 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000370 # Here we assume that the socket is client-side, and not
371 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000372 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000373 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000374 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000376 try:
377 if self.do_handshake_on_connect:
378 self.do_handshake()
379 except:
380 self._sslobj = None
381 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000382
383 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000384 """Accepts a new connection from a remote client, and returns
385 a tuple containing that new connection wrapped with a server-side
386 SSL channel, and the address of the remote client."""
387
388 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 return (SSLSocket(sock=newsock,
390 keyfile=self.keyfile, certfile=self.certfile,
391 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000392 cert_reqs=self.cert_reqs,
393 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000394 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000395 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000396 do_handshake_on_connect=
397 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000398 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399
Guido van Rossume6650f92007-12-06 19:05:55 +0000400 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000401 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000402 self._real_close()
403
Bill Janssen54cc54c2007-12-14 22:08:56 +0000404
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405def wrap_socket(sock, keyfile=None, certfile=None,
406 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000407 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000408 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000409 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000410
Bill Janssen6e027db2007-11-15 22:23:56 +0000411 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000412 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000413 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000414 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000415 suppress_ragged_eofs=suppress_ragged_eofs,
416 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000417
Thomas Woutersed03b412007-08-28 21:37:11 +0000418# some utility functions
419
420def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000421 """Takes a date-time string in standard ASN1_print form
422 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
423 a Python time value in seconds past the epoch."""
424
Thomas Woutersed03b412007-08-28 21:37:11 +0000425 import time
426 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
427
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428PEM_HEADER = "-----BEGIN CERTIFICATE-----"
429PEM_FOOTER = "-----END CERTIFICATE-----"
430
431def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432 """Takes a certificate in binary DER format and returns the
433 PEM version of it as a string."""
434
Bill Janssen6e027db2007-11-15 22:23:56 +0000435 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
436 return (PEM_HEADER + '\n' +
437 textwrap.fill(f, 64) + '\n' +
438 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000439
440def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441 """Takes a certificate in ASCII PEM format and returns the
442 DER-encoded version of it as a byte sequence"""
443
444 if not pem_cert_string.startswith(PEM_HEADER):
445 raise ValueError("Invalid PEM encoding; must start with %s"
446 % PEM_HEADER)
447 if not pem_cert_string.strip().endswith(PEM_FOOTER):
448 raise ValueError("Invalid PEM encoding; must end with %s"
449 % PEM_FOOTER)
450 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000451 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000453def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454 """Retrieve the certificate from the server at the specified address,
455 and return it as a PEM-encoded string.
456 If 'ca_certs' is specified, validate the server cert against it.
457 If 'ssl_version' is specified, use it in the connection attempt."""
458
459 host, port = addr
460 if (ca_certs is not None):
461 cert_reqs = CERT_REQUIRED
462 else:
463 cert_reqs = CERT_NONE
464 s = wrap_socket(socket(), ssl_version=ssl_version,
465 cert_reqs=cert_reqs, ca_certs=ca_certs)
466 s.connect(addr)
467 dercert = s.getpeercert(True)
468 s.close()
469 return DER_cert_to_PEM_cert(dercert)
470
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000471def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472 if protocol_code == PROTOCOL_TLSv1:
473 return "TLSv1"
474 elif protocol_code == PROTOCOL_SSLv23:
475 return "SSLv23"
476 elif protocol_code == PROTOCOL_SSLv2:
477 return "SSLv2"
478 elif protocol_code == PROTOCOL_SSLv3:
479 return "SSLv3"
480 else:
481 return "<unknown>"