blob: af1cc840a437f78e99da069049ad5523bec26e82 [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:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000267 if flags != 0:
268 raise ValueError(
269 "non-zero flags not allowed in calls to sendall() on %s" %
270 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000271 amount = len(data)
272 count = 0
273 while (count < amount):
274 v = self.send(data[count:])
275 count += v
276 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000277 else:
278 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000279
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000280 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000281 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000282 if self._sslobj:
283 if flags != 0:
284 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000285 "non-zero flags not allowed in calls to recv() on %s" %
286 self.__class__)
287 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000288 else:
289 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000290
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000291 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000292 self._checkClosed()
293 if buffer and (nbytes is None):
294 nbytes = len(buffer)
295 elif nbytes is None:
296 nbytes = 1024
297 if self._sslobj:
298 if flags != 0:
299 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000300 "non-zero flags not allowed in calls to recv_into() on %s" %
301 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000302 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 else:
304 return socket.recv_into(self, buffer, nbytes, flags)
305
Bill Janssen980f3142008-06-29 00:05:51 +0000306 def recvfrom(self, addr, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000307 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000308 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000309 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000310 self.__class__)
311 else:
Bill Janssen980f3142008-06-29 00:05:51 +0000312 return socket.recvfrom(self, addr, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000313
Bill Janssen58afe4c2008-09-08 16:45:19 +0000314 def recvfrom_into(self, buffer, nbytes=None, flags=0):
315 self._checkClosed()
316 if self._sslobj:
317 raise ValueError("recvfrom_into not allowed on instances of %s" %
318 self.__class__)
319 else:
320 return socket.recvfrom_into(self, buffer, nbytes, flags)
321
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000322 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000323 self._checkClosed()
324 if self._sslobj:
325 return self._sslobj.pending()
326 else:
327 return 0
328
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000329 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000332 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000333
Ezio Melottidc55e672010-01-18 09:15:14 +0000334 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000335 if self._sslobj:
336 s = self._sslobj.shutdown()
337 self._sslobj = None
338 return s
339 else:
340 raise ValueError("No SSL wrapper around " + str(self))
341
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000342 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000345 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000346
Bill Janssen48dc27c2007-12-05 03:38:10 +0000347 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000348 """Perform a TLS/SSL handshake."""
349
Bill Janssen48dc27c2007-12-05 03:38:10 +0000350 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000352 if timeout == 0.0 and block:
353 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000354 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000355 finally:
356 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
358 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000359 """Connects to remote ADDR, and then wraps the connection in
360 an SSL channel."""
361
Thomas Woutersed03b412007-08-28 21:37:11 +0000362 # Here we assume that the socket is client-side, and not
363 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000364 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000366 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000367 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000368 try:
369 if self.do_handshake_on_connect:
370 self.do_handshake()
371 except:
372 self._sslobj = None
373 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
375 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376 """Accepts a new connection from a remote client, and returns
377 a tuple containing that new connection wrapped with a server-side
378 SSL channel, and the address of the remote client."""
379
380 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000381 return (SSLSocket(sock=newsock,
382 keyfile=self.keyfile, certfile=self.certfile,
383 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000384 cert_reqs=self.cert_reqs,
385 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000386 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000387 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000388 do_handshake_on_connect=
389 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000390 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000391
Guido van Rossume6650f92007-12-06 19:05:55 +0000392 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000393 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000394 self._real_close()
395
Bill Janssen54cc54c2007-12-14 22:08:56 +0000396
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000397def wrap_socket(sock, keyfile=None, certfile=None,
398 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000399 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000400 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000401 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000402
Bill Janssen6e027db2007-11-15 22:23:56 +0000403 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000405 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000406 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000407 suppress_ragged_eofs=suppress_ragged_eofs,
408 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409
Thomas Woutersed03b412007-08-28 21:37:11 +0000410# some utility functions
411
412def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000413 """Takes a date-time string in standard ASN1_print form
414 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
415 a Python time value in seconds past the epoch."""
416
Thomas Woutersed03b412007-08-28 21:37:11 +0000417 import time
418 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
419
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000420PEM_HEADER = "-----BEGIN CERTIFICATE-----"
421PEM_FOOTER = "-----END CERTIFICATE-----"
422
423def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000424 """Takes a certificate in binary DER format and returns the
425 PEM version of it as a string."""
426
Bill Janssen6e027db2007-11-15 22:23:56 +0000427 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
428 return (PEM_HEADER + '\n' +
429 textwrap.fill(f, 64) + '\n' +
430 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431
432def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433 """Takes a certificate in ASCII PEM format and returns the
434 DER-encoded version of it as a byte sequence"""
435
436 if not pem_cert_string.startswith(PEM_HEADER):
437 raise ValueError("Invalid PEM encoding; must start with %s"
438 % PEM_HEADER)
439 if not pem_cert_string.strip().endswith(PEM_FOOTER):
440 raise ValueError("Invalid PEM encoding; must end with %s"
441 % PEM_FOOTER)
442 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000443 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000445def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000446 """Retrieve the certificate from the server at the specified address,
447 and return it as a PEM-encoded string.
448 If 'ca_certs' is specified, validate the server cert against it.
449 If 'ssl_version' is specified, use it in the connection attempt."""
450
451 host, port = addr
452 if (ca_certs is not None):
453 cert_reqs = CERT_REQUIRED
454 else:
455 cert_reqs = CERT_NONE
456 s = wrap_socket(socket(), ssl_version=ssl_version,
457 cert_reqs=cert_reqs, ca_certs=ca_certs)
458 s.connect(addr)
459 dercert = s.getpeercert(True)
460 s.close()
461 return DER_cert_to_PEM_cert(dercert)
462
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000463def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464 if protocol_code == PROTOCOL_TLSv1:
465 return "TLSv1"
466 elif protocol_code == PROTOCOL_SSLv23:
467 return "SSLv23"
468 elif protocol_code == PROTOCOL_SSLv2:
469 return "SSLv2"
470 elif protocol_code == PROTOCOL_SSLv3:
471 return "SSLv3"
472 else:
473 return "<unknown>"