blob: e7c175f063a68ede5ba269ce4e190fba356f1925 [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
Antoine Pitrou59fdd672010-10-08 10:37:08 +000058import re
Thomas Woutersed03b412007-08-28 21:37:11 +000059
60import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061
Antoine Pitrou04f6a322010-04-05 21:40:07 +000062from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou152efa22010-05-16 18:19:27 +000063from _ssl import _SSLContext, SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000064from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Guido van Rossum5b8b1552007-11-16 00:06:11 +000065from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23,
66 PROTOCOL_TLSv1)
Antoine Pitroub5218772010-05-21 09:56:06 +000067from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000068from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000069from _ssl import (
70 SSL_ERROR_ZERO_RETURN,
71 SSL_ERROR_WANT_READ,
72 SSL_ERROR_WANT_WRITE,
73 SSL_ERROR_WANT_X509_LOOKUP,
74 SSL_ERROR_SYSCALL,
75 SSL_ERROR_SSL,
76 SSL_ERROR_WANT_CONNECT,
77 SSL_ERROR_EOF,
78 SSL_ERROR_INVALID_ERROR_CODE,
79 )
Antoine Pitroud5323212010-10-22 18:19:07 +000080from _ssl import HAS_SNI
Thomas Woutersed03b412007-08-28 21:37:11 +000081
Thomas Wouters47b49bf2007-08-30 22:15:33 +000082from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000083from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000084from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000085import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000086import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000087import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000088
Thomas Woutersed03b412007-08-28 21:37:11 +000089
Antoine Pitrou59fdd672010-10-08 10:37:08 +000090class CertificateError(ValueError):
91 pass
92
93
94def _dnsname_to_pat(dn):
95 pats = []
96 for frag in dn.split(r'.'):
97 if frag == '*':
98 # When '*' is a fragment by itself, it matches a non-empty dotless
99 # fragment.
100 pats.append('[^.]+')
101 else:
102 # Otherwise, '*' matches any dotless fragment.
103 frag = re.escape(frag)
104 pats.append(frag.replace(r'\*', '[^.]*'))
105 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
106
107
108def match_hostname(cert, hostname):
109 """Verify that *cert* (in decoded format as returned by
110 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
111 are mostly followed, but IP addresses are not accepted for *hostname*.
112
113 CertificateError is raised on failure. On success, the function
114 returns nothing.
115 """
116 if not cert:
117 raise ValueError("empty or no certificate")
118 dnsnames = []
119 san = cert.get('subjectAltName', ())
120 for key, value in san:
121 if key == 'DNS':
122 if _dnsname_to_pat(value).match(hostname):
123 return
124 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200125 if not dnsnames:
126 # The subject is only checked when there is no dNSName entry
127 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000128 for sub in cert.get('subject', ()):
129 for key, value in sub:
130 # XXX according to RFC 2818, the most specific Common Name
131 # must be used.
132 if key == 'commonName':
133 if _dnsname_to_pat(value).match(hostname):
134 return
135 dnsnames.append(value)
136 if len(dnsnames) > 1:
137 raise CertificateError("hostname %r "
138 "doesn't match either of %s"
139 % (hostname, ', '.join(map(repr, dnsnames))))
140 elif len(dnsnames) == 1:
141 raise CertificateError("hostname %r "
142 "doesn't match %r"
143 % (hostname, dnsnames[0]))
144 else:
145 raise CertificateError("no appropriate commonName or "
146 "subjectAltName fields were found")
147
148
Antoine Pitrou152efa22010-05-16 18:19:27 +0000149class SSLContext(_SSLContext):
150 """An SSLContext holds various SSL-related configuration options and
151 data, such as certificates and possibly a private key."""
152
153 __slots__ = ('protocol',)
154
155 def __new__(cls, protocol, *args, **kwargs):
156 return _SSLContext.__new__(cls, protocol)
157
158 def __init__(self, protocol):
159 self.protocol = protocol
160
161 def wrap_socket(self, sock, server_side=False,
162 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000163 suppress_ragged_eofs=True,
164 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000165 return SSLSocket(sock=sock, server_side=server_side,
166 do_handshake_on_connect=do_handshake_on_connect,
167 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000168 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000169 _context=self)
170
171
172class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000173 """This class implements a subtype of socket.socket that wraps
174 the underlying OS socket in an SSL context when necessary, and
175 provides read and write methods over that channel."""
176
Bill Janssen6e027db2007-11-15 22:23:56 +0000177 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000178 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000179 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
180 do_handshake_on_connect=True,
181 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000182 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000183 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000184 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000185
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186 if _context:
187 self.context = _context
188 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000189 if server_side and not certfile:
190 raise ValueError("certfile must be specified for server-side "
191 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000192 if keyfile and not certfile:
193 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194 if certfile and not keyfile:
195 keyfile = certfile
196 self.context = SSLContext(ssl_version)
197 self.context.verify_mode = cert_reqs
198 if ca_certs:
199 self.context.load_verify_locations(ca_certs)
200 if certfile:
201 self.context.load_cert_chain(certfile, keyfile)
202 if ciphers:
203 self.context.set_ciphers(ciphers)
204 self.keyfile = keyfile
205 self.certfile = certfile
206 self.cert_reqs = cert_reqs
207 self.ssl_version = ssl_version
208 self.ca_certs = ca_certs
209 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000210 if server_side and server_hostname:
211 raise ValueError("server_hostname can only be specified "
212 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000213 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000214 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000215 self.do_handshake_on_connect = do_handshake_on_connect
216 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000217 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000218 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000219 socket.__init__(self,
220 family=sock.family,
221 type=sock.type,
222 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000223 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000224 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000225 # see if it's connected
226 try:
227 sock.getpeername()
228 except socket_error as e:
229 if e.errno != errno.ENOTCONN:
230 raise
231 else:
232 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000233 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000234 elif fileno is not None:
235 socket.__init__(self, fileno=fileno)
236 else:
237 socket.__init__(self, family=family, type=type, proto=proto)
238
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000239 self._closed = False
240 self._sslobj = None
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000241 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000242 if connected:
243 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000244 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000245 self._sslobj = self.context._wrap_socket(self, server_side,
246 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000247 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000248 timeout = self.gettimeout()
249 if timeout == 0.0:
250 # non-blocking
251 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000252 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000253
Bill Janssen6e027db2007-11-15 22:23:56 +0000254 except socket_error as x:
255 self.close()
256 raise x
257
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000258 def dup(self):
259 raise NotImplemented("Can't dup() %s instances" %
260 self.__class__.__name__)
261
Bill Janssen6e027db2007-11-15 22:23:56 +0000262 def _checkClosed(self, msg=None):
263 # raise an exception here if you wish to check for spurious closes
264 pass
265
Bill Janssen54cc54c2007-12-14 22:08:56 +0000266 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000267 """Read up to LEN bytes and return them.
268 Return zero-length string on EOF."""
269
Bill Janssen6e027db2007-11-15 22:23:56 +0000270 self._checkClosed()
271 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000272 if buffer is not None:
273 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000275 v = self._sslobj.read(len or 1024)
276 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000277 except SSLError as x:
278 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000279 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000280 return 0
281 else:
282 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000283 else:
284 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000285
286 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000287 """Write DATA to the underlying SSL channel. Returns
288 number of bytes of DATA actually transmitted."""
289
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000291 return self._sslobj.write(data)
292
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000293 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000294 """Returns a formatted version of the data in the
295 certificate provided by the other end of the SSL channel.
296 Return None if no certificate was provided, {} if a
297 certificate was provided, but not validated."""
298
Bill Janssen6e027db2007-11-15 22:23:56 +0000299 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000300 return self._sslobj.peer_certificate(binary_form)
301
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000302 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304 if not self._sslobj:
305 return None
306 else:
307 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000308
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000309 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000311 if self._sslobj:
312 if flags != 0:
313 raise ValueError(
314 "non-zero flags not allowed in calls to send() on %s" %
315 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000316 while True:
317 try:
318 v = self._sslobj.write(data)
319 except SSLError as x:
320 if x.args[0] == SSL_ERROR_WANT_READ:
321 return 0
322 elif x.args[0] == SSL_ERROR_WANT_WRITE:
323 return 0
324 else:
325 raise
326 else:
327 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000328 else:
329 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000330
Antoine Pitroua468adc2010-09-14 14:43:44 +0000331 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000332 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000333 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000334 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000335 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000336 elif addr is None:
337 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000338 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000339 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000340
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000341 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000342 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000344 if flags != 0:
345 raise ValueError(
346 "non-zero flags not allowed in calls to sendall() on %s" %
347 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000348 amount = len(data)
349 count = 0
350 while (count < amount):
351 v = self.send(data[count:])
352 count += v
353 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000354 else:
355 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000356
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000357 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000359 if self._sslobj:
360 if flags != 0:
361 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000362 "non-zero flags not allowed in calls to recv() on %s" %
363 self.__class__)
364 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000365 else:
366 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000368 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 self._checkClosed()
370 if buffer and (nbytes is None):
371 nbytes = len(buffer)
372 elif nbytes is None:
373 nbytes = 1024
374 if self._sslobj:
375 if flags != 0:
376 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000377 "non-zero flags not allowed in calls to recv_into() on %s" %
378 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000379 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000380 else:
381 return socket.recv_into(self, buffer, nbytes, flags)
382
Antoine Pitroua468adc2010-09-14 14:43:44 +0000383 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000384 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000385 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000386 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000387 self.__class__)
388 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000389 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000390
Bill Janssen58afe4c2008-09-08 16:45:19 +0000391 def recvfrom_into(self, buffer, nbytes=None, flags=0):
392 self._checkClosed()
393 if self._sslobj:
394 raise ValueError("recvfrom_into not allowed on instances of %s" %
395 self.__class__)
396 else:
397 return socket.recvfrom_into(self, buffer, nbytes, flags)
398
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000399 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 self._checkClosed()
401 if self._sslobj:
402 return self._sslobj.pending()
403 else:
404 return 0
405
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000406 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000407 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000409 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000410
Ezio Melottidc55e672010-01-18 09:15:14 +0000411 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000412 if self._sslobj:
413 s = self._sslobj.shutdown()
414 self._sslobj = None
415 return s
416 else:
417 raise ValueError("No SSL wrapper around " + str(self))
418
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000419 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000420 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000421 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000422 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000423
Bill Janssen48dc27c2007-12-05 03:38:10 +0000424 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000425 """Perform a TLS/SSL handshake."""
426
Bill Janssen48dc27c2007-12-05 03:38:10 +0000427 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000428 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000429 if timeout == 0.0 and block:
430 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000431 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000432 finally:
433 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000434
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000435 def _real_connect(self, addr, return_errno):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000436 if self.server_side:
437 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000438 # Here we assume that the socket is client-side, and not
439 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000440 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000442 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000443 try:
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000444 socket.connect(self, addr)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000445 if self.do_handshake_on_connect:
446 self.do_handshake()
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000447 except socket_error as e:
448 if return_errno:
449 return e.errno
450 else:
451 self._sslobj = None
452 raise e
453 self._connected = True
454 return 0
455
456 def connect(self, addr):
457 """Connects to remote ADDR, and then wraps the connection in
458 an SSL channel."""
459 self._real_connect(addr, False)
460
461 def connect_ex(self, addr):
462 """Connects to remote ADDR, and then wraps the connection in
463 an SSL channel."""
464 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000465
466 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000467 """Accepts a new connection from a remote client, and returns
468 a tuple containing that new connection wrapped with a server-side
469 SSL channel, and the address of the remote client."""
470
471 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000472 return (SSLSocket(sock=newsock,
473 keyfile=self.keyfile, certfile=self.certfile,
474 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000475 cert_reqs=self.cert_reqs,
476 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000477 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000478 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000479 do_handshake_on_connect=
480 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000481 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000482
Guido van Rossume6650f92007-12-06 19:05:55 +0000483 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000484 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000485 self._real_close()
486
Bill Janssen54cc54c2007-12-14 22:08:56 +0000487
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488def wrap_socket(sock, keyfile=None, certfile=None,
489 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000490 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000491 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000492 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Bill Janssen6e027db2007-11-15 22:23:56 +0000494 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000496 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000497 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000498 suppress_ragged_eofs=suppress_ragged_eofs,
499 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500
Thomas Woutersed03b412007-08-28 21:37:11 +0000501# some utility functions
502
503def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000504 """Takes a date-time string in standard ASN1_print form
505 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
506 a Python time value in seconds past the epoch."""
507
Thomas Woutersed03b412007-08-28 21:37:11 +0000508 import time
509 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
510
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000511PEM_HEADER = "-----BEGIN CERTIFICATE-----"
512PEM_FOOTER = "-----END CERTIFICATE-----"
513
514def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515 """Takes a certificate in binary DER format and returns the
516 PEM version of it as a string."""
517
Bill Janssen6e027db2007-11-15 22:23:56 +0000518 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
519 return (PEM_HEADER + '\n' +
520 textwrap.fill(f, 64) + '\n' +
521 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
523def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524 """Takes a certificate in ASCII PEM format and returns the
525 DER-encoded version of it as a byte sequence"""
526
527 if not pem_cert_string.startswith(PEM_HEADER):
528 raise ValueError("Invalid PEM encoding; must start with %s"
529 % PEM_HEADER)
530 if not pem_cert_string.strip().endswith(PEM_FOOTER):
531 raise ValueError("Invalid PEM encoding; must end with %s"
532 % PEM_FOOTER)
533 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000534 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000536def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 """Retrieve the certificate from the server at the specified address,
538 and return it as a PEM-encoded string.
539 If 'ca_certs' is specified, validate the server cert against it.
540 If 'ssl_version' is specified, use it in the connection attempt."""
541
542 host, port = addr
543 if (ca_certs is not None):
544 cert_reqs = CERT_REQUIRED
545 else:
546 cert_reqs = CERT_NONE
547 s = wrap_socket(socket(), ssl_version=ssl_version,
548 cert_reqs=cert_reqs, ca_certs=ca_certs)
549 s.connect(addr)
550 dercert = s.getpeercert(True)
551 s.close()
552 return DER_cert_to_PEM_cert(dercert)
553
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000554def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555 if protocol_code == PROTOCOL_TLSv1:
556 return "TLSv1"
557 elif protocol_code == PROTOCOL_SSLv23:
558 return "SSLv23"
559 elif protocol_code == PROTOCOL_SSLv2:
560 return "SSLv2"
561 elif protocol_code == PROTOCOL_SSLv3:
562 return "SSLv3"
563 else:
564 return "<unknown>"