blob: f1a0e45903c74966552ac0f93bdbcf0e4696ff03 [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)
125 if not san:
126 # The subject is only checked when subjectAltName is empty
127 for sub in cert.get('subject', ()):
128 for key, value in sub:
129 # XXX according to RFC 2818, the most specific Common Name
130 # must be used.
131 if key == 'commonName':
132 if _dnsname_to_pat(value).match(hostname):
133 return
134 dnsnames.append(value)
135 if len(dnsnames) > 1:
136 raise CertificateError("hostname %r "
137 "doesn't match either of %s"
138 % (hostname, ', '.join(map(repr, dnsnames))))
139 elif len(dnsnames) == 1:
140 raise CertificateError("hostname %r "
141 "doesn't match %r"
142 % (hostname, dnsnames[0]))
143 else:
144 raise CertificateError("no appropriate commonName or "
145 "subjectAltName fields were found")
146
147
Antoine Pitrou152efa22010-05-16 18:19:27 +0000148class SSLContext(_SSLContext):
149 """An SSLContext holds various SSL-related configuration options and
150 data, such as certificates and possibly a private key."""
151
152 __slots__ = ('protocol',)
153
154 def __new__(cls, protocol, *args, **kwargs):
155 return _SSLContext.__new__(cls, protocol)
156
157 def __init__(self, protocol):
158 self.protocol = protocol
159
160 def wrap_socket(self, sock, server_side=False,
161 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000162 suppress_ragged_eofs=True,
163 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000164 return SSLSocket(sock=sock, server_side=server_side,
165 do_handshake_on_connect=do_handshake_on_connect,
166 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000167 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000168 _context=self)
169
170
171class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000172 """This class implements a subtype of socket.socket that wraps
173 the underlying OS socket in an SSL context when necessary, and
174 provides read and write methods over that channel."""
175
Bill Janssen6e027db2007-11-15 22:23:56 +0000176 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000177 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000178 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
179 do_handshake_on_connect=True,
180 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000181 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000182 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000183 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000184
Antoine Pitrou152efa22010-05-16 18:19:27 +0000185 if _context:
186 self.context = _context
187 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000188 if server_side and not certfile:
189 raise ValueError("certfile must be specified for server-side "
190 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000191 if keyfile and not certfile:
192 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000193 if certfile and not keyfile:
194 keyfile = certfile
195 self.context = SSLContext(ssl_version)
196 self.context.verify_mode = cert_reqs
197 if ca_certs:
198 self.context.load_verify_locations(ca_certs)
199 if certfile:
200 self.context.load_cert_chain(certfile, keyfile)
201 if ciphers:
202 self.context.set_ciphers(ciphers)
203 self.keyfile = keyfile
204 self.certfile = certfile
205 self.cert_reqs = cert_reqs
206 self.ssl_version = ssl_version
207 self.ca_certs = ca_certs
208 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000209 if server_side and server_hostname:
210 raise ValueError("server_hostname can only be specified "
211 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000212 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000213 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214 self.do_handshake_on_connect = do_handshake_on_connect
215 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000216 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000217 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000218 socket.__init__(self,
219 family=sock.family,
220 type=sock.type,
221 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000222 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000223 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000224 # see if it's connected
225 try:
226 sock.getpeername()
227 except socket_error as e:
228 if e.errno != errno.ENOTCONN:
229 raise
230 else:
231 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000232 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000233 elif fileno is not None:
234 socket.__init__(self, fileno=fileno)
235 else:
236 socket.__init__(self, family=family, type=type, proto=proto)
237
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000238 self._closed = False
239 self._sslobj = None
240 if connected:
241 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000242 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000243 self._sslobj = self.context._wrap_socket(self, server_side,
244 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000245 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000246 timeout = self.gettimeout()
247 if timeout == 0.0:
248 # non-blocking
249 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000250 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000251
Bill Janssen6e027db2007-11-15 22:23:56 +0000252 except socket_error as x:
253 self.close()
254 raise x
255
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000256 def dup(self):
257 raise NotImplemented("Can't dup() %s instances" %
258 self.__class__.__name__)
259
Bill Janssen6e027db2007-11-15 22:23:56 +0000260 def _checkClosed(self, msg=None):
261 # raise an exception here if you wish to check for spurious closes
262 pass
263
Bill Janssen54cc54c2007-12-14 22:08:56 +0000264 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000265 """Read up to LEN bytes and return them.
266 Return zero-length string on EOF."""
267
Bill Janssen6e027db2007-11-15 22:23:56 +0000268 self._checkClosed()
269 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000270 if buffer is not None:
271 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000273 v = self._sslobj.read(len or 1024)
274 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000275 except SSLError as x:
276 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000277 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000278 return 0
279 else:
280 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000281 else:
282 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000283
284 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000285 """Write DATA to the underlying SSL channel. Returns
286 number of bytes of DATA actually transmitted."""
287
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000289 return self._sslobj.write(data)
290
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000291 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000292 """Returns a formatted version of the data in the
293 certificate provided by the other end of the SSL channel.
294 Return None if no certificate was provided, {} if a
295 certificate was provided, but not validated."""
296
Bill Janssen6e027db2007-11-15 22:23:56 +0000297 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000298 return self._sslobj.peer_certificate(binary_form)
299
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000300 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000301 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000302 if not self._sslobj:
303 return None
304 else:
305 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000306
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000307 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000308 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000309 if self._sslobj:
310 if flags != 0:
311 raise ValueError(
312 "non-zero flags not allowed in calls to send() on %s" %
313 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000314 while True:
315 try:
316 v = self._sslobj.write(data)
317 except SSLError as x:
318 if x.args[0] == SSL_ERROR_WANT_READ:
319 return 0
320 elif x.args[0] == SSL_ERROR_WANT_WRITE:
321 return 0
322 else:
323 raise
324 else:
325 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000326 else:
327 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000328
Antoine Pitroua468adc2010-09-14 14:43:44 +0000329 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000330 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000331 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000332 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000333 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000334 elif addr is None:
335 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000336 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000337 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000338
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000339 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000340 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000342 if flags != 0:
343 raise ValueError(
344 "non-zero flags not allowed in calls to sendall() on %s" %
345 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000346 amount = len(data)
347 count = 0
348 while (count < amount):
349 v = self.send(data[count:])
350 count += v
351 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000352 else:
353 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000354
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000355 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000356 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000357 if self._sslobj:
358 if flags != 0:
359 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000360 "non-zero flags not allowed in calls to recv() on %s" %
361 self.__class__)
362 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000363 else:
364 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000365
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000366 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000367 self._checkClosed()
368 if buffer and (nbytes is None):
369 nbytes = len(buffer)
370 elif nbytes is None:
371 nbytes = 1024
372 if self._sslobj:
373 if flags != 0:
374 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000375 "non-zero flags not allowed in calls to recv_into() on %s" %
376 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000377 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000378 else:
379 return socket.recv_into(self, buffer, nbytes, flags)
380
Antoine Pitroua468adc2010-09-14 14:43:44 +0000381 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000382 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000383 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000384 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000385 self.__class__)
386 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000387 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000388
Bill Janssen58afe4c2008-09-08 16:45:19 +0000389 def recvfrom_into(self, buffer, nbytes=None, flags=0):
390 self._checkClosed()
391 if self._sslobj:
392 raise ValueError("recvfrom_into not allowed on instances of %s" %
393 self.__class__)
394 else:
395 return socket.recvfrom_into(self, buffer, nbytes, flags)
396
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000397 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000398 self._checkClosed()
399 if self._sslobj:
400 return self._sslobj.pending()
401 else:
402 return 0
403
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000404 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000405 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000407 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000408
Ezio Melottidc55e672010-01-18 09:15:14 +0000409 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000410 if self._sslobj:
411 s = self._sslobj.shutdown()
412 self._sslobj = None
413 return s
414 else:
415 raise ValueError("No SSL wrapper around " + str(self))
416
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000417 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000418 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000419 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000420 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000421
Bill Janssen48dc27c2007-12-05 03:38:10 +0000422 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000423 """Perform a TLS/SSL handshake."""
424
Bill Janssen48dc27c2007-12-05 03:38:10 +0000425 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000426 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000427 if timeout == 0.0 and block:
428 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000429 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000430 finally:
431 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000432
433 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000434 """Connects to remote ADDR, and then wraps the connection in
435 an SSL channel."""
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.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000440 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000442 socket.connect(self, addr)
Antoine Pitroud5323212010-10-22 18:19:07 +0000443 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000444 try:
445 if self.do_handshake_on_connect:
446 self.do_handshake()
447 except:
448 self._sslobj = None
449 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000450
451 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000452 """Accepts a new connection from a remote client, and returns
453 a tuple containing that new connection wrapped with a server-side
454 SSL channel, and the address of the remote client."""
455
456 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000457 return (SSLSocket(sock=newsock,
458 keyfile=self.keyfile, certfile=self.certfile,
459 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000460 cert_reqs=self.cert_reqs,
461 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000462 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000463 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000464 do_handshake_on_connect=
465 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000466 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467
Guido van Rossume6650f92007-12-06 19:05:55 +0000468 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000469 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000470 self._real_close()
471
Bill Janssen54cc54c2007-12-14 22:08:56 +0000472
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473def wrap_socket(sock, keyfile=None, certfile=None,
474 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000475 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000476 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000477 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478
Bill Janssen6e027db2007-11-15 22:23:56 +0000479 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000481 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000482 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000483 suppress_ragged_eofs=suppress_ragged_eofs,
484 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Thomas Woutersed03b412007-08-28 21:37:11 +0000486# some utility functions
487
488def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000489 """Takes a date-time string in standard ASN1_print form
490 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
491 a Python time value in seconds past the epoch."""
492
Thomas Woutersed03b412007-08-28 21:37:11 +0000493 import time
494 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
495
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496PEM_HEADER = "-----BEGIN CERTIFICATE-----"
497PEM_FOOTER = "-----END CERTIFICATE-----"
498
499def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500 """Takes a certificate in binary DER format and returns the
501 PEM version of it as a string."""
502
Bill Janssen6e027db2007-11-15 22:23:56 +0000503 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
504 return (PEM_HEADER + '\n' +
505 textwrap.fill(f, 64) + '\n' +
506 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
508def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509 """Takes a certificate in ASCII PEM format and returns the
510 DER-encoded version of it as a byte sequence"""
511
512 if not pem_cert_string.startswith(PEM_HEADER):
513 raise ValueError("Invalid PEM encoding; must start with %s"
514 % PEM_HEADER)
515 if not pem_cert_string.strip().endswith(PEM_FOOTER):
516 raise ValueError("Invalid PEM encoding; must end with %s"
517 % PEM_FOOTER)
518 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000519 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000521def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522 """Retrieve the certificate from the server at the specified address,
523 and return it as a PEM-encoded string.
524 If 'ca_certs' is specified, validate the server cert against it.
525 If 'ssl_version' is specified, use it in the connection attempt."""
526
527 host, port = addr
528 if (ca_certs is not None):
529 cert_reqs = CERT_REQUIRED
530 else:
531 cert_reqs = CERT_NONE
532 s = wrap_socket(socket(), ssl_version=ssl_version,
533 cert_reqs=cert_reqs, ca_certs=ca_certs)
534 s.connect(addr)
535 dercert = s.getpeercert(True)
536 s.close()
537 return DER_cert_to_PEM_cert(dercert)
538
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000539def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000540 if protocol_code == PROTOCOL_TLSv1:
541 return "TLSv1"
542 elif protocol_code == PROTOCOL_SSLv23:
543 return "SSLv23"
544 elif protocol_code == PROTOCOL_SSLv2:
545 return "SSLv2"
546 elif protocol_code == PROTOCOL_SSLv3:
547 return "SSLv3"
548 else:
549 return "<unknown>"