blob: f98bd73428ff7af71275481a9d7fd883df9109fb [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
Antoine Pitrou28f7ab62010-04-26 22:37:59 +000099 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000100 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000101 socket.__init__(self,
102 family=sock.family,
103 type=sock.type,
104 proto=sock.proto,
105 fileno=_dup(sock.fileno()))
Antoine Pitrouc2203f92010-04-24 22:07:51 +0000106 self.settimeout(sock.gettimeout())
Antoine Pitrou28f7ab62010-04-26 22:37:59 +0000107 # see if it's connected
108 try:
109 sock.getpeername()
110 except socket_error as e:
111 if e.errno != errno.ENOTCONN:
112 raise
113 else:
114 connected = True
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000115 sock.close()
Bill Janssen6e027db2007-11-15 22:23:56 +0000116 elif fileno is not None:
117 socket.__init__(self, fileno=fileno)
118 else:
119 socket.__init__(self, family=family, type=type, proto=proto)
120
Thomas Woutersed03b412007-08-28 21:37:11 +0000121 if certfile and not keyfile:
122 keyfile = certfile
Antoine Pitrou28f7ab62010-04-26 22:37:59 +0000123
124 self._closed = False
125 self._sslobj = None
126 if connected:
127 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000128 try:
129 self._sslobj = _ssl.sslwrap(self, server_side,
130 keyfile, certfile,
131 cert_reqs, ssl_version, ca_certs)
132 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000133 timeout = self.gettimeout()
134 if timeout == 0.0:
135 # non-blocking
136 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000137 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000138
Bill Janssen6e027db2007-11-15 22:23:56 +0000139 except socket_error as x:
140 self.close()
141 raise x
142
Thomas Woutersed03b412007-08-28 21:37:11 +0000143 self.keyfile = keyfile
144 self.certfile = certfile
145 self.cert_reqs = cert_reqs
146 self.ssl_version = ssl_version
147 self.ca_certs = ca_certs
Bill Janssen6e027db2007-11-15 22:23:56 +0000148 self.do_handshake_on_connect = do_handshake_on_connect
149 self.suppress_ragged_eofs = suppress_ragged_eofs
Thomas Woutersed03b412007-08-28 21:37:11 +0000150
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000151 def dup(self):
152 raise NotImplemented("Can't dup() %s instances" %
153 self.__class__.__name__)
154
Bill Janssen6e027db2007-11-15 22:23:56 +0000155 def _checkClosed(self, msg=None):
156 # raise an exception here if you wish to check for spurious closes
157 pass
158
Bill Janssen54cc54c2007-12-14 22:08:56 +0000159 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000160 """Read up to LEN bytes and return them.
161 Return zero-length string on EOF."""
162
Bill Janssen6e027db2007-11-15 22:23:56 +0000163 self._checkClosed()
164 try:
Antoine Pitrou10c4c232010-09-03 18:39:47 +0000165 if buffer is not None:
166 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000167 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000168 v = self._sslobj.read(len or 1024)
169 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000170 except SSLError as x:
171 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou10c4c232010-09-03 18:39:47 +0000172 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000173 return 0
174 else:
175 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000176 else:
177 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000178
179 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000180 """Write DATA to the underlying SSL channel. Returns
181 number of bytes of DATA actually transmitted."""
182
Bill Janssen6e027db2007-11-15 22:23:56 +0000183 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000184 return self._sslobj.write(data)
185
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000186 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000187 """Returns a formatted version of the data in the
188 certificate provided by the other end of the SSL channel.
189 Return None if no certificate was provided, {} if a
190 certificate was provided, but not validated."""
191
Bill Janssen6e027db2007-11-15 22:23:56 +0000192 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000193 return self._sslobj.peer_certificate(binary_form)
194
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000195 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000196 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000197 if not self._sslobj:
198 return None
199 else:
200 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000201
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000202 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000203 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000204 if self._sslobj:
205 if flags != 0:
206 raise ValueError(
207 "non-zero flags not allowed in calls to send() on %s" %
208 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000209 while True:
210 try:
211 v = self._sslobj.write(data)
212 except SSLError as x:
213 if x.args[0] == SSL_ERROR_WANT_READ:
214 return 0
215 elif x.args[0] == SSL_ERROR_WANT_WRITE:
216 return 0
217 else:
218 raise
219 else:
220 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000221 else:
222 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000223
Antoine Pitrou5974cdd2010-09-14 14:47:08 +0000224 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000225 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000226 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000227 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000228 self.__class__)
Antoine Pitrou5974cdd2010-09-14 14:47:08 +0000229 elif addr is None:
230 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000231 else:
Antoine Pitrou5974cdd2010-09-14 14:47:08 +0000232 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000233
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000234 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000235 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000236 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000237 amount = len(data)
238 count = 0
239 while (count < amount):
240 v = self.send(data[count:])
241 count += v
242 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000243 else:
244 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000245
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000246 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000247 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000248 if self._sslobj:
249 if flags != 0:
250 raise ValueError(
Antoine Pitroua06bfd82010-03-22 15:09:31 +0000251 "non-zero flags not allowed in calls to recv() on %s" %
252 self.__class__)
253 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000254 else:
255 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000257 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000258 self._checkClosed()
259 if buffer and (nbytes is None):
260 nbytes = len(buffer)
261 elif nbytes is None:
262 nbytes = 1024
263 if self._sslobj:
264 if flags != 0:
265 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000266 "non-zero flags not allowed in calls to recv_into() on %s" %
267 self.__class__)
Antoine Pitroua06bfd82010-03-22 15:09:31 +0000268 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000269 else:
270 return socket.recv_into(self, buffer, nbytes, flags)
271
Antoine Pitrou5974cdd2010-09-14 14:47:08 +0000272 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000273 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000274 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000275 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000276 self.__class__)
277 else:
Antoine Pitrou5974cdd2010-09-14 14:47:08 +0000278 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000279
Bill Janssen58afe4c2008-09-08 16:45:19 +0000280 def recvfrom_into(self, buffer, nbytes=None, flags=0):
281 self._checkClosed()
282 if self._sslobj:
283 raise ValueError("recvfrom_into not allowed on instances of %s" %
284 self.__class__)
285 else:
286 return socket.recvfrom_into(self, buffer, nbytes, flags)
287
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000288 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 self._checkClosed()
290 if self._sslobj:
291 return self._sslobj.pending()
292 else:
293 return 0
294
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000295 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000296 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000298 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000299
Ezio Melottib84420e2010-01-18 09:16:17 +0000300 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000301 if self._sslobj:
302 s = self._sslobj.shutdown()
303 self._sslobj = None
304 return s
305 else:
306 raise ValueError("No SSL wrapper around " + str(self))
307
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000308 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000309 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000311 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000312
Bill Janssen48dc27c2007-12-05 03:38:10 +0000313 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000314 """Perform a TLS/SSL handshake."""
315
Bill Janssen48dc27c2007-12-05 03:38:10 +0000316 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000317 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000318 if timeout == 0.0 and block:
319 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000320 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000321 finally:
322 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
324 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000325 """Connects to remote ADDR, and then wraps the connection in
326 an SSL channel."""
327
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 # Here we assume that the socket is client-side, and not
329 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000330 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000332 socket.connect(self, addr)
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000334 self.cert_reqs, self.ssl_version,
335 self.ca_certs)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000336 try:
337 if self.do_handshake_on_connect:
338 self.do_handshake()
339 except:
340 self._sslobj = None
341 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000342
343 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000344 """Accepts a new connection from a remote client, and returns
345 a tuple containing that new connection wrapped with a server-side
346 SSL channel, and the address of the remote client."""
347
348 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000349 return (SSLSocket(sock=newsock,
350 keyfile=self.keyfile, certfile=self.certfile,
351 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000352 cert_reqs=self.cert_reqs,
353 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000354 ca_certs=self.ca_certs,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000355 do_handshake_on_connect=
356 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000357 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000358
Guido van Rossume6650f92007-12-06 19:05:55 +0000359 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000360 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000361 self._real_close()
362
Bill Janssen54cc54c2007-12-14 22:08:56 +0000363
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000364def wrap_socket(sock, keyfile=None, certfile=None,
365 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000366 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000367 do_handshake_on_connect=True,
368 suppress_ragged_eofs=True):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000369
Bill Janssen6e027db2007-11-15 22:23:56 +0000370 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000371 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000372 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000373 do_handshake_on_connect=do_handshake_on_connect,
374 suppress_ragged_eofs=suppress_ragged_eofs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000375
Thomas Woutersed03b412007-08-28 21:37:11 +0000376# some utility functions
377
378def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000379 """Takes a date-time string in standard ASN1_print form
380 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
381 a Python time value in seconds past the epoch."""
382
Thomas Woutersed03b412007-08-28 21:37:11 +0000383 import time
384 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
385
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000386PEM_HEADER = "-----BEGIN CERTIFICATE-----"
387PEM_FOOTER = "-----END CERTIFICATE-----"
388
389def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000390 """Takes a certificate in binary DER format and returns the
391 PEM version of it as a string."""
392
Bill Janssen6e027db2007-11-15 22:23:56 +0000393 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
394 return (PEM_HEADER + '\n' +
395 textwrap.fill(f, 64) + '\n' +
396 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000397
398def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399 """Takes a certificate in ASCII PEM format and returns the
400 DER-encoded version of it as a byte sequence"""
401
402 if not pem_cert_string.startswith(PEM_HEADER):
403 raise ValueError("Invalid PEM encoding; must start with %s"
404 % PEM_HEADER)
405 if not pem_cert_string.strip().endswith(PEM_FOOTER):
406 raise ValueError("Invalid PEM encoding; must end with %s"
407 % PEM_FOOTER)
408 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000409 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000410
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000411def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000412 """Retrieve the certificate from the server at the specified address,
413 and return it as a PEM-encoded string.
414 If 'ca_certs' is specified, validate the server cert against it.
415 If 'ssl_version' is specified, use it in the connection attempt."""
416
417 host, port = addr
418 if (ca_certs is not None):
419 cert_reqs = CERT_REQUIRED
420 else:
421 cert_reqs = CERT_NONE
422 s = wrap_socket(socket(), ssl_version=ssl_version,
423 cert_reqs=cert_reqs, ca_certs=ca_certs)
424 s.connect(addr)
425 dercert = s.getpeercert(True)
426 s.close()
427 return DER_cert_to_PEM_cert(dercert)
428
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000429def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000430 if protocol_code == PROTOCOL_TLSv1:
431 return "TLSv1"
432 elif protocol_code == PROTOCOL_SSLv23:
433 return "SSLv23"
434 elif protocol_code == PROTOCOL_SSLv2:
435 return "SSLv2"
436 elif protocol_code == PROTOCOL_SSLv3:
437 return "SSLv3"
438 else:
439 return "<unknown>"