blob: ce9ebdf30ae6fa9e51ff8331890dedbd49f8fadf [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
89except ImportError:
90 pass
91else:
92 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000093
Thomas Wouters47b49bf2007-08-30 22:15:33 +000094from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000095from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000096from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000097import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000098import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000099import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000100
Thomas Woutersed03b412007-08-28 21:37:11 +0000101
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000102class CertificateError(ValueError):
103 pass
104
105
106def _dnsname_to_pat(dn):
107 pats = []
108 for frag in dn.split(r'.'):
109 if frag == '*':
110 # When '*' is a fragment by itself, it matches a non-empty dotless
111 # fragment.
112 pats.append('[^.]+')
113 else:
114 # Otherwise, '*' matches any dotless fragment.
115 frag = re.escape(frag)
116 pats.append(frag.replace(r'\*', '[^.]*'))
117 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
118
119
120def match_hostname(cert, hostname):
121 """Verify that *cert* (in decoded format as returned by
122 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
123 are mostly followed, but IP addresses are not accepted for *hostname*.
124
125 CertificateError is raised on failure. On success, the function
126 returns nothing.
127 """
128 if not cert:
129 raise ValueError("empty or no certificate")
130 dnsnames = []
131 san = cert.get('subjectAltName', ())
132 for key, value in san:
133 if key == 'DNS':
134 if _dnsname_to_pat(value).match(hostname):
135 return
136 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200137 if not dnsnames:
138 # The subject is only checked when there is no dNSName entry
139 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000140 for sub in cert.get('subject', ()):
141 for key, value in sub:
142 # XXX according to RFC 2818, the most specific Common Name
143 # must be used.
144 if key == 'commonName':
145 if _dnsname_to_pat(value).match(hostname):
146 return
147 dnsnames.append(value)
148 if len(dnsnames) > 1:
149 raise CertificateError("hostname %r "
150 "doesn't match either of %s"
151 % (hostname, ', '.join(map(repr, dnsnames))))
152 elif len(dnsnames) == 1:
153 raise CertificateError("hostname %r "
154 "doesn't match %r"
155 % (hostname, dnsnames[0]))
156 else:
157 raise CertificateError("no appropriate commonName or "
158 "subjectAltName fields were found")
159
160
Antoine Pitrou152efa22010-05-16 18:19:27 +0000161class SSLContext(_SSLContext):
162 """An SSLContext holds various SSL-related configuration options and
163 data, such as certificates and possibly a private key."""
164
165 __slots__ = ('protocol',)
166
167 def __new__(cls, protocol, *args, **kwargs):
168 return _SSLContext.__new__(cls, protocol)
169
170 def __init__(self, protocol):
171 self.protocol = protocol
172
173 def wrap_socket(self, sock, server_side=False,
174 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000175 suppress_ragged_eofs=True,
176 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000177 return SSLSocket(sock=sock, server_side=server_side,
178 do_handshake_on_connect=do_handshake_on_connect,
179 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000180 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000181 _context=self)
182
183
184class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000185 """This class implements a subtype of socket.socket that wraps
186 the underlying OS socket in an SSL context when necessary, and
187 provides read and write methods over that channel."""
188
Bill Janssen6e027db2007-11-15 22:23:56 +0000189 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000190 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000191 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
192 do_handshake_on_connect=True,
193 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000195 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000196 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000197
Antoine Pitrou152efa22010-05-16 18:19:27 +0000198 if _context:
199 self.context = _context
200 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000201 if server_side and not certfile:
202 raise ValueError("certfile must be specified for server-side "
203 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000204 if keyfile and not certfile:
205 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 if certfile and not keyfile:
207 keyfile = certfile
208 self.context = SSLContext(ssl_version)
209 self.context.verify_mode = cert_reqs
210 if ca_certs:
211 self.context.load_verify_locations(ca_certs)
212 if certfile:
213 self.context.load_cert_chain(certfile, keyfile)
214 if ciphers:
215 self.context.set_ciphers(ciphers)
216 self.keyfile = keyfile
217 self.certfile = certfile
218 self.cert_reqs = cert_reqs
219 self.ssl_version = ssl_version
220 self.ca_certs = ca_certs
221 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000222 if server_side and server_hostname:
223 raise ValueError("server_hostname can only be specified "
224 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000225 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000226 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000227 self.do_handshake_on_connect = do_handshake_on_connect
228 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000229 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000230 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000231 socket.__init__(self,
232 family=sock.family,
233 type=sock.type,
234 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000235 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000236 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000237 # see if it's connected
238 try:
239 sock.getpeername()
240 except socket_error as e:
241 if e.errno != errno.ENOTCONN:
242 raise
243 else:
244 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000245 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000246 elif fileno is not None:
247 socket.__init__(self, fileno=fileno)
248 else:
249 socket.__init__(self, family=family, type=type, proto=proto)
250
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000251 self._closed = False
252 self._sslobj = None
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000253 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000254 if connected:
255 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000256 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000257 self._sslobj = self.context._wrap_socket(self, server_side,
258 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000259 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000260 timeout = self.gettimeout()
261 if timeout == 0.0:
262 # non-blocking
263 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000264 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000265
Bill Janssen6e027db2007-11-15 22:23:56 +0000266 except socket_error as x:
267 self.close()
268 raise x
269
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000270 def dup(self):
271 raise NotImplemented("Can't dup() %s instances" %
272 self.__class__.__name__)
273
Bill Janssen6e027db2007-11-15 22:23:56 +0000274 def _checkClosed(self, msg=None):
275 # raise an exception here if you wish to check for spurious closes
276 pass
277
Bill Janssen54cc54c2007-12-14 22:08:56 +0000278 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000279 """Read up to LEN bytes and return them.
280 Return zero-length string on EOF."""
281
Bill Janssen6e027db2007-11-15 22:23:56 +0000282 self._checkClosed()
283 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000284 if buffer is not None:
285 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000286 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000287 v = self._sslobj.read(len or 1024)
288 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000289 except SSLError as x:
290 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000291 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000292 return 0
293 else:
294 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000295 else:
296 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000297
298 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000299 """Write DATA to the underlying SSL channel. Returns
300 number of bytes of DATA actually transmitted."""
301
Bill Janssen6e027db2007-11-15 22:23:56 +0000302 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000303 return self._sslobj.write(data)
304
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000305 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000306 """Returns a formatted version of the data in the
307 certificate provided by the other end of the SSL channel.
308 Return None if no certificate was provided, {} if a
309 certificate was provided, but not validated."""
310
Bill Janssen6e027db2007-11-15 22:23:56 +0000311 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000312 return self._sslobj.peer_certificate(binary_form)
313
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000314 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000315 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000316 if not self._sslobj:
317 return None
318 else:
319 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000320
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000321 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000322 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000323 if self._sslobj:
324 if flags != 0:
325 raise ValueError(
326 "non-zero flags not allowed in calls to send() on %s" %
327 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000328 while True:
329 try:
330 v = self._sslobj.write(data)
331 except SSLError as x:
332 if x.args[0] == SSL_ERROR_WANT_READ:
333 return 0
334 elif x.args[0] == SSL_ERROR_WANT_WRITE:
335 return 0
336 else:
337 raise
338 else:
339 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000340 else:
341 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000342
Antoine Pitroua468adc2010-09-14 14:43:44 +0000343 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000344 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000345 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000346 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000347 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000348 elif addr is None:
349 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000350 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000351 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000352
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000353 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000354 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000355 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000356 if flags != 0:
357 raise ValueError(
358 "non-zero flags not allowed in calls to sendall() on %s" %
359 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000360 amount = len(data)
361 count = 0
362 while (count < amount):
363 v = self.send(data[count:])
364 count += v
365 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000366 else:
367 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000368
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000369 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000370 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000371 if self._sslobj:
372 if flags != 0:
373 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000374 "non-zero flags not allowed in calls to recv() on %s" %
375 self.__class__)
376 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000377 else:
378 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000380 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000381 self._checkClosed()
382 if buffer and (nbytes is None):
383 nbytes = len(buffer)
384 elif nbytes is None:
385 nbytes = 1024
386 if self._sslobj:
387 if flags != 0:
388 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000389 "non-zero flags not allowed in calls to recv_into() on %s" %
390 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000391 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000392 else:
393 return socket.recv_into(self, buffer, nbytes, flags)
394
Antoine Pitroua468adc2010-09-14 14:43:44 +0000395 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000396 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000397 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000398 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000399 self.__class__)
400 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000401 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000402
Bill Janssen58afe4c2008-09-08 16:45:19 +0000403 def recvfrom_into(self, buffer, nbytes=None, flags=0):
404 self._checkClosed()
405 if self._sslobj:
406 raise ValueError("recvfrom_into not allowed on instances of %s" %
407 self.__class__)
408 else:
409 return socket.recvfrom_into(self, buffer, nbytes, flags)
410
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000411 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000412 self._checkClosed()
413 if self._sslobj:
414 return self._sslobj.pending()
415 else:
416 return 0
417
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000418 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000419 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000420 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000421 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000422
Ezio Melottidc55e672010-01-18 09:15:14 +0000423 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000424 if self._sslobj:
425 s = self._sslobj.shutdown()
426 self._sslobj = None
427 return s
428 else:
429 raise ValueError("No SSL wrapper around " + str(self))
430
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000431 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000433 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000434 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000435
Bill Janssen48dc27c2007-12-05 03:38:10 +0000436 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000437 """Perform a TLS/SSL handshake."""
438
Bill Janssen48dc27c2007-12-05 03:38:10 +0000439 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000440 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000441 if timeout == 0.0 and block:
442 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000443 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000444 finally:
445 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000446
Antoine Pitroub4410db2011-05-18 18:51:06 +0200447 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000448 if self.server_side:
449 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000450 # Here we assume that the socket is client-side, and not
451 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000452 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000453 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000454 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000455 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200456 if connect_ex:
457 rc = socket.connect_ex(self, addr)
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000458 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200459 rc = None
460 socket.connect(self, addr)
461 if not rc:
462 if self.do_handshake_on_connect:
463 self.do_handshake()
464 self._connected = True
465 return rc
466 except socket_error:
467 self._sslobj = None
468 raise
Antoine Pitrou86cbfec2011-02-26 23:25:34 +0000469
470 def connect(self, addr):
471 """Connects to remote ADDR, and then wraps the connection in
472 an SSL channel."""
473 self._real_connect(addr, False)
474
475 def connect_ex(self, addr):
476 """Connects to remote ADDR, and then wraps the connection in
477 an SSL channel."""
478 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000479
480 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000481 """Accepts a new connection from a remote client, and returns
482 a tuple containing that new connection wrapped with a server-side
483 SSL channel, and the address of the remote client."""
484
485 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000486 return (SSLSocket(sock=newsock,
487 keyfile=self.keyfile, certfile=self.certfile,
488 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000489 cert_reqs=self.cert_reqs,
490 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000491 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000492 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000493 do_handshake_on_connect=
494 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000495 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Guido van Rossume6650f92007-12-06 19:05:55 +0000497 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000498 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000499 self._real_close()
500
Bill Janssen54cc54c2007-12-14 22:08:56 +0000501
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502def wrap_socket(sock, keyfile=None, certfile=None,
503 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000504 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000505 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000506 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
Bill Janssen6e027db2007-11-15 22:23:56 +0000508 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000510 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000511 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000512 suppress_ragged_eofs=suppress_ragged_eofs,
513 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000514
Thomas Woutersed03b412007-08-28 21:37:11 +0000515# some utility functions
516
517def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000518 """Takes a date-time string in standard ASN1_print form
519 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
520 a Python time value in seconds past the epoch."""
521
Thomas Woutersed03b412007-08-28 21:37:11 +0000522 import time
523 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
524
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525PEM_HEADER = "-----BEGIN CERTIFICATE-----"
526PEM_FOOTER = "-----END CERTIFICATE-----"
527
528def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529 """Takes a certificate in binary DER format and returns the
530 PEM version of it as a string."""
531
Bill Janssen6e027db2007-11-15 22:23:56 +0000532 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
533 return (PEM_HEADER + '\n' +
534 textwrap.fill(f, 64) + '\n' +
535 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536
537def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538 """Takes a certificate in ASCII PEM format and returns the
539 DER-encoded version of it as a byte sequence"""
540
541 if not pem_cert_string.startswith(PEM_HEADER):
542 raise ValueError("Invalid PEM encoding; must start with %s"
543 % PEM_HEADER)
544 if not pem_cert_string.strip().endswith(PEM_FOOTER):
545 raise ValueError("Invalid PEM encoding; must end with %s"
546 % PEM_FOOTER)
547 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000548 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000550def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551 """Retrieve the certificate from the server at the specified address,
552 and return it as a PEM-encoded string.
553 If 'ca_certs' is specified, validate the server cert against it.
554 If 'ssl_version' is specified, use it in the connection attempt."""
555
556 host, port = addr
557 if (ca_certs is not None):
558 cert_reqs = CERT_REQUIRED
559 else:
560 cert_reqs = CERT_NONE
561 s = wrap_socket(socket(), ssl_version=ssl_version,
562 cert_reqs=cert_reqs, ca_certs=ca_certs)
563 s.connect(addr)
564 dercert = s.getpeercert(True)
565 s.close()
566 return DER_cert_to_PEM_cert(dercert)
567
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000568def get_protocol_name(protocol_code):
Victor Stinneree18b6f2011-05-10 00:38:00 +0200569 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')