blob: a42643fa10e31ddf68b602aa465890e87287e61c [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,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +000097 suppress_ragged_eofs=True, ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +000098
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,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000126 cert_reqs, ssl_version, ca_certs,
127 ciphers)
Bill Janssen6e027db2007-11-15 22:23:56 +0000128 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000129 timeout = self.gettimeout()
130 if timeout == 0.0:
131 # non-blocking
132 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000133 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000134
Bill Janssen6e027db2007-11-15 22:23:56 +0000135 except socket_error as x:
136 self.close()
137 raise x
138
Thomas Woutersed03b412007-08-28 21:37:11 +0000139 self.keyfile = keyfile
140 self.certfile = certfile
141 self.cert_reqs = cert_reqs
142 self.ssl_version = ssl_version
143 self.ca_certs = ca_certs
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000144 self.ciphers = ciphers
Bill Janssen6e027db2007-11-15 22:23:56 +0000145 self.do_handshake_on_connect = do_handshake_on_connect
146 self.suppress_ragged_eofs = suppress_ragged_eofs
Thomas Woutersed03b412007-08-28 21:37:11 +0000147
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000148 def dup(self):
149 raise NotImplemented("Can't dup() %s instances" %
150 self.__class__.__name__)
151
Bill Janssen6e027db2007-11-15 22:23:56 +0000152 def _checkClosed(self, msg=None):
153 # raise an exception here if you wish to check for spurious closes
154 pass
155
Bill Janssen54cc54c2007-12-14 22:08:56 +0000156 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000157 """Read up to LEN bytes and return them.
158 Return zero-length string on EOF."""
159
Bill Janssen6e027db2007-11-15 22:23:56 +0000160 self._checkClosed()
161 try:
162 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000163 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000164 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000165 v = self._sslobj.read(len or 1024)
166 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000167 except SSLError as x:
168 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000169 if buffer:
170 return 0
171 else:
172 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000173 else:
174 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
176 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000177 """Write DATA to the underlying SSL channel. Returns
178 number of bytes of DATA actually transmitted."""
179
Bill Janssen6e027db2007-11-15 22:23:56 +0000180 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000181 return self._sslobj.write(data)
182
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000183 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000184 """Returns a formatted version of the data in the
185 certificate provided by the other end of the SSL channel.
186 Return None if no certificate was provided, {} if a
187 certificate was provided, but not validated."""
188
Bill Janssen6e027db2007-11-15 22:23:56 +0000189 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000190 return self._sslobj.peer_certificate(binary_form)
191
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000192 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000193 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000194 if not self._sslobj:
195 return None
196 else:
197 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000198
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000199 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000200 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000201 if self._sslobj:
202 if flags != 0:
203 raise ValueError(
204 "non-zero flags not allowed in calls to send() on %s" %
205 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000206 while True:
207 try:
208 v = self._sslobj.write(data)
209 except SSLError as x:
210 if x.args[0] == SSL_ERROR_WANT_READ:
211 return 0
212 elif x.args[0] == SSL_ERROR_WANT_WRITE:
213 return 0
214 else:
215 raise
216 else:
217 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000218 else:
219 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000220
Bill Janssen980f3142008-06-29 00:05:51 +0000221 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000222 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000223 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000224 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000225 self.__class__)
226 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000227 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000228
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000229 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000230 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000231 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000232 amount = len(data)
233 count = 0
234 while (count < amount):
235 v = self.send(data[count:])
236 count += v
237 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000238 else:
239 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000240
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000241 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000242 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000243 if self._sslobj:
244 if flags != 0:
245 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000246 "non-zero flags not allowed in calls to recv() on %s" %
247 self.__class__)
248 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000249 else:
250 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000251
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000252 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000253 self._checkClosed()
254 if buffer and (nbytes is None):
255 nbytes = len(buffer)
256 elif nbytes is None:
257 nbytes = 1024
258 if self._sslobj:
259 if flags != 0:
260 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000261 "non-zero flags not allowed in calls to recv_into() on %s" %
262 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000263 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 else:
265 return socket.recv_into(self, buffer, nbytes, flags)
266
Bill Janssen980f3142008-06-29 00:05:51 +0000267 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000268 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000269 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000270 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000271 self.__class__)
272 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000273 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000274
Bill Janssen58afe4c2008-09-08 16:45:19 +0000275 def recvfrom_into(self, buffer, nbytes=None, flags=0):
276 self._checkClosed()
277 if self._sslobj:
278 raise ValueError("recvfrom_into not allowed on instances of %s" %
279 self.__class__)
280 else:
281 return socket.recvfrom_into(self, buffer, nbytes, flags)
282
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000283 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000284 self._checkClosed()
285 if self._sslobj:
286 return self._sslobj.pending()
287 else:
288 return 0
289
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000290 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000291 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000292 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000293 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000294
Ezio Melottidc55e672010-01-18 09:15:14 +0000295 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000296 if self._sslobj:
297 s = self._sslobj.shutdown()
298 self._sslobj = None
299 return s
300 else:
301 raise ValueError("No SSL wrapper around " + str(self))
302
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000303 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000305 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000306 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000307
Bill Janssen48dc27c2007-12-05 03:38:10 +0000308 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000309 """Perform a TLS/SSL handshake."""
310
Bill Janssen48dc27c2007-12-05 03:38:10 +0000311 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000312 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000313 if timeout == 0.0 and block:
314 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000315 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000316 finally:
317 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000318
319 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000320 """Connects to remote ADDR, and then wraps the connection in
321 an SSL channel."""
322
Thomas Woutersed03b412007-08-28 21:37:11 +0000323 # Here we assume that the socket is client-side, and not
324 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000325 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000326 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000327 socket.connect(self, addr)
Bill Janssen6e027db2007-11-15 22:23:56 +0000328 self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile,
Thomas Woutersed03b412007-08-28 21:37:11 +0000329 self.cert_reqs, self.ssl_version,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000330 self.ca_certs, self.ciphers)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000331 try:
332 if self.do_handshake_on_connect:
333 self.do_handshake()
334 except:
335 self._sslobj = None
336 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000337
338 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000339 """Accepts a new connection from a remote client, and returns
340 a tuple containing that new connection wrapped with a server-side
341 SSL channel, and the address of the remote client."""
342
343 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 return (SSLSocket(sock=newsock,
345 keyfile=self.keyfile, certfile=self.certfile,
346 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000347 cert_reqs=self.cert_reqs,
348 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000349 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000350 ciphers=self.ciphers,
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,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000364 suppress_ragged_eofs=True, ciphers=None):
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,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000370 suppress_ragged_eofs=suppress_ragged_eofs,
371 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000372
Thomas Woutersed03b412007-08-28 21:37:11 +0000373# some utility functions
374
375def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376 """Takes a date-time string in standard ASN1_print form
377 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
378 a Python time value in seconds past the epoch."""
379
Thomas Woutersed03b412007-08-28 21:37:11 +0000380 import time
381 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
382
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383PEM_HEADER = "-----BEGIN CERTIFICATE-----"
384PEM_FOOTER = "-----END CERTIFICATE-----"
385
386def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387 """Takes a certificate in binary DER format and returns the
388 PEM version of it as a string."""
389
Bill Janssen6e027db2007-11-15 22:23:56 +0000390 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
391 return (PEM_HEADER + '\n' +
392 textwrap.fill(f, 64) + '\n' +
393 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394
395def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000396 """Takes a certificate in ASCII PEM format and returns the
397 DER-encoded version of it as a byte sequence"""
398
399 if not pem_cert_string.startswith(PEM_HEADER):
400 raise ValueError("Invalid PEM encoding; must start with %s"
401 % PEM_HEADER)
402 if not pem_cert_string.strip().endswith(PEM_FOOTER):
403 raise ValueError("Invalid PEM encoding; must end with %s"
404 % PEM_FOOTER)
405 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000406 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000407
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000408def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409 """Retrieve the certificate from the server at the specified address,
410 and return it as a PEM-encoded string.
411 If 'ca_certs' is specified, validate the server cert against it.
412 If 'ssl_version' is specified, use it in the connection attempt."""
413
414 host, port = addr
415 if (ca_certs is not None):
416 cert_reqs = CERT_REQUIRED
417 else:
418 cert_reqs = CERT_NONE
419 s = wrap_socket(socket(), ssl_version=ssl_version,
420 cert_reqs=cert_reqs, ca_certs=ca_certs)
421 s.connect(addr)
422 dercert = s.getpeercert(True)
423 s.close()
424 return DER_cert_to_PEM_cert(dercert)
425
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000426def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427 if protocol_code == PROTOCOL_TLSv1:
428 return "TLSv1"
429 elif protocol_code == PROTOCOL_SSLv23:
430 return "SSLv23"
431 elif protocol_code == PROTOCOL_SSLv2:
432 return "SSLv2"
433 elif protocol_code == PROTOCOL_SSLv3:
434 return "SSLv3"
435 else:
436 return "<unknown>"