blob: 585105d1cc4f00df2e5abc115c148c95b57298d2 [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
Antoine Pitrou152efa22010-05-16 18:19:27 +000062from _ssl import _SSLContext, 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)
Antoine Pitroub5218772010-05-21 09:56:06 +000066from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000067from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000068from _ssl import (
69 SSL_ERROR_ZERO_RETURN,
70 SSL_ERROR_WANT_READ,
71 SSL_ERROR_WANT_WRITE,
72 SSL_ERROR_WANT_X509_LOOKUP,
73 SSL_ERROR_SYSCALL,
74 SSL_ERROR_SSL,
75 SSL_ERROR_WANT_CONNECT,
76 SSL_ERROR_EOF,
77 SSL_ERROR_INVALID_ERROR_CODE,
78 )
Thomas Woutersed03b412007-08-28 21:37:11 +000079
Thomas Wouters47b49bf2007-08-30 22:15:33 +000080from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000081from socket import error as socket_error
Guido van Rossum39eb8fa2007-11-16 01:24:05 +000082from socket import dup as _dup
Bill Janssen40a0f662008-08-12 16:56:25 +000083from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000084import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000085import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000086import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000087
Thomas Woutersed03b412007-08-28 21:37:11 +000088
Antoine Pitrou152efa22010-05-16 18:19:27 +000089class SSLContext(_SSLContext):
90 """An SSLContext holds various SSL-related configuration options and
91 data, such as certificates and possibly a private key."""
92
93 __slots__ = ('protocol',)
94
95 def __new__(cls, protocol, *args, **kwargs):
96 return _SSLContext.__new__(cls, protocol)
97
98 def __init__(self, protocol):
99 self.protocol = protocol
100
101 def wrap_socket(self, sock, server_side=False,
102 do_handshake_on_connect=True,
103 suppress_ragged_eofs=True):
104 return SSLSocket(sock=sock, server_side=server_side,
105 do_handshake_on_connect=do_handshake_on_connect,
106 suppress_ragged_eofs=suppress_ragged_eofs,
107 _context=self)
108
109
110class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000111 """This class implements a subtype of socket.socket that wraps
112 the underlying OS socket in an SSL context when necessary, and
113 provides read and write methods over that channel."""
114
Bill Janssen6e027db2007-11-15 22:23:56 +0000115 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000116 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000117 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
118 do_handshake_on_connect=True,
119 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000120 suppress_ragged_eofs=True, ciphers=None,
121 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000122
Antoine Pitrou152efa22010-05-16 18:19:27 +0000123 if _context:
124 self.context = _context
125 else:
126 if certfile and not keyfile:
127 keyfile = certfile
128 self.context = SSLContext(ssl_version)
129 self.context.verify_mode = cert_reqs
130 if ca_certs:
131 self.context.load_verify_locations(ca_certs)
132 if certfile:
133 self.context.load_cert_chain(certfile, keyfile)
134 if ciphers:
135 self.context.set_ciphers(ciphers)
136 self.keyfile = keyfile
137 self.certfile = certfile
138 self.cert_reqs = cert_reqs
139 self.ssl_version = ssl_version
140 self.ca_certs = ca_certs
141 self.ciphers = ciphers
142
143 self.do_handshake_on_connect = do_handshake_on_connect
144 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000145 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000146 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000147 socket.__init__(self,
148 family=sock.family,
149 type=sock.type,
150 proto=sock.proto,
151 fileno=_dup(sock.fileno()))
Antoine Pitrou40f08742010-04-24 22:04:40 +0000152 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000153 # see if it's connected
154 try:
155 sock.getpeername()
156 except socket_error as e:
157 if e.errno != errno.ENOTCONN:
158 raise
159 else:
160 connected = True
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000161 sock.close()
Bill Janssen6e027db2007-11-15 22:23:56 +0000162 elif fileno is not None:
163 socket.__init__(self, fileno=fileno)
164 else:
165 socket.__init__(self, family=family, type=type, proto=proto)
166
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000167 self._closed = False
168 self._sslobj = None
169 if connected:
170 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000171 try:
Antoine Pitrou152efa22010-05-16 18:19:27 +0000172 self._sslobj = self.context._wrap_socket(self, server_side)
Bill Janssen6e027db2007-11-15 22:23:56 +0000173 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000174 timeout = self.gettimeout()
175 if timeout == 0.0:
176 # non-blocking
177 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000178 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000179
Bill Janssen6e027db2007-11-15 22:23:56 +0000180 except socket_error as x:
181 self.close()
182 raise x
183
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000184 def dup(self):
185 raise NotImplemented("Can't dup() %s instances" %
186 self.__class__.__name__)
187
Bill Janssen6e027db2007-11-15 22:23:56 +0000188 def _checkClosed(self, msg=None):
189 # raise an exception here if you wish to check for spurious closes
190 pass
191
Bill Janssen54cc54c2007-12-14 22:08:56 +0000192 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000193 """Read up to LEN bytes and return them.
194 Return zero-length string on EOF."""
195
Bill Janssen6e027db2007-11-15 22:23:56 +0000196 self._checkClosed()
197 try:
198 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000199 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000200 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000201 v = self._sslobj.read(len or 1024)
202 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000203 except SSLError as x:
204 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000205 if buffer:
206 return 0
207 else:
208 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000209 else:
210 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000211
212 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000213 """Write DATA to the underlying SSL channel. Returns
214 number of bytes of DATA actually transmitted."""
215
Bill Janssen6e027db2007-11-15 22:23:56 +0000216 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000217 return self._sslobj.write(data)
218
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000219 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000220 """Returns a formatted version of the data in the
221 certificate provided by the other end of the SSL channel.
222 Return None if no certificate was provided, {} if a
223 certificate was provided, but not validated."""
224
Bill Janssen6e027db2007-11-15 22:23:56 +0000225 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000226 return self._sslobj.peer_certificate(binary_form)
227
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000228 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000229 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000230 if not self._sslobj:
231 return None
232 else:
233 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000234
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000235 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000236 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000237 if self._sslobj:
238 if flags != 0:
239 raise ValueError(
240 "non-zero flags not allowed in calls to send() on %s" %
241 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000242 while True:
243 try:
244 v = self._sslobj.write(data)
245 except SSLError as x:
246 if x.args[0] == SSL_ERROR_WANT_READ:
247 return 0
248 elif x.args[0] == SSL_ERROR_WANT_WRITE:
249 return 0
250 else:
251 raise
252 else:
253 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000254 else:
255 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
Bill Janssen980f3142008-06-29 00:05:51 +0000257 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000258 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000259 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000260 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000261 self.__class__)
262 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000263 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000264
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000265 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000266 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000267 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000268 amount = len(data)
269 count = 0
270 while (count < amount):
271 v = self.send(data[count:])
272 count += v
273 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000274 else:
275 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000276
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000277 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000278 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000279 if self._sslobj:
280 if flags != 0:
281 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000282 "non-zero flags not allowed in calls to recv() on %s" %
283 self.__class__)
284 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000285 else:
286 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000287
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000288 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 self._checkClosed()
290 if buffer and (nbytes is None):
291 nbytes = len(buffer)
292 elif nbytes is None:
293 nbytes = 1024
294 if self._sslobj:
295 if flags != 0:
296 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000297 "non-zero flags not allowed in calls to recv_into() on %s" %
298 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000299 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000300 else:
301 return socket.recv_into(self, buffer, nbytes, flags)
302
Bill Janssen980f3142008-06-29 00:05:51 +0000303 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000304 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000305 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000306 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000307 self.__class__)
308 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000309 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000310
Bill Janssen58afe4c2008-09-08 16:45:19 +0000311 def recvfrom_into(self, buffer, nbytes=None, flags=0):
312 self._checkClosed()
313 if self._sslobj:
314 raise ValueError("recvfrom_into not allowed on instances of %s" %
315 self.__class__)
316 else:
317 return socket.recvfrom_into(self, buffer, nbytes, flags)
318
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000319 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000320 self._checkClosed()
321 if self._sslobj:
322 return self._sslobj.pending()
323 else:
324 return 0
325
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000326 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000327 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000328 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000329 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000330
Ezio Melottidc55e672010-01-18 09:15:14 +0000331 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000332 if self._sslobj:
333 s = self._sslobj.shutdown()
334 self._sslobj = None
335 return s
336 else:
337 raise ValueError("No SSL wrapper around " + str(self))
338
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000339 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000340 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000341 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000342 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000343
Bill Janssen48dc27c2007-12-05 03:38:10 +0000344 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 """Perform a TLS/SSL handshake."""
346
Bill Janssen48dc27c2007-12-05 03:38:10 +0000347 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000348 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000349 if timeout == 0.0 and block:
350 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000352 finally:
353 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000354
355 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000356 """Connects to remote ADDR, and then wraps the connection in
357 an SSL channel."""
358
Thomas Woutersed03b412007-08-28 21:37:11 +0000359 # Here we assume that the socket is client-side, and not
360 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000361 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000362 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000363 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000365 try:
366 if self.do_handshake_on_connect:
367 self.do_handshake()
368 except:
369 self._sslobj = None
370 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000371
372 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000373 """Accepts a new connection from a remote client, and returns
374 a tuple containing that new connection wrapped with a server-side
375 SSL channel, and the address of the remote client."""
376
377 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000378 return (SSLSocket(sock=newsock,
379 keyfile=self.keyfile, certfile=self.certfile,
380 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000381 cert_reqs=self.cert_reqs,
382 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000383 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000384 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000385 do_handshake_on_connect=
386 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000387 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000388
Guido van Rossume6650f92007-12-06 19:05:55 +0000389 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000390 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000391 self._real_close()
392
Bill Janssen54cc54c2007-12-14 22:08:56 +0000393
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394def wrap_socket(sock, keyfile=None, certfile=None,
395 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000396 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000397 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000398 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000402 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000403 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000404 suppress_ragged_eofs=suppress_ragged_eofs,
405 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406
Thomas Woutersed03b412007-08-28 21:37:11 +0000407# some utility functions
408
409def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000410 """Takes a date-time string in standard ASN1_print form
411 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
412 a Python time value in seconds past the epoch."""
413
Thomas Woutersed03b412007-08-28 21:37:11 +0000414 import time
415 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
416
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000417PEM_HEADER = "-----BEGIN CERTIFICATE-----"
418PEM_FOOTER = "-----END CERTIFICATE-----"
419
420def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421 """Takes a certificate in binary DER format and returns the
422 PEM version of it as a string."""
423
Bill Janssen6e027db2007-11-15 22:23:56 +0000424 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
425 return (PEM_HEADER + '\n' +
426 textwrap.fill(f, 64) + '\n' +
427 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428
429def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000430 """Takes a certificate in ASCII PEM format and returns the
431 DER-encoded version of it as a byte sequence"""
432
433 if not pem_cert_string.startswith(PEM_HEADER):
434 raise ValueError("Invalid PEM encoding; must start with %s"
435 % PEM_HEADER)
436 if not pem_cert_string.strip().endswith(PEM_FOOTER):
437 raise ValueError("Invalid PEM encoding; must end with %s"
438 % PEM_FOOTER)
439 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000440 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000442def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000443 """Retrieve the certificate from the server at the specified address,
444 and return it as a PEM-encoded string.
445 If 'ca_certs' is specified, validate the server cert against it.
446 If 'ssl_version' is specified, use it in the connection attempt."""
447
448 host, port = addr
449 if (ca_certs is not None):
450 cert_reqs = CERT_REQUIRED
451 else:
452 cert_reqs = CERT_NONE
453 s = wrap_socket(socket(), ssl_version=ssl_version,
454 cert_reqs=cert_reqs, ca_certs=ca_certs)
455 s.connect(addr)
456 dercert = s.getpeercert(True)
457 s.close()
458 return DER_cert_to_PEM_cert(dercert)
459
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000460def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461 if protocol_code == PROTOCOL_TLSv1:
462 return "TLSv1"
463 elif protocol_code == PROTOCOL_SSLv23:
464 return "SSLv23"
465 elif protocol_code == PROTOCOL_SSLv2:
466 return "SSLv2"
467 elif protocol_code == PROTOCOL_SSLv3:
468 return "SSLv3"
469 else:
470 return "<unknown>"