blob: 5e2da29e639b0405f15858108430b5c43d5c8eab [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
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
Antoine Pitroude8cf322010-04-26 17:29:05 +000085import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000086
Thomas Woutersed03b412007-08-28 21:37:11 +000087
Antoine Pitrou152efa22010-05-16 18:19:27 +000088class SSLContext(_SSLContext):
89 """An SSLContext holds various SSL-related configuration options and
90 data, such as certificates and possibly a private key."""
91
92 __slots__ = ('protocol',)
93
94 def __new__(cls, protocol, *args, **kwargs):
95 return _SSLContext.__new__(cls, protocol)
96
97 def __init__(self, protocol):
98 self.protocol = protocol
99
100 def wrap_socket(self, sock, server_side=False,
101 do_handshake_on_connect=True,
102 suppress_ragged_eofs=True):
103 return SSLSocket(sock=sock, server_side=server_side,
104 do_handshake_on_connect=do_handshake_on_connect,
105 suppress_ragged_eofs=suppress_ragged_eofs,
106 _context=self)
107
108
109class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000110 """This class implements a subtype of socket.socket that wraps
111 the underlying OS socket in an SSL context when necessary, and
112 provides read and write methods over that channel."""
113
Bill Janssen6e027db2007-11-15 22:23:56 +0000114 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000115 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000116 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
117 do_handshake_on_connect=True,
118 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000119 suppress_ragged_eofs=True, ciphers=None,
120 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000121
Antoine Pitrou152efa22010-05-16 18:19:27 +0000122 if _context:
123 self.context = _context
124 else:
125 if certfile and not keyfile:
126 keyfile = certfile
127 self.context = SSLContext(ssl_version)
128 self.context.verify_mode = cert_reqs
129 if ca_certs:
130 self.context.load_verify_locations(ca_certs)
131 if certfile:
132 self.context.load_cert_chain(certfile, keyfile)
133 if ciphers:
134 self.context.set_ciphers(ciphers)
135 self.keyfile = keyfile
136 self.certfile = certfile
137 self.cert_reqs = cert_reqs
138 self.ssl_version = ssl_version
139 self.ca_certs = ca_certs
140 self.ciphers = ciphers
141
142 self.do_handshake_on_connect = do_handshake_on_connect
143 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000144 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000145 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000146 socket.__init__(self,
147 family=sock.family,
148 type=sock.type,
149 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000150 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000151 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000152 # see if it's connected
153 try:
154 sock.getpeername()
155 except socket_error as e:
156 if e.errno != errno.ENOTCONN:
157 raise
158 else:
159 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000160 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000161 elif fileno is not None:
162 socket.__init__(self, fileno=fileno)
163 else:
164 socket.__init__(self, family=family, type=type, proto=proto)
165
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000166 self._closed = False
167 self._sslobj = None
168 if connected:
169 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000170 try:
Antoine Pitrou152efa22010-05-16 18:19:27 +0000171 self._sslobj = self.context._wrap_socket(self, server_side)
Bill Janssen6e027db2007-11-15 22:23:56 +0000172 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000173 timeout = self.gettimeout()
174 if timeout == 0.0:
175 # non-blocking
176 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000177 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000178
Bill Janssen6e027db2007-11-15 22:23:56 +0000179 except socket_error as x:
180 self.close()
181 raise x
182
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000183 def dup(self):
184 raise NotImplemented("Can't dup() %s instances" %
185 self.__class__.__name__)
186
Bill Janssen6e027db2007-11-15 22:23:56 +0000187 def _checkClosed(self, msg=None):
188 # raise an exception here if you wish to check for spurious closes
189 pass
190
Bill Janssen54cc54c2007-12-14 22:08:56 +0000191 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000192 """Read up to LEN bytes and return them.
193 Return zero-length string on EOF."""
194
Bill Janssen6e027db2007-11-15 22:23:56 +0000195 self._checkClosed()
196 try:
197 if buffer:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000198 v = self._sslobj.read(buffer, len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000199 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000200 v = self._sslobj.read(len or 1024)
201 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000202 except SSLError as x:
203 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000204 if buffer:
205 return 0
206 else:
207 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000208 else:
209 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000210
211 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000212 """Write DATA to the underlying SSL channel. Returns
213 number of bytes of DATA actually transmitted."""
214
Bill Janssen6e027db2007-11-15 22:23:56 +0000215 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000216 return self._sslobj.write(data)
217
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000218 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000219 """Returns a formatted version of the data in the
220 certificate provided by the other end of the SSL channel.
221 Return None if no certificate was provided, {} if a
222 certificate was provided, but not validated."""
223
Bill Janssen6e027db2007-11-15 22:23:56 +0000224 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000225 return self._sslobj.peer_certificate(binary_form)
226
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000227 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000228 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000229 if not self._sslobj:
230 return None
231 else:
232 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000233
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000234 def send(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:
237 if flags != 0:
238 raise ValueError(
239 "non-zero flags not allowed in calls to send() on %s" %
240 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000241 while True:
242 try:
243 v = self._sslobj.write(data)
244 except SSLError as x:
245 if x.args[0] == SSL_ERROR_WANT_READ:
246 return 0
247 elif x.args[0] == SSL_ERROR_WANT_WRITE:
248 return 0
249 else:
250 raise
251 else:
252 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000253 else:
254 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000255
Bill Janssen980f3142008-06-29 00:05:51 +0000256 def sendto(self, data, addr, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000257 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000258 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000259 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000260 self.__class__)
261 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000262 return socket.sendto(self, data, addr, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000263
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000264 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000265 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000266 if self._sslobj:
Bill Janssen6e027db2007-11-15 22:23:56 +0000267 amount = len(data)
268 count = 0
269 while (count < amount):
270 v = self.send(data[count:])
271 count += v
272 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000273 else:
274 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000275
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000276 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000277 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000278 if self._sslobj:
279 if flags != 0:
280 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000281 "non-zero flags not allowed in calls to recv() on %s" %
282 self.__class__)
283 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000284 else:
285 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000286
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000287 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 self._checkClosed()
289 if buffer and (nbytes is None):
290 nbytes = len(buffer)
291 elif nbytes is None:
292 nbytes = 1024
293 if self._sslobj:
294 if flags != 0:
295 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000296 "non-zero flags not allowed in calls to recv_into() on %s" %
297 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000298 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000299 else:
300 return socket.recv_into(self, buffer, nbytes, flags)
301
Bill Janssen980f3142008-06-29 00:05:51 +0000302 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000304 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000305 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000306 self.__class__)
307 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000308 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000309
Bill Janssen58afe4c2008-09-08 16:45:19 +0000310 def recvfrom_into(self, buffer, nbytes=None, flags=0):
311 self._checkClosed()
312 if self._sslobj:
313 raise ValueError("recvfrom_into not allowed on instances of %s" %
314 self.__class__)
315 else:
316 return socket.recvfrom_into(self, buffer, nbytes, flags)
317
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000318 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000319 self._checkClosed()
320 if self._sslobj:
321 return self._sslobj.pending()
322 else:
323 return 0
324
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000325 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000328 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000329
Ezio Melottidc55e672010-01-18 09:15:14 +0000330 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000331 if self._sslobj:
332 s = self._sslobj.shutdown()
333 self._sslobj = None
334 return s
335 else:
336 raise ValueError("No SSL wrapper around " + str(self))
337
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000338 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000340 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000341 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000342
Bill Janssen48dc27c2007-12-05 03:38:10 +0000343 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 """Perform a TLS/SSL handshake."""
345
Bill Janssen48dc27c2007-12-05 03:38:10 +0000346 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000347 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000348 if timeout == 0.0 and block:
349 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000350 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000351 finally:
352 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000353
354 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 """Connects to remote ADDR, and then wraps the connection in
356 an SSL channel."""
357
Thomas Woutersed03b412007-08-28 21:37:11 +0000358 # Here we assume that the socket is client-side, and not
359 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000360 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000361 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000362 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000363 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000364 try:
365 if self.do_handshake_on_connect:
366 self.do_handshake()
367 except:
368 self._sslobj = None
369 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000370
371 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000372 """Accepts a new connection from a remote client, and returns
373 a tuple containing that new connection wrapped with a server-side
374 SSL channel, and the address of the remote client."""
375
376 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000377 return (SSLSocket(sock=newsock,
378 keyfile=self.keyfile, certfile=self.certfile,
379 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000380 cert_reqs=self.cert_reqs,
381 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000382 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000383 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000384 do_handshake_on_connect=
385 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000386 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387
Guido van Rossume6650f92007-12-06 19:05:55 +0000388 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000389 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000390 self._real_close()
391
Bill Janssen54cc54c2007-12-14 22:08:56 +0000392
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393def wrap_socket(sock, keyfile=None, certfile=None,
394 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000395 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000396 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000397 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398
Bill Janssen6e027db2007-11-15 22:23:56 +0000399 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000401 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000402 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000403 suppress_ragged_eofs=suppress_ragged_eofs,
404 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405
Thomas Woutersed03b412007-08-28 21:37:11 +0000406# some utility functions
407
408def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000409 """Takes a date-time string in standard ASN1_print form
410 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
411 a Python time value in seconds past the epoch."""
412
Thomas Woutersed03b412007-08-28 21:37:11 +0000413 import time
414 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
415
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000416PEM_HEADER = "-----BEGIN CERTIFICATE-----"
417PEM_FOOTER = "-----END CERTIFICATE-----"
418
419def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000420 """Takes a certificate in binary DER format and returns the
421 PEM version of it as a string."""
422
Bill Janssen6e027db2007-11-15 22:23:56 +0000423 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
424 return (PEM_HEADER + '\n' +
425 textwrap.fill(f, 64) + '\n' +
426 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427
428def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000429 """Takes a certificate in ASCII PEM format and returns the
430 DER-encoded version of it as a byte sequence"""
431
432 if not pem_cert_string.startswith(PEM_HEADER):
433 raise ValueError("Invalid PEM encoding; must start with %s"
434 % PEM_HEADER)
435 if not pem_cert_string.strip().endswith(PEM_FOOTER):
436 raise ValueError("Invalid PEM encoding; must end with %s"
437 % PEM_FOOTER)
438 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000439 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000441def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000442 """Retrieve the certificate from the server at the specified address,
443 and return it as a PEM-encoded string.
444 If 'ca_certs' is specified, validate the server cert against it.
445 If 'ssl_version' is specified, use it in the connection attempt."""
446
447 host, port = addr
448 if (ca_certs is not None):
449 cert_reqs = CERT_REQUIRED
450 else:
451 cert_reqs = CERT_NONE
452 s = wrap_socket(socket(), ssl_version=ssl_version,
453 cert_reqs=cert_reqs, ca_certs=ca_certs)
454 s.connect(addr)
455 dercert = s.getpeercert(True)
456 s.close()
457 return DER_cert_to_PEM_cert(dercert)
458
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000459def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460 if protocol_code == PROTOCOL_TLSv1:
461 return "TLSv1"
462 elif protocol_code == PROTOCOL_SSLv23:
463 return "SSLv23"
464 elif protocol_code == PROTOCOL_SSLv2:
465 return "SSLv2"
466 elif protocol_code == PROTOCOL_SSLv3:
467 return "SSLv3"
468 else:
469 return "<unknown>"