blob: 90c21ceff78009196b0830c89531cf3d78cbdab9 [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
Antoine Pitroub5218772010-05-21 09:56:06 +000065from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000066from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000067from _ssl import (
68 SSL_ERROR_ZERO_RETURN,
69 SSL_ERROR_WANT_READ,
70 SSL_ERROR_WANT_WRITE,
71 SSL_ERROR_WANT_X509_LOOKUP,
72 SSL_ERROR_SYSCALL,
73 SSL_ERROR_SSL,
74 SSL_ERROR_WANT_CONNECT,
75 SSL_ERROR_EOF,
76 SSL_ERROR_INVALID_ERROR_CODE,
77 )
Antoine Pitroud5323212010-10-22 18:19:07 +000078from _ssl import HAS_SNI
Victor Stinneree18b6f2011-05-10 00:38:00 +020079from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020080from _ssl import _OPENSSL_API_VERSION
81
Victor Stinneree18b6f2011-05-10 00:38:00 +020082_PROTOCOL_NAMES = {
83 PROTOCOL_TLSv1: "TLSv1",
84 PROTOCOL_SSLv23: "SSLv23",
85 PROTOCOL_SSLv3: "SSLv3",
86}
87try:
88 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +010089 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Victor Stinneree18b6f2011-05-10 00:38:00 +020090except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +010091 _SSLv2_IF_EXISTS = None
Victor Stinneree18b6f2011-05-10 00:38:00 +020092else:
93 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000094
Thomas Wouters47b49bf2007-08-30 22:15:33 +000095from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000096from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000097from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000099import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000100import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000101
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100102# Disable weak or insecure ciphers by default
103# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
104_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
105
Thomas Woutersed03b412007-08-28 21:37:11 +0000106
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000107class CertificateError(ValueError):
108 pass
109
110
Antoine Pitrou86d53ca2013-05-18 17:56:42 +0200111def _dnsname_to_pat(dn, max_wildcards=1):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000112 pats = []
113 for frag in dn.split(r'.'):
Antoine Pitrou86d53ca2013-05-18 17:56:42 +0200114 if frag.count('*') > max_wildcards:
115 # Issue #17980: avoid denials of service by refusing more
116 # than one wildcard per fragment. A survery of established
117 # policy among SSL implementations showed it to be a
118 # reasonable choice.
119 raise CertificateError(
120 "too many wildcards in certificate DNS name: " + repr(dn))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000121 if frag == '*':
122 # When '*' is a fragment by itself, it matches a non-empty dotless
123 # fragment.
124 pats.append('[^.]+')
125 else:
126 # Otherwise, '*' matches any dotless fragment.
127 frag = re.escape(frag)
128 pats.append(frag.replace(r'\*', '[^.]*'))
129 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
130
131
132def match_hostname(cert, hostname):
133 """Verify that *cert* (in decoded format as returned by
134 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
135 are mostly followed, but IP addresses are not accepted for *hostname*.
136
137 CertificateError is raised on failure. On success, the function
138 returns nothing.
139 """
140 if not cert:
141 raise ValueError("empty or no certificate")
142 dnsnames = []
143 san = cert.get('subjectAltName', ())
144 for key, value in san:
145 if key == 'DNS':
146 if _dnsname_to_pat(value).match(hostname):
147 return
148 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200149 if not dnsnames:
150 # The subject is only checked when there is no dNSName entry
151 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000152 for sub in cert.get('subject', ()):
153 for key, value in sub:
154 # XXX according to RFC 2818, the most specific Common Name
155 # must be used.
156 if key == 'commonName':
157 if _dnsname_to_pat(value).match(hostname):
158 return
159 dnsnames.append(value)
160 if len(dnsnames) > 1:
161 raise CertificateError("hostname %r "
162 "doesn't match either of %s"
163 % (hostname, ', '.join(map(repr, dnsnames))))
164 elif len(dnsnames) == 1:
165 raise CertificateError("hostname %r "
166 "doesn't match %r"
167 % (hostname, dnsnames[0]))
168 else:
169 raise CertificateError("no appropriate commonName or "
170 "subjectAltName fields were found")
171
172
Antoine Pitrou152efa22010-05-16 18:19:27 +0000173class SSLContext(_SSLContext):
174 """An SSLContext holds various SSL-related configuration options and
175 data, such as certificates and possibly a private key."""
176
177 __slots__ = ('protocol',)
178
179 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100180 self = _SSLContext.__new__(cls, protocol)
181 if protocol != _SSLv2_IF_EXISTS:
182 self.set_ciphers(_DEFAULT_CIPHERS)
183 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000184
185 def __init__(self, protocol):
186 self.protocol = protocol
187
188 def wrap_socket(self, sock, server_side=False,
189 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000190 suppress_ragged_eofs=True,
191 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000192 return SSLSocket(sock=sock, server_side=server_side,
193 do_handshake_on_connect=do_handshake_on_connect,
194 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000195 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000196 _context=self)
197
198
199class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000200 """This class implements a subtype of socket.socket that wraps
201 the underlying OS socket in an SSL context when necessary, and
202 provides read and write methods over that channel."""
203
Bill Janssen6e027db2007-11-15 22:23:56 +0000204 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000205 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000206 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
207 do_handshake_on_connect=True,
208 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000210 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000212
Antoine Pitrou152efa22010-05-16 18:19:27 +0000213 if _context:
214 self.context = _context
215 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000216 if server_side and not certfile:
217 raise ValueError("certfile must be specified for server-side "
218 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000219 if keyfile and not certfile:
220 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000221 if certfile and not keyfile:
222 keyfile = certfile
223 self.context = SSLContext(ssl_version)
224 self.context.verify_mode = cert_reqs
225 if ca_certs:
226 self.context.load_verify_locations(ca_certs)
227 if certfile:
228 self.context.load_cert_chain(certfile, keyfile)
229 if ciphers:
230 self.context.set_ciphers(ciphers)
231 self.keyfile = keyfile
232 self.certfile = certfile
233 self.cert_reqs = cert_reqs
234 self.ssl_version = ssl_version
235 self.ca_certs = ca_certs
236 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000237 if server_side and server_hostname:
238 raise ValueError("server_hostname can only be specified "
239 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000240 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000241 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000242 self.do_handshake_on_connect = do_handshake_on_connect
243 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000244 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000245 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000246 socket.__init__(self,
247 family=sock.family,
248 type=sock.type,
249 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000250 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000251 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000252 # see if it's connected
253 try:
254 sock.getpeername()
255 except socket_error as e:
256 if e.errno != errno.ENOTCONN:
257 raise
258 else:
259 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000260 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000261 elif fileno is not None:
262 socket.__init__(self, fileno=fileno)
263 else:
264 socket.__init__(self, family=family, type=type, proto=proto)
265
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000266 self._closed = False
267 self._sslobj = None
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000268 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000269 if connected:
270 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000271 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000272 self._sslobj = self.context._wrap_socket(self, server_side,
273 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000275 timeout = self.gettimeout()
276 if timeout == 0.0:
277 # non-blocking
278 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000279 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000280
Bill Janssen6e027db2007-11-15 22:23:56 +0000281 except socket_error as x:
282 self.close()
283 raise x
284
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000285 def dup(self):
286 raise NotImplemented("Can't dup() %s instances" %
287 self.__class__.__name__)
288
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 def _checkClosed(self, msg=None):
290 # raise an exception here if you wish to check for spurious closes
291 pass
292
Bill Janssen54cc54c2007-12-14 22:08:56 +0000293 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000294 """Read up to LEN bytes and return them.
295 Return zero-length string on EOF."""
296
Bill Janssen6e027db2007-11-15 22:23:56 +0000297 self._checkClosed()
298 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000299 if buffer is not None:
300 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000301 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000302 v = self._sslobj.read(len or 1024)
303 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000304 except SSLError as x:
305 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000306 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000307 return 0
308 else:
309 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000310 else:
311 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000312
313 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000314 """Write DATA to the underlying SSL channel. Returns
315 number of bytes of DATA actually transmitted."""
316
Bill Janssen6e027db2007-11-15 22:23:56 +0000317 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000318 return self._sslobj.write(data)
319
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000320 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000321 """Returns a formatted version of the data in the
322 certificate provided by the other end of the SSL channel.
323 Return None if no certificate was provided, {} if a
324 certificate was provided, but not validated."""
325
Bill Janssen6e027db2007-11-15 22:23:56 +0000326 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327 return self._sslobj.peer_certificate(binary_form)
328
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000329 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 if not self._sslobj:
332 return None
333 else:
334 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000335
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000336 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000338 if self._sslobj:
339 if flags != 0:
340 raise ValueError(
341 "non-zero flags not allowed in calls to send() on %s" %
342 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000343 while True:
344 try:
345 v = self._sslobj.write(data)
346 except SSLError as x:
347 if x.args[0] == SSL_ERROR_WANT_READ:
348 return 0
349 elif x.args[0] == SSL_ERROR_WANT_WRITE:
350 return 0
351 else:
352 raise
353 else:
354 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 else:
356 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
Antoine Pitroua468adc2010-09-14 14:43:44 +0000358 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000359 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000360 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000361 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000362 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000363 elif addr is None:
364 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000365 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000366 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000368 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000370 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000371 if flags != 0:
372 raise ValueError(
373 "non-zero flags not allowed in calls to sendall() on %s" %
374 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000375 amount = len(data)
376 count = 0
377 while (count < amount):
378 v = self.send(data[count:])
379 count += v
380 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000381 else:
382 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000383
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000384 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000385 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000386 if self._sslobj:
387 if flags != 0:
388 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000389 "non-zero flags not allowed in calls to recv() on %s" %
390 self.__class__)
391 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000392 else:
393 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000395 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000396 self._checkClosed()
397 if buffer and (nbytes is None):
398 nbytes = len(buffer)
399 elif nbytes is None:
400 nbytes = 1024
401 if self._sslobj:
402 if flags != 0:
403 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000404 "non-zero flags not allowed in calls to recv_into() on %s" %
405 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000406 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000407 else:
408 return socket.recv_into(self, buffer, nbytes, flags)
409
Antoine Pitroua468adc2010-09-14 14:43:44 +0000410 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000411 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000412 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000413 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000414 self.__class__)
415 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000416 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000417
Bill Janssen58afe4c2008-09-08 16:45:19 +0000418 def recvfrom_into(self, buffer, nbytes=None, flags=0):
419 self._checkClosed()
420 if self._sslobj:
421 raise ValueError("recvfrom_into not allowed on instances of %s" %
422 self.__class__)
423 else:
424 return socket.recvfrom_into(self, buffer, nbytes, flags)
425
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000426 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000427 self._checkClosed()
428 if self._sslobj:
429 return self._sslobj.pending()
430 else:
431 return 0
432
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000433 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000434 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000436 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000437
Ezio Melottidc55e672010-01-18 09:15:14 +0000438 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000439 if self._sslobj:
440 s = self._sslobj.shutdown()
441 self._sslobj = None
442 return s
443 else:
444 raise ValueError("No SSL wrapper around " + str(self))
445
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000446 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000447 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000448 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000449 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000450
Bill Janssen48dc27c2007-12-05 03:38:10 +0000451 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000452 """Perform a TLS/SSL handshake."""
453
Bill Janssen48dc27c2007-12-05 03:38:10 +0000454 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000455 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000456 if timeout == 0.0 and block:
457 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000458 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000459 finally:
460 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000461
Antoine Pitroub4410db2011-05-18 18:51:06 +0200462 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000463 if self.server_side:
464 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000465 # Here we assume that the socket is client-side, and not
466 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000467 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000469 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000470 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200471 if connect_ex:
472 rc = socket.connect_ex(self, addr)
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000473 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200474 rc = None
475 socket.connect(self, addr)
476 if not rc:
477 if self.do_handshake_on_connect:
478 self.do_handshake()
479 self._connected = True
480 return rc
481 except socket_error:
482 self._sslobj = None
483 raise
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000484
485 def connect(self, addr):
486 """Connects to remote ADDR, and then wraps the connection in
487 an SSL channel."""
488 self._real_connect(addr, False)
489
490 def connect_ex(self, addr):
491 """Connects to remote ADDR, and then wraps the connection in
492 an SSL channel."""
493 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000494
495 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000496 """Accepts a new connection from a remote client, and returns
497 a tuple containing that new connection wrapped with a server-side
498 SSL channel, and the address of the remote client."""
499
500 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100501 newsock = self.context.wrap_socket(newsock,
502 do_handshake_on_connect=self.do_handshake_on_connect,
503 suppress_ragged_eofs=self.suppress_ragged_eofs,
504 server_side=True)
505 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Guido van Rossume6650f92007-12-06 19:05:55 +0000507 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000508 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000509 self._real_close()
510
Bill Janssen54cc54c2007-12-14 22:08:56 +0000511
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512def wrap_socket(sock, keyfile=None, certfile=None,
513 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000514 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000515 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000516 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
Bill Janssen6e027db2007-11-15 22:23:56 +0000518 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000520 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000521 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000522 suppress_ragged_eofs=suppress_ragged_eofs,
523 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524
Thomas Woutersed03b412007-08-28 21:37:11 +0000525# some utility functions
526
527def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000528 """Takes a date-time string in standard ASN1_print form
529 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
530 a Python time value in seconds past the epoch."""
531
Thomas Woutersed03b412007-08-28 21:37:11 +0000532 import time
533 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
534
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535PEM_HEADER = "-----BEGIN CERTIFICATE-----"
536PEM_FOOTER = "-----END CERTIFICATE-----"
537
538def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539 """Takes a certificate in binary DER format and returns the
540 PEM version of it as a string."""
541
Bill Janssen6e027db2007-11-15 22:23:56 +0000542 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
543 return (PEM_HEADER + '\n' +
544 textwrap.fill(f, 64) + '\n' +
545 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
547def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548 """Takes a certificate in ASCII PEM format and returns the
549 DER-encoded version of it as a byte sequence"""
550
551 if not pem_cert_string.startswith(PEM_HEADER):
552 raise ValueError("Invalid PEM encoding; must start with %s"
553 % PEM_HEADER)
554 if not pem_cert_string.strip().endswith(PEM_FOOTER):
555 raise ValueError("Invalid PEM encoding; must end with %s"
556 % PEM_FOOTER)
557 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000558 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000560def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561 """Retrieve the certificate from the server at the specified address,
562 and return it as a PEM-encoded string.
563 If 'ca_certs' is specified, validate the server cert against it.
564 If 'ssl_version' is specified, use it in the connection attempt."""
565
566 host, port = addr
567 if (ca_certs is not None):
568 cert_reqs = CERT_REQUIRED
569 else:
570 cert_reqs = CERT_NONE
571 s = wrap_socket(socket(), ssl_version=ssl_version,
572 cert_reqs=cert_reqs, ca_certs=ca_certs)
573 s.connect(addr)
574 dercert = s.getpeercert(True)
575 s.close()
576 return DER_cert_to_PEM_cert(dercert)
577
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000578def get_protocol_name(protocol_code):
Victor Stinneree18b6f2011-05-10 00:38:00 +0200579 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')