Update to 2.7.3
[profile/ivi/python.git] / Lib / ssl.py
1 # Wrapper module for _ssl, providing some additional facilities
2 # implemented in Python.  Written by Bill Janssen.
3
4 """\
5 This module provides some more Pythonic support for SSL.
6
7 Object types:
8
9   SSLSocket -- subtype of socket.socket which does SSL over the socket
10
11 Exceptions:
12
13   SSLError -- exception raised for I/O errors
14
15 Functions:
16
17   cert_time_to_seconds -- convert time string used for certificate
18                           notBefore and notAfter functions to integer
19                           seconds past the Epoch (the time values
20                           returned from time.time())
21
22   fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
23                           by the server running on HOST at port PORT.  No
24                           validation of the certificate is performed.
25
26 Integer constants:
27
28 SSL_ERROR_ZERO_RETURN
29 SSL_ERROR_WANT_READ
30 SSL_ERROR_WANT_WRITE
31 SSL_ERROR_WANT_X509_LOOKUP
32 SSL_ERROR_SYSCALL
33 SSL_ERROR_SSL
34 SSL_ERROR_WANT_CONNECT
35
36 SSL_ERROR_EOF
37 SSL_ERROR_INVALID_ERROR_CODE
38
39 The following group define certificate requirements that one side is
40 allowing/requiring from the other side:
41
42 CERT_NONE - no certificates from the other side are required (or will
43             be looked at if provided)
44 CERT_OPTIONAL - certificates are not required, but if provided will be
45                 validated, and if validation fails, the connection will
46                 also fail
47 CERT_REQUIRED - certificates are required, and will be validated, and
48                 if validation fails, the connection will also fail
49
50 The following constants identify various SSL protocol variants:
51
52 PROTOCOL_SSLv2
53 PROTOCOL_SSLv3
54 PROTOCOL_SSLv23
55 PROTOCOL_TLSv1
56 """
57
58 import textwrap
59
60 import _ssl             # if we can't import it, let the error propagate
61
62 from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
63 from _ssl import SSLError
64 from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
65 from _ssl import RAND_status, RAND_egd, RAND_add
66 from _ssl import \
67      SSL_ERROR_ZERO_RETURN, \
68      SSL_ERROR_WANT_READ, \
69      SSL_ERROR_WANT_WRITE, \
70      SSL_ERROR_WANT_X509_LOOKUP, \
71      SSL_ERROR_SYSCALL, \
72      SSL_ERROR_SSL, \
73      SSL_ERROR_WANT_CONNECT, \
74      SSL_ERROR_EOF, \
75      SSL_ERROR_INVALID_ERROR_CODE
76 from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
77 _PROTOCOL_NAMES = {
78     PROTOCOL_TLSv1: "TLSv1",
79     PROTOCOL_SSLv23: "SSLv23",
80     PROTOCOL_SSLv3: "SSLv3",
81 }
82 try:
83     from _ssl import PROTOCOL_SSLv2
84     _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
85 except ImportError:
86     _SSLv2_IF_EXISTS = None
87 else:
88     _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
89
90 from socket import socket, _fileobject, _delegate_methods, error as socket_error
91 from socket import getnameinfo as _getnameinfo
92 import base64        # for DER-to-PEM translation
93 import errno
94
95 # Disable weak or insecure ciphers by default
96 # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
97 _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
98
99
100 class SSLSocket(socket):
101
102     """This class implements a subtype of socket.socket that wraps
103     the underlying OS socket in an SSL context when necessary, and
104     provides read and write methods over that channel."""
105
106     def __init__(self, sock, keyfile=None, certfile=None,
107                  server_side=False, cert_reqs=CERT_NONE,
108                  ssl_version=PROTOCOL_SSLv23, ca_certs=None,
109                  do_handshake_on_connect=True,
110                  suppress_ragged_eofs=True, ciphers=None):
111         socket.__init__(self, _sock=sock._sock)
112         # The initializer for socket overrides the methods send(), recv(), etc.
113         # in the instancce, which we don't need -- but we want to provide the
114         # methods defined in SSLSocket.
115         for attr in _delegate_methods:
116             try:
117                 delattr(self, attr)
118             except AttributeError:
119                 pass
120
121         if ciphers is None and ssl_version != _SSLv2_IF_EXISTS:
122             ciphers = _DEFAULT_CIPHERS
123
124         if certfile and not keyfile:
125             keyfile = certfile
126         # see if it's connected
127         try:
128             socket.getpeername(self)
129         except socket_error, e:
130             if e.errno != errno.ENOTCONN:
131                 raise
132             # no, no connection yet
133             self._connected = False
134             self._sslobj = None
135         else:
136             # yes, create the SSL object
137             self._connected = True
138             self._sslobj = _ssl.sslwrap(self._sock, server_side,
139                                         keyfile, certfile,
140                                         cert_reqs, ssl_version, ca_certs,
141                                         ciphers)
142             if do_handshake_on_connect:
143                 self.do_handshake()
144         self.keyfile = keyfile
145         self.certfile = certfile
146         self.cert_reqs = cert_reqs
147         self.ssl_version = ssl_version
148         self.ca_certs = ca_certs
149         self.ciphers = ciphers
150         self.do_handshake_on_connect = do_handshake_on_connect
151         self.suppress_ragged_eofs = suppress_ragged_eofs
152         self._makefile_refs = 0
153
154     def read(self, len=1024):
155
156         """Read up to LEN bytes and return them.
157         Return zero-length string on EOF."""
158
159         try:
160             return self._sslobj.read(len)
161         except SSLError, x:
162             if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
163                 return ''
164             else:
165                 raise
166
167     def write(self, data):
168
169         """Write DATA to the underlying SSL channel.  Returns
170         number of bytes of DATA actually transmitted."""
171
172         return self._sslobj.write(data)
173
174     def getpeercert(self, binary_form=False):
175
176         """Returns a formatted version of the data in the
177         certificate provided by the other end of the SSL channel.
178         Return None if no certificate was provided, {} if a
179         certificate was provided, but not validated."""
180
181         return self._sslobj.peer_certificate(binary_form)
182
183     def cipher(self):
184
185         if not self._sslobj:
186             return None
187         else:
188             return self._sslobj.cipher()
189
190     def send(self, data, flags=0):
191         if self._sslobj:
192             if flags != 0:
193                 raise ValueError(
194                     "non-zero flags not allowed in calls to send() on %s" %
195                     self.__class__)
196             while True:
197                 try:
198                     v = self._sslobj.write(data)
199                 except SSLError, x:
200                     if x.args[0] == SSL_ERROR_WANT_READ:
201                         return 0
202                     elif x.args[0] == SSL_ERROR_WANT_WRITE:
203                         return 0
204                     else:
205                         raise
206                 else:
207                     return v
208         else:
209             return self._sock.send(data, flags)
210
211     def sendto(self, data, flags_or_addr, addr=None):
212         if self._sslobj:
213             raise ValueError("sendto not allowed on instances of %s" %
214                              self.__class__)
215         elif addr is None:
216             return self._sock.sendto(data, flags_or_addr)
217         else:
218             return self._sock.sendto(data, flags_or_addr, addr)
219
220     def sendall(self, data, flags=0):
221         if self._sslobj:
222             if flags != 0:
223                 raise ValueError(
224                     "non-zero flags not allowed in calls to sendall() on %s" %
225                     self.__class__)
226             amount = len(data)
227             count = 0
228             while (count < amount):
229                 v = self.send(data[count:])
230                 count += v
231             return amount
232         else:
233             return socket.sendall(self, data, flags)
234
235     def recv(self, buflen=1024, flags=0):
236         if self._sslobj:
237             if flags != 0:
238                 raise ValueError(
239                     "non-zero flags not allowed in calls to recv() on %s" %
240                     self.__class__)
241             return self.read(buflen)
242         else:
243             return self._sock.recv(buflen, flags)
244
245     def recv_into(self, buffer, nbytes=None, flags=0):
246         if buffer and (nbytes is None):
247             nbytes = len(buffer)
248         elif nbytes is None:
249             nbytes = 1024
250         if self._sslobj:
251             if flags != 0:
252                 raise ValueError(
253                   "non-zero flags not allowed in calls to recv_into() on %s" %
254                   self.__class__)
255             tmp_buffer = self.read(nbytes)
256             v = len(tmp_buffer)
257             buffer[:v] = tmp_buffer
258             return v
259         else:
260             return self._sock.recv_into(buffer, nbytes, flags)
261
262     def recvfrom(self, buflen=1024, flags=0):
263         if self._sslobj:
264             raise ValueError("recvfrom not allowed on instances of %s" %
265                              self.__class__)
266         else:
267             return self._sock.recvfrom(buflen, flags)
268
269     def recvfrom_into(self, buffer, nbytes=None, flags=0):
270         if self._sslobj:
271             raise ValueError("recvfrom_into not allowed on instances of %s" %
272                              self.__class__)
273         else:
274             return self._sock.recvfrom_into(buffer, nbytes, flags)
275
276     def pending(self):
277         if self._sslobj:
278             return self._sslobj.pending()
279         else:
280             return 0
281
282     def unwrap(self):
283         if self._sslobj:
284             s = self._sslobj.shutdown()
285             self._sslobj = None
286             return s
287         else:
288             raise ValueError("No SSL wrapper around " + str(self))
289
290     def shutdown(self, how):
291         self._sslobj = None
292         socket.shutdown(self, how)
293
294     def close(self):
295         if self._makefile_refs < 1:
296             self._sslobj = None
297             socket.close(self)
298         else:
299             self._makefile_refs -= 1
300
301     def do_handshake(self):
302
303         """Perform a TLS/SSL handshake."""
304
305         self._sslobj.do_handshake()
306
307     def _real_connect(self, addr, return_errno):
308         # Here we assume that the socket is client-side, and not
309         # connected at the time of the call.  We connect it, then wrap it.
310         if self._connected:
311             raise ValueError("attempt to connect already-connected SSLSocket!")
312         self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
313                                     self.cert_reqs, self.ssl_version,
314                                     self.ca_certs, self.ciphers)
315         try:
316             socket.connect(self, addr)
317             if self.do_handshake_on_connect:
318                 self.do_handshake()
319         except socket_error as e:
320             if return_errno:
321                 return e.errno
322             else:
323                 self._sslobj = None
324                 raise e
325         self._connected = True
326         return 0
327
328     def connect(self, addr):
329         """Connects to remote ADDR, and then wraps the connection in
330         an SSL channel."""
331         self._real_connect(addr, False)
332
333     def connect_ex(self, addr):
334         """Connects to remote ADDR, and then wraps the connection in
335         an SSL channel."""
336         return self._real_connect(addr, True)
337
338     def accept(self):
339
340         """Accepts a new connection from a remote client, and returns
341         a tuple containing that new connection wrapped with a server-side
342         SSL channel, and the address of the remote client."""
343
344         newsock, addr = socket.accept(self)
345         return (SSLSocket(newsock,
346                           keyfile=self.keyfile,
347                           certfile=self.certfile,
348                           server_side=True,
349                           cert_reqs=self.cert_reqs,
350                           ssl_version=self.ssl_version,
351                           ca_certs=self.ca_certs,
352                           ciphers=self.ciphers,
353                           do_handshake_on_connect=self.do_handshake_on_connect,
354                           suppress_ragged_eofs=self.suppress_ragged_eofs),
355                 addr)
356
357     def makefile(self, mode='r', bufsize=-1):
358
359         """Make and return a file-like object that
360         works with the SSL connection.  Just use the code
361         from the socket module."""
362
363         self._makefile_refs += 1
364         # close=True so as to decrement the reference count when done with
365         # the file-like object.
366         return _fileobject(self, mode, bufsize, close=True)
367
368
369
370 def wrap_socket(sock, keyfile=None, certfile=None,
371                 server_side=False, cert_reqs=CERT_NONE,
372                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
373                 do_handshake_on_connect=True,
374                 suppress_ragged_eofs=True, ciphers=None):
375
376     return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
377                      server_side=server_side, cert_reqs=cert_reqs,
378                      ssl_version=ssl_version, ca_certs=ca_certs,
379                      do_handshake_on_connect=do_handshake_on_connect,
380                      suppress_ragged_eofs=suppress_ragged_eofs,
381                      ciphers=ciphers)
382
383
384 # some utility functions
385
386 def cert_time_to_seconds(cert_time):
387
388     """Takes a date-time string in standard ASN1_print form
389     ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
390     a Python time value in seconds past the epoch."""
391
392     import time
393     return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
394
395 PEM_HEADER = "-----BEGIN CERTIFICATE-----"
396 PEM_FOOTER = "-----END CERTIFICATE-----"
397
398 def DER_cert_to_PEM_cert(der_cert_bytes):
399
400     """Takes a certificate in binary DER format and returns the
401     PEM version of it as a string."""
402
403     if hasattr(base64, 'standard_b64encode'):
404         # preferred because older API gets line-length wrong
405         f = base64.standard_b64encode(der_cert_bytes)
406         return (PEM_HEADER + '\n' +
407                 textwrap.fill(f, 64) + '\n' +
408                 PEM_FOOTER + '\n')
409     else:
410         return (PEM_HEADER + '\n' +
411                 base64.encodestring(der_cert_bytes) +
412                 PEM_FOOTER + '\n')
413
414 def PEM_cert_to_DER_cert(pem_cert_string):
415
416     """Takes a certificate in ASCII PEM format and returns the
417     DER-encoded version of it as a byte sequence"""
418
419     if not pem_cert_string.startswith(PEM_HEADER):
420         raise ValueError("Invalid PEM encoding; must start with %s"
421                          % PEM_HEADER)
422     if not pem_cert_string.strip().endswith(PEM_FOOTER):
423         raise ValueError("Invalid PEM encoding; must end with %s"
424                          % PEM_FOOTER)
425     d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
426     return base64.decodestring(d)
427
428 def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
429
430     """Retrieve the certificate from the server at the specified address,
431     and return it as a PEM-encoded string.
432     If 'ca_certs' is specified, validate the server cert against it.
433     If 'ssl_version' is specified, use it in the connection attempt."""
434
435     host, port = addr
436     if (ca_certs is not None):
437         cert_reqs = CERT_REQUIRED
438     else:
439         cert_reqs = CERT_NONE
440     s = wrap_socket(socket(), ssl_version=ssl_version,
441                     cert_reqs=cert_reqs, ca_certs=ca_certs)
442     s.connect(addr)
443     dercert = s.getpeercert(True)
444     s.close()
445     return DER_cert_to_PEM_cert(dercert)
446
447 def get_protocol_name(protocol_code):
448     return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
449
450
451 # a replacement for the old socket.ssl function
452
453 def sslwrap_simple(sock, keyfile=None, certfile=None):
454
455     """A replacement for the old socket.ssl function.  Designed
456     for compability with Python 2.5 and earlier.  Will disappear in
457     Python 3.0."""
458
459     if hasattr(sock, "_sock"):
460         sock = sock._sock
461
462     ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE,
463                             PROTOCOL_SSLv23, None)
464     try:
465         sock.getpeername()
466     except socket_error:
467         # no, no connection yet
468         pass
469     else:
470         # yes, do the handshake
471         ssl_sock.do_handshake()
472
473     return ssl_sock