blob: 59aff879b42034543636d2826104b19d40253d1f [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
61from _ssl import SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000062from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Guido van Rossum5b8b1552007-11-16 00:06:11 +000063from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23,
64 PROTOCOL_TLSv1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000065from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +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,
76 )
Thomas Woutersed03b412007-08-28 21:37:11 +000077
Thomas Wouters47b49bf2007-08-30 22:15:33 +000078from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000079from socket import error as socket_error
Guido van Rossum39eb8fa2007-11-16 01:24:05 +000080from socket import dup as _dup
Bill Janssen40a0f662008-08-12 16:56:25 +000081from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000082import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000083import traceback
Antoine Pitrou365171d2010-04-26 17:32:49 +000084import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000085
Guido van Rossum5b8b1552007-11-16 00:06:11 +000086class SSLSocket(socket):
Thomas Woutersed03b412007-08-28 21:37:11 +000087
Thomas Wouters47b49bf2007-08-30 22:15:33 +000088 """This class implements a subtype of socket.socket that wraps
89 the underlying OS socket in an SSL context when necessary, and
90 provides read and write methods over that channel."""
91
Bill Janssen6e027db2007-11-15 22:23:56 +000092 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +000093 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +000094 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
95 do_handshake_on_connect=True,
96 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
97 suppress_ragged_eofs=True):
98
Bill Janssen6e027db2007-11-15 22:23:56 +000099 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000100 socket.__init__(self,
101 family=sock.family,
102 type=sock.type,
103 proto=sock.proto,
104 fileno=_dup(sock.fileno()))
Antoine Pitrouc2203f92010-04-24 22:07:51 +0000105 self.settimeout(sock.gettimeout())
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000106 sock.close()
Bill Janssen6e027db2007-11-15 22:23:56 +0000107 elif fileno is not None:
108 socket.__init__(self, fileno=fileno)
109 else:
110 socket.__init__(self, family=family, type=type, proto=proto)
111
112 self._closed = False
113
Thomas Woutersed03b412007-08-28 21:37:11 +0000114 if certfile and not keyfile:
115 keyfile = certfile
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000116 # see if it's connected
117 try:
118 socket.getpeername(self)
Antoine Pitrou365171d2010-04-26 17:32:49 +0000119 except socket_error as e:
120 if e.errno != errno.ENOTCONN:
121 raise
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000122 # no, no connection yet
123 self._sslobj = None
Thomas Woutersed03b412007-08-28 21:37:11 +0000124 else:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000125 # yes, create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000126 try:
127 self._sslobj = _ssl.sslwrap(self, server_side,
128 keyfile, certfile,
129 cert_reqs, ssl_version, ca_certs)
130 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000131 timeout = self.gettimeout()
132 if timeout == 0.0:
133 # non-blocking
134 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000135 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000136
Bill Janssen6e027db2007-11-15 22:23:56 +0000137 except socket_error as x:
138 self.close()
139 raise x
140
Thomas Woutersed03b412007-08-28 21:37:11 +0000141 self.keyfile = keyfile
142 self.certfile = certfile
143 self.cert_reqs = cert_reqs
144 self.ssl_version = ssl_version
145 self.ca_certs = ca_certs
Bill Janssen6e027db2007-11-15 22:23:56 +0000146 self.do_handshake_on_connect = do_handshake_on_connect
147 self.suppress_ragged_eofs = suppress_ragged_eofs
Thomas Woutersed03b412007-08-28 21:37:11 +0000148
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000149 def dup(self):
150 raise NotImplemented("Can't dup() %s instances" %
151 self.__class__.__name__)
152
Bill Janssen6e027db2007-11-15 22:23:56 +0000153 def _checkClosed(self, msg=None):
154 # raise an exception here if you wish to check for spurious closes
155 pass
156
Bill Janssen54cc54c2007-12-14 22:08:56 +0000157 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000158 """Read up to LEN bytes and return them.
159 Return zero-length string on EOF."""
160
Bill Janssen6e027db2007-11-15 22:23:56 +0000161 self._checkClosed()
162 try:
163 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000164 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000165 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000166 v = self._sslobj.read(len or 1024)
167 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000168 except SSLError as x:
169 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000170 if buffer:
171 return 0
172 else:
173 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000174 else:
175 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000176
177 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000178 """Write DATA to the underlying SSL channel. Returns
179 number of bytes of DATA actually transmitted."""
180
Bill Janssen6e027db2007-11-15 22:23:56 +0000181 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000182 return self._sslobj.write(data)
183
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000184 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000185 """Returns a formatted version of the data in the
186 certificate provided by the other end of the SSL channel.
187 Return None if no certificate was provided, {} if a
188 certificate was provided, but not validated."""
189
Bill Janssen6e027db2007-11-15 22:23:56 +0000190 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000191 return self._sslobj.peer_certificate(binary_form)
192
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000193 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000194 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000195 if not self._sslobj:
196 return None
197 else:
198 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000199
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000200 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000201 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000202 if self._sslobj:
203 if flags != 0:
204 raise ValueError(
205 "non-zero flags not allowed in calls to send() on %s" %
206 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000207 while True:
208 try:
209 v = self._sslobj.write(data)
210 except SSLError as x:
211 if x.args[0] == SSL_ERROR_WANT_READ:
212 return 0
213 elif x.args[0] == SSL_ERROR_WANT_WRITE:
214 return 0
215 else:
216 raise
217 else:
218 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000219 else:
220 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000221
Bill Janssen980f3142008-06-29 00:05:51 +0000222 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000223 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000224 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000225 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000226 self.__class__)
227 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000228 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000229
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000230 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000231 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000232 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000233 amount = len(data)
234 count = 0
235 while (count < amount):
236 v = self.send(data[count:])
237 count += v
238 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000239 else:
240 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000241
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000242 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000243 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000244 if self._sslobj:
245 if flags != 0:
246 raise ValueError(
Antoine Pitroua06bfd82010-03-22 15:09:31 +0000247 "non-zero flags not allowed in calls to recv() on %s" %
248 self.__class__)
249 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000250 else:
251 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000252
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000253 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000254 self._checkClosed()
255 if buffer and (nbytes is None):
256 nbytes = len(buffer)
257 elif nbytes is None:
258 nbytes = 1024
259 if self._sslobj:
260 if flags != 0:
261 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000262 "non-zero flags not allowed in calls to recv_into() on %s" %
263 self.__class__)
Antoine Pitroua06bfd82010-03-22 15:09:31 +0000264 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000265 else:
266 return socket.recv_into(self, buffer, nbytes, flags)
267
Bill Janssen980f3142008-06-29 00:05:51 +0000268 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000269 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000270 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000271 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000272 self.__class__)
273 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000274 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000275
Bill Janssen58afe4c2008-09-08 16:45:19 +0000276 def recvfrom_into(self, buffer, nbytes=None, flags=0):
277 self._checkClosed()
278 if self._sslobj:
279 raise ValueError("recvfrom_into not allowed on instances of %s" %
280 self.__class__)
281 else:
282 return socket.recvfrom_into(self, buffer, nbytes, flags)
283
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000284 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000285 self._checkClosed()
286 if self._sslobj:
287 return self._sslobj.pending()
288 else:
289 return 0
290
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000291 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000292 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000293 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000294 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000295
Ezio Melottib84420e2010-01-18 09:16:17 +0000296 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000297 if self._sslobj:
298 s = self._sslobj.shutdown()
299 self._sslobj = None
300 return s
301 else:
302 raise ValueError("No SSL wrapper around " + str(self))
303
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000304 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000305 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000306 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000307 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000308
Bill Janssen48dc27c2007-12-05 03:38:10 +0000309 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 """Perform a TLS/SSL handshake."""
311
Bill Janssen48dc27c2007-12-05 03:38:10 +0000312 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000313 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000314 if timeout == 0.0 and block:
315 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000316 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000317 finally:
318 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000319
320 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000321 """Connects to remote ADDR, and then wraps the connection in
322 an SSL channel."""
323
Thomas Woutersed03b412007-08-28 21:37:11 +0000324 # Here we assume that the socket is client-side, and not
325 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000326 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 socket.connect(self, addr)
Bill Janssen6e027db2007-11-15 22:23:56 +0000329 self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000330 self.cert_reqs, self.ssl_version,
331 self.ca_certs)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000332 try:
333 if self.do_handshake_on_connect:
334 self.do_handshake()
335 except:
336 self._sslobj = None
337 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000338
339 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000340 """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."""
343
344 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 return (SSLSocket(sock=newsock,
346 keyfile=self.keyfile, certfile=self.certfile,
347 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000348 cert_reqs=self.cert_reqs,
349 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000350 ca_certs=self.ca_certs,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000351 do_handshake_on_connect=
352 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000353 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354
Guido van Rossume6650f92007-12-06 19:05:55 +0000355 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000356 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000357 self._real_close()
358
Bill Janssen54cc54c2007-12-14 22:08:56 +0000359
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000360def wrap_socket(sock, keyfile=None, certfile=None,
361 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000362 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000363 do_handshake_on_connect=True,
364 suppress_ragged_eofs=True):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365
Bill Janssen6e027db2007-11-15 22:23:56 +0000366 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000367 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000368 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000369 do_handshake_on_connect=do_handshake_on_connect,
370 suppress_ragged_eofs=suppress_ragged_eofs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000371
Thomas Woutersed03b412007-08-28 21:37:11 +0000372# some utility functions
373
374def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000375 """Takes a date-time string in standard ASN1_print form
376 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
377 a Python time value in seconds past the epoch."""
378
Thomas Woutersed03b412007-08-28 21:37:11 +0000379 import time
380 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
381
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382PEM_HEADER = "-----BEGIN CERTIFICATE-----"
383PEM_FOOTER = "-----END CERTIFICATE-----"
384
385def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000386 """Takes a certificate in binary DER format and returns the
387 PEM version of it as a string."""
388
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
390 return (PEM_HEADER + '\n' +
391 textwrap.fill(f, 64) + '\n' +
392 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393
394def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395 """Takes a certificate in ASCII PEM format and returns the
396 DER-encoded version of it as a byte sequence"""
397
398 if not pem_cert_string.startswith(PEM_HEADER):
399 raise ValueError("Invalid PEM encoding; must start with %s"
400 % PEM_HEADER)
401 if not pem_cert_string.strip().endswith(PEM_FOOTER):
402 raise ValueError("Invalid PEM encoding; must end with %s"
403 % PEM_FOOTER)
404 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000405 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000407def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408 """Retrieve the certificate from the server at the specified address,
409 and return it as a PEM-encoded string.
410 If 'ca_certs' is specified, validate the server cert against it.
411 If 'ssl_version' is specified, use it in the connection attempt."""
412
413 host, port = addr
414 if (ca_certs is not None):
415 cert_reqs = CERT_REQUIRED
416 else:
417 cert_reqs = CERT_NONE
418 s = wrap_socket(socket(), ssl_version=ssl_version,
419 cert_reqs=cert_reqs, ca_certs=ca_certs)
420 s.connect(addr)
421 dercert = s.getpeercert(True)
422 s.close()
423 return DER_cert_to_PEM_cert(dercert)
424
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000425def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000426 if protocol_code == PROTOCOL_TLSv1:
427 return "TLSv1"
428 elif protocol_code == PROTOCOL_SSLv23:
429 return "SSLv23"
430 elif protocol_code == PROTOCOL_SSLv2:
431 return "SSLv2"
432 elif protocol_code == PROTOCOL_SSLv3:
433 return "SSLv3"
434 else:
435 return "<unknown>"