blob: 75f542d44ab5ac974d84cb930dcd823164312984 [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000062from _ssl import 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)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000066from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000067from _ssl import (
68 SSL_ERROR_ZERO_RETURN,
69 SSL_ERROR_WANT_READ,
70 SSL_ERROR_WANT_WRITE,
71 SSL_ERROR_WANT_X509_LOOKUP,
72 SSL_ERROR_SYSCALL,
73 SSL_ERROR_SSL,
74 SSL_ERROR_WANT_CONNECT,
75 SSL_ERROR_EOF,
76 SSL_ERROR_INVALID_ERROR_CODE,
77 )
Thomas Woutersed03b412007-08-28 21:37:11 +000078
Thomas Wouters47b49bf2007-08-30 22:15:33 +000079from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000080from socket import error as socket_error
Guido van Rossum39eb8fa2007-11-16 01:24:05 +000081from socket import dup as _dup
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
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()))
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000105 sock.close()
Bill Janssen6e027db2007-11-15 22:23:56 +0000106 elif fileno is not None:
107 socket.__init__(self, fileno=fileno)
108 else:
109 socket.__init__(self, family=family, type=type, proto=proto)
110
111 self._closed = False
112
Thomas Woutersed03b412007-08-28 21:37:11 +0000113 if certfile and not keyfile:
114 keyfile = certfile
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000115 # see if it's connected
116 try:
117 socket.getpeername(self)
Benjamin Petersonc071d3a2008-12-31 04:10:35 +0000118 except socket_error:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000119 # no, no connection yet
120 self._sslobj = None
Thomas Woutersed03b412007-08-28 21:37:11 +0000121 else:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000122 # yes, create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000123 try:
124 self._sslobj = _ssl.sslwrap(self, server_side,
125 keyfile, certfile,
126 cert_reqs, ssl_version, ca_certs)
127 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000128 timeout = self.gettimeout()
129 if timeout == 0.0:
130 # non-blocking
131 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000132 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000133
Bill Janssen6e027db2007-11-15 22:23:56 +0000134 except socket_error as x:
135 self.close()
136 raise x
137
Thomas Woutersed03b412007-08-28 21:37:11 +0000138 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
Bill Janssen6e027db2007-11-15 22:23:56 +0000143 self.do_handshake_on_connect = do_handshake_on_connect
144 self.suppress_ragged_eofs = suppress_ragged_eofs
Thomas Woutersed03b412007-08-28 21:37:11 +0000145
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000146 def dup(self):
147 raise NotImplemented("Can't dup() %s instances" %
148 self.__class__.__name__)
149
Bill Janssen6e027db2007-11-15 22:23:56 +0000150 def _checkClosed(self, msg=None):
151 # raise an exception here if you wish to check for spurious closes
152 pass
153
Bill Janssen54cc54c2007-12-14 22:08:56 +0000154 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000155 """Read up to LEN bytes and return them.
156 Return zero-length string on EOF."""
157
Bill Janssen6e027db2007-11-15 22:23:56 +0000158 self._checkClosed()
159 try:
160 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000161 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000162 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000163 v = self._sslobj.read(len or 1024)
164 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000165 except SSLError as x:
166 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000167 if buffer:
168 return 0
169 else:
170 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000171 else:
172 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000173
174 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000175 """Write DATA to the underlying SSL channel. Returns
176 number of bytes of DATA actually transmitted."""
177
Bill Janssen6e027db2007-11-15 22:23:56 +0000178 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000179 return self._sslobj.write(data)
180
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000181 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000182 """Returns a formatted version of the data in the
183 certificate provided by the other end of the SSL channel.
184 Return None if no certificate was provided, {} if a
185 certificate was provided, but not validated."""
186
Bill Janssen6e027db2007-11-15 22:23:56 +0000187 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000188 return self._sslobj.peer_certificate(binary_form)
189
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000190 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000191 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000192 if not self._sslobj:
193 return None
194 else:
195 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000196
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000197 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000198 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000199 if self._sslobj:
200 if flags != 0:
201 raise ValueError(
202 "non-zero flags not allowed in calls to send() on %s" %
203 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000204 while True:
205 try:
206 v = self._sslobj.write(data)
207 except SSLError as x:
208 if x.args[0] == SSL_ERROR_WANT_READ:
209 return 0
210 elif x.args[0] == SSL_ERROR_WANT_WRITE:
211 return 0
212 else:
213 raise
214 else:
215 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000216 else:
217 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000218
Bill Janssen980f3142008-06-29 00:05:51 +0000219 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000220 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000221 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000222 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000223 self.__class__)
224 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000225 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000226
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000227 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000228 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000229 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000230 amount = len(data)
231 count = 0
232 while (count < amount):
233 v = self.send(data[count:])
234 count += v
235 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000236 else:
237 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000238
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000239 def recv(self, buflen=1024, 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(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000244 "non-zero flags not allowed in calls to recv() on %s" %
245 self.__class__)
246 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000247 else:
248 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000249
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000250 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000251 self._checkClosed()
252 if buffer and (nbytes is None):
253 nbytes = len(buffer)
254 elif nbytes is None:
255 nbytes = 1024
256 if self._sslobj:
257 if flags != 0:
258 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000259 "non-zero flags not allowed in calls to recv_into() on %s" %
260 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000261 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000262 else:
263 return socket.recv_into(self, buffer, nbytes, flags)
264
Bill Janssen980f3142008-06-29 00:05:51 +0000265 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000266 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000267 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000268 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000269 self.__class__)
270 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000271 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000272
Bill Janssen58afe4c2008-09-08 16:45:19 +0000273 def recvfrom_into(self, buffer, nbytes=None, flags=0):
274 self._checkClosed()
275 if self._sslobj:
276 raise ValueError("recvfrom_into not allowed on instances of %s" %
277 self.__class__)
278 else:
279 return socket.recvfrom_into(self, buffer, nbytes, flags)
280
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000281 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000282 self._checkClosed()
283 if self._sslobj:
284 return self._sslobj.pending()
285 else:
286 return 0
287
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000288 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000290 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000291 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000292
Ezio Melottidc55e672010-01-18 09:15:14 +0000293 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000294 if self._sslobj:
295 s = self._sslobj.shutdown()
296 self._sslobj = None
297 return s
298 else:
299 raise ValueError("No SSL wrapper around " + str(self))
300
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000301 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000302 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000304 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000305
Bill Janssen48dc27c2007-12-05 03:38:10 +0000306 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000307 """Perform a TLS/SSL handshake."""
308
Bill Janssen48dc27c2007-12-05 03:38:10 +0000309 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000311 if timeout == 0.0 and block:
312 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000313 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000314 finally:
315 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000316
317 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000318 """Connects to remote ADDR, and then wraps the connection in
319 an SSL channel."""
320
Thomas Woutersed03b412007-08-28 21:37:11 +0000321 # Here we assume that the socket is client-side, and not
322 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000323 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000324 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000325 socket.connect(self, addr)
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000327 self.cert_reqs, self.ssl_version,
328 self.ca_certs)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000329 try:
330 if self.do_handshake_on_connect:
331 self.do_handshake()
332 except:
333 self._sslobj = None
334 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000335
336 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000337 """Accepts a new connection from a remote client, and returns
338 a tuple containing that new connection wrapped with a server-side
339 SSL channel, and the address of the remote client."""
340
341 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000342 return (SSLSocket(sock=newsock,
343 keyfile=self.keyfile, certfile=self.certfile,
344 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000345 cert_reqs=self.cert_reqs,
346 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000347 ca_certs=self.ca_certs,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000348 do_handshake_on_connect=
349 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000350 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000351
Guido van Rossume6650f92007-12-06 19:05:55 +0000352 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000353 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000354 self._real_close()
355
Bill Janssen54cc54c2007-12-14 22:08:56 +0000356
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000357def wrap_socket(sock, keyfile=None, certfile=None,
358 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000359 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000360 do_handshake_on_connect=True,
361 suppress_ragged_eofs=True):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000362
Bill Janssen6e027db2007-11-15 22:23:56 +0000363 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000364 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000365 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000366 do_handshake_on_connect=do_handshake_on_connect,
367 suppress_ragged_eofs=suppress_ragged_eofs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000368
Thomas Woutersed03b412007-08-28 21:37:11 +0000369# some utility functions
370
371def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000372 """Takes a date-time string in standard ASN1_print form
373 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
374 a Python time value in seconds past the epoch."""
375
Thomas Woutersed03b412007-08-28 21:37:11 +0000376 import time
377 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
378
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000379PEM_HEADER = "-----BEGIN CERTIFICATE-----"
380PEM_FOOTER = "-----END CERTIFICATE-----"
381
382def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383 """Takes a certificate in binary DER format and returns the
384 PEM version of it as a string."""
385
Bill Janssen6e027db2007-11-15 22:23:56 +0000386 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
387 return (PEM_HEADER + '\n' +
388 textwrap.fill(f, 64) + '\n' +
389 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000390
391def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000392 """Takes a certificate in ASCII PEM format and returns the
393 DER-encoded version of it as a byte sequence"""
394
395 if not pem_cert_string.startswith(PEM_HEADER):
396 raise ValueError("Invalid PEM encoding; must start with %s"
397 % PEM_HEADER)
398 if not pem_cert_string.strip().endswith(PEM_FOOTER):
399 raise ValueError("Invalid PEM encoding; must end with %s"
400 % PEM_FOOTER)
401 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000402 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000403
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000404def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405 """Retrieve the certificate from the server at the specified address,
406 and return it as a PEM-encoded string.
407 If 'ca_certs' is specified, validate the server cert against it.
408 If 'ssl_version' is specified, use it in the connection attempt."""
409
410 host, port = addr
411 if (ca_certs is not None):
412 cert_reqs = CERT_REQUIRED
413 else:
414 cert_reqs = CERT_NONE
415 s = wrap_socket(socket(), ssl_version=ssl_version,
416 cert_reqs=cert_reqs, ca_certs=ca_certs)
417 s.connect(addr)
418 dercert = s.getpeercert(True)
419 s.close()
420 return DER_cert_to_PEM_cert(dercert)
421
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000422def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000423 if protocol_code == PROTOCOL_TLSv1:
424 return "TLSv1"
425 elif protocol_code == PROTOCOL_SSLv23:
426 return "SSLv23"
427 elif protocol_code == PROTOCOL_SSLv2:
428 return "SSLv2"
429 elif protocol_code == PROTOCOL_SSLv3:
430 return "SSLv3"
431 else:
432 return "<unknown>"