blob: e0096971640824d5b51294126a520980c6e080b0 [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
Thomas Wouters47b49bf2007-08-30 22:15:33 +000084
Guido van Rossum5b8b1552007-11-16 00:06:11 +000085class SSLSocket(socket):
Thomas Woutersed03b412007-08-28 21:37:11 +000086
Thomas Wouters47b49bf2007-08-30 22:15:33 +000087 """This class implements a subtype of socket.socket that wraps
88 the underlying OS socket in an SSL context when necessary, and
89 provides read and write methods over that channel."""
90
Bill Janssen6e027db2007-11-15 22:23:56 +000091 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +000092 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +000093 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
94 do_handshake_on_connect=True,
95 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
96 suppress_ragged_eofs=True):
97
Bill Janssen6e027db2007-11-15 22:23:56 +000098 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +000099 socket.__init__(self,
100 family=sock.family,
101 type=sock.type,
102 proto=sock.proto,
103 fileno=_dup(sock.fileno()))
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000104 sock.close()
Bill Janssen6e027db2007-11-15 22:23:56 +0000105 elif fileno is not None:
106 socket.__init__(self, fileno=fileno)
107 else:
108 socket.__init__(self, family=family, type=type, proto=proto)
109
110 self._closed = False
111
Thomas Woutersed03b412007-08-28 21:37:11 +0000112 if certfile and not keyfile:
113 keyfile = certfile
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000114 # see if it's connected
115 try:
116 socket.getpeername(self)
Benjamin Petersonc071d3a2008-12-31 04:10:35 +0000117 except socket_error:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000118 # no, no connection yet
119 self._sslobj = None
Thomas Woutersed03b412007-08-28 21:37:11 +0000120 else:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000121 # yes, create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000122 try:
123 self._sslobj = _ssl.sslwrap(self, server_side,
124 keyfile, certfile,
125 cert_reqs, ssl_version, ca_certs)
126 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000127 timeout = self.gettimeout()
128 if timeout == 0.0:
129 # non-blocking
130 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000131 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000132
Bill Janssen6e027db2007-11-15 22:23:56 +0000133 except socket_error as x:
134 self.close()
135 raise x
136
Thomas Woutersed03b412007-08-28 21:37:11 +0000137 self.keyfile = keyfile
138 self.certfile = certfile
139 self.cert_reqs = cert_reqs
140 self.ssl_version = ssl_version
141 self.ca_certs = ca_certs
Bill Janssen6e027db2007-11-15 22:23:56 +0000142 self.do_handshake_on_connect = do_handshake_on_connect
143 self.suppress_ragged_eofs = suppress_ragged_eofs
Thomas Woutersed03b412007-08-28 21:37:11 +0000144
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000145 def dup(self):
146 raise NotImplemented("Can't dup() %s instances" %
147 self.__class__.__name__)
148
Bill Janssen6e027db2007-11-15 22:23:56 +0000149 def _checkClosed(self, msg=None):
150 # raise an exception here if you wish to check for spurious closes
151 pass
152
Bill Janssen54cc54c2007-12-14 22:08:56 +0000153 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000154 """Read up to LEN bytes and return them.
155 Return zero-length string on EOF."""
156
Bill Janssen6e027db2007-11-15 22:23:56 +0000157 self._checkClosed()
158 try:
159 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000160 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000161 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000162 v = self._sslobj.read(len or 1024)
163 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000164 except SSLError as x:
165 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000166 if buffer:
167 return 0
168 else:
169 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000170 else:
171 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000172
173 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000174 """Write DATA to the underlying SSL channel. Returns
175 number of bytes of DATA actually transmitted."""
176
Bill Janssen6e027db2007-11-15 22:23:56 +0000177 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000178 return self._sslobj.write(data)
179
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000180 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000181 """Returns a formatted version of the data in the
182 certificate provided by the other end of the SSL channel.
183 Return None if no certificate was provided, {} if a
184 certificate was provided, but not validated."""
185
Bill Janssen6e027db2007-11-15 22:23:56 +0000186 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000187 return self._sslobj.peer_certificate(binary_form)
188
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000189 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000190 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000191 if not self._sslobj:
192 return None
193 else:
194 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000195
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000196 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000197 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000198 if self._sslobj:
199 if flags != 0:
200 raise ValueError(
201 "non-zero flags not allowed in calls to send() on %s" %
202 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000203 while True:
204 try:
205 v = self._sslobj.write(data)
206 except SSLError as x:
207 if x.args[0] == SSL_ERROR_WANT_READ:
208 return 0
209 elif x.args[0] == SSL_ERROR_WANT_WRITE:
210 return 0
211 else:
212 raise
213 else:
214 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000215 else:
216 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000217
Bill Janssen980f3142008-06-29 00:05:51 +0000218 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000219 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000220 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000221 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000222 self.__class__)
223 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000224 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000225
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000226 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000227 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000228 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000229 amount = len(data)
230 count = 0
231 while (count < amount):
232 v = self.send(data[count:])
233 count += v
234 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000235 else:
236 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000237
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000238 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000239 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000240 if self._sslobj:
241 if flags != 0:
242 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000243 "non-zero flags not allowed in calls to recv() on %s" %
244 self.__class__)
245 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000246 else:
247 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000248
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000249 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000250 self._checkClosed()
251 if buffer and (nbytes is None):
252 nbytes = len(buffer)
253 elif nbytes is None:
254 nbytes = 1024
255 if self._sslobj:
256 if flags != 0:
257 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000258 "non-zero flags not allowed in calls to recv_into() on %s" %
259 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000260 while True:
261 try:
262 v = self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000263 return v
264 except SSLError as x:
265 if x.args[0] == SSL_ERROR_WANT_READ:
266 continue
267 else:
268 raise x
Antoine Pitrou5733c082010-03-22 14:49:10 +0000269 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000270 else:
271 return socket.recv_into(self, buffer, nbytes, flags)
272
Bill Janssen980f3142008-06-29 00:05:51 +0000273 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000275 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000276 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000277 self.__class__)
278 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000279 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000280
Bill Janssen58afe4c2008-09-08 16:45:19 +0000281 def recvfrom_into(self, buffer, nbytes=None, flags=0):
282 self._checkClosed()
283 if self._sslobj:
284 raise ValueError("recvfrom_into not allowed on instances of %s" %
285 self.__class__)
286 else:
287 return socket.recvfrom_into(self, buffer, nbytes, flags)
288
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000289 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 self._checkClosed()
291 if self._sslobj:
292 return self._sslobj.pending()
293 else:
294 return 0
295
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000296 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000297 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000298 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000299 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000300
Ezio Melottidc55e672010-01-18 09:15:14 +0000301 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000302 if self._sslobj:
303 s = self._sslobj.shutdown()
304 self._sslobj = None
305 return s
306 else:
307 raise ValueError("No SSL wrapper around " + str(self))
308
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000309 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000311 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000312 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000313
Bill Janssen48dc27c2007-12-05 03:38:10 +0000314 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000315 """Perform a TLS/SSL handshake."""
316
Bill Janssen48dc27c2007-12-05 03:38:10 +0000317 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000318 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000319 if timeout == 0.0 and block:
320 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000321 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000322 finally:
323 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000324
325 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000326 """Connects to remote ADDR, and then wraps the connection in
327 an SSL channel."""
328
Thomas Woutersed03b412007-08-28 21:37:11 +0000329 # Here we assume that the socket is client-side, and not
330 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000331 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000332 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000333 socket.connect(self, addr)
Bill Janssen6e027db2007-11-15 22:23:56 +0000334 self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000335 self.cert_reqs, self.ssl_version,
336 self.ca_certs)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000337 try:
338 if self.do_handshake_on_connect:
339 self.do_handshake()
340 except:
341 self._sslobj = None
342 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000343
344 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000345 """Accepts a new connection from a remote client, and returns
346 a tuple containing that new connection wrapped with a server-side
347 SSL channel, and the address of the remote client."""
348
349 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000350 return (SSLSocket(sock=newsock,
351 keyfile=self.keyfile, certfile=self.certfile,
352 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000353 cert_reqs=self.cert_reqs,
354 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000355 ca_certs=self.ca_certs,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000356 do_handshake_on_connect=
357 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000359
Guido van Rossume6650f92007-12-06 19:05:55 +0000360 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000361 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000362 self._real_close()
363
Bill Janssen54cc54c2007-12-14 22:08:56 +0000364
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365def wrap_socket(sock, keyfile=None, certfile=None,
366 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000367 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000368 do_handshake_on_connect=True,
369 suppress_ragged_eofs=True):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370
Bill Janssen6e027db2007-11-15 22:23:56 +0000371 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000372 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000373 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000374 do_handshake_on_connect=do_handshake_on_connect,
375 suppress_ragged_eofs=suppress_ragged_eofs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000376
Thomas Woutersed03b412007-08-28 21:37:11 +0000377# some utility functions
378
379def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000380 """Takes a date-time string in standard ASN1_print form
381 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
382 a Python time value in seconds past the epoch."""
383
Thomas Woutersed03b412007-08-28 21:37:11 +0000384 import time
385 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
386
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387PEM_HEADER = "-----BEGIN CERTIFICATE-----"
388PEM_FOOTER = "-----END CERTIFICATE-----"
389
390def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000391 """Takes a certificate in binary DER format and returns the
392 PEM version of it as a string."""
393
Bill Janssen6e027db2007-11-15 22:23:56 +0000394 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
395 return (PEM_HEADER + '\n' +
396 textwrap.fill(f, 64) + '\n' +
397 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398
399def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400 """Takes a certificate in ASCII PEM format and returns the
401 DER-encoded version of it as a byte sequence"""
402
403 if not pem_cert_string.startswith(PEM_HEADER):
404 raise ValueError("Invalid PEM encoding; must start with %s"
405 % PEM_HEADER)
406 if not pem_cert_string.strip().endswith(PEM_FOOTER):
407 raise ValueError("Invalid PEM encoding; must end with %s"
408 % PEM_FOOTER)
409 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000410 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000412def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413 """Retrieve the certificate from the server at the specified address,
414 and return it as a PEM-encoded string.
415 If 'ca_certs' is specified, validate the server cert against it.
416 If 'ssl_version' is specified, use it in the connection attempt."""
417
418 host, port = addr
419 if (ca_certs is not None):
420 cert_reqs = CERT_REQUIRED
421 else:
422 cert_reqs = CERT_NONE
423 s = wrap_socket(socket(), ssl_version=ssl_version,
424 cert_reqs=cert_reqs, ca_certs=ca_certs)
425 s.connect(addr)
426 dercert = s.getpeercert(True)
427 s.close()
428 return DER_cert_to_PEM_cert(dercert)
429
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000430def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431 if protocol_code == PROTOCOL_TLSv1:
432 return "TLSv1"
433 elif protocol_code == PROTOCOL_SSLv23:
434 return "SSLv23"
435 elif protocol_code == PROTOCOL_SSLv2:
436 return "SSLv2"
437 elif protocol_code == PROTOCOL_SSLv3:
438 return "SSLv3"
439 else:
440 return "<unknown>"