Home | History | Annotate | Download | only in python2.7
      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             if return_errno:
    317                 rc = socket.connect_ex(self, addr)
    318             else:
    319                 rc = None
    320                 socket.connect(self, addr)
    321             if not rc:
    322                 if self.do_handshake_on_connect:
    323                     self.do_handshake()
    324                 self._connected = True
    325             return rc
    326         except socket_error:
    327             self._sslobj = None
    328             raise
    329 
    330     def connect(self, addr):
    331         """Connects to remote ADDR, and then wraps the connection in
    332         an SSL channel."""
    333         self._real_connect(addr, False)
    334 
    335     def connect_ex(self, addr):
    336         """Connects to remote ADDR, and then wraps the connection in
    337         an SSL channel."""
    338         return self._real_connect(addr, True)
    339 
    340     def accept(self):
    341 
    342         """Accepts a new connection from a remote client, and returns
    343         a tuple containing that new connection wrapped with a server-side
    344         SSL channel, and the address of the remote client."""
    345 
    346         newsock, addr = socket.accept(self)
    347         try:
    348             return (SSLSocket(newsock,
    349                               keyfile=self.keyfile,
    350                               certfile=self.certfile,
    351                               server_side=True,
    352                               cert_reqs=self.cert_reqs,
    353                               ssl_version=self.ssl_version,
    354                               ca_certs=self.ca_certs,
    355                               ciphers=self.ciphers,
    356                               do_handshake_on_connect=self.do_handshake_on_connect,
    357                               suppress_ragged_eofs=self.suppress_ragged_eofs),
    358                     addr)
    359         except socket_error as e:
    360             newsock.close()
    361             raise e
    362 
    363     def makefile(self, mode='r', bufsize=-1):
    364 
    365         """Make and return a file-like object that
    366         works with the SSL connection.  Just use the code
    367         from the socket module."""
    368 
    369         self._makefile_refs += 1
    370         # close=True so as to decrement the reference count when done with
    371         # the file-like object.
    372         return _fileobject(self, mode, bufsize, close=True)
    373 
    374 
    375 
    376 def wrap_socket(sock, keyfile=None, certfile=None,
    377                 server_side=False, cert_reqs=CERT_NONE,
    378                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
    379                 do_handshake_on_connect=True,
    380                 suppress_ragged_eofs=True, ciphers=None):
    381 
    382     return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
    383                      server_side=server_side, cert_reqs=cert_reqs,
    384                      ssl_version=ssl_version, ca_certs=ca_certs,
    385                      do_handshake_on_connect=do_handshake_on_connect,
    386                      suppress_ragged_eofs=suppress_ragged_eofs,
    387                      ciphers=ciphers)
    388 
    389 
    390 # some utility functions
    391 
    392 def cert_time_to_seconds(cert_time):
    393 
    394     """Takes a date-time string in standard ASN1_print form
    395     ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
    396     a Python time value in seconds past the epoch."""
    397 
    398     import time
    399     return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
    400 
    401 PEM_HEADER = "-----BEGIN CERTIFICATE-----"
    402 PEM_FOOTER = "-----END CERTIFICATE-----"
    403 
    404 def DER_cert_to_PEM_cert(der_cert_bytes):
    405 
    406     """Takes a certificate in binary DER format and returns the
    407     PEM version of it as a string."""
    408 
    409     if hasattr(base64, 'standard_b64encode'):
    410         # preferred because older API gets line-length wrong
    411         f = base64.standard_b64encode(der_cert_bytes)
    412         return (PEM_HEADER + '\n' +
    413                 textwrap.fill(f, 64) + '\n' +
    414                 PEM_FOOTER + '\n')
    415     else:
    416         return (PEM_HEADER + '\n' +
    417                 base64.encodestring(der_cert_bytes) +
    418                 PEM_FOOTER + '\n')
    419 
    420 def PEM_cert_to_DER_cert(pem_cert_string):
    421 
    422     """Takes a certificate in ASCII PEM format and returns the
    423     DER-encoded version of it as a byte sequence"""
    424 
    425     if not pem_cert_string.startswith(PEM_HEADER):
    426         raise ValueError("Invalid PEM encoding; must start with %s"
    427                          % PEM_HEADER)
    428     if not pem_cert_string.strip().endswith(PEM_FOOTER):
    429         raise ValueError("Invalid PEM encoding; must end with %s"
    430                          % PEM_FOOTER)
    431     d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
    432     return base64.decodestring(d)
    433 
    434 def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
    435 
    436     """Retrieve the certificate from the server at the specified address,
    437     and return it as a PEM-encoded string.
    438     If 'ca_certs' is specified, validate the server cert against it.
    439     If 'ssl_version' is specified, use it in the connection attempt."""
    440 
    441     host, port = addr
    442     if (ca_certs is not None):
    443         cert_reqs = CERT_REQUIRED
    444     else:
    445         cert_reqs = CERT_NONE
    446     s = wrap_socket(socket(), ssl_version=ssl_version,
    447                     cert_reqs=cert_reqs, ca_certs=ca_certs)
    448     s.connect(addr)
    449     dercert = s.getpeercert(True)
    450     s.close()
    451     return DER_cert_to_PEM_cert(dercert)
    452 
    453 def get_protocol_name(protocol_code):
    454     return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
    455 
    456 
    457 # a replacement for the old socket.ssl function
    458 
    459 def sslwrap_simple(sock, keyfile=None, certfile=None):
    460 
    461     """A replacement for the old socket.ssl function.  Designed
    462     for compability with Python 2.5 and earlier.  Will disappear in
    463     Python 3.0."""
    464 
    465     if hasattr(sock, "_sock"):
    466         sock = sock._sock
    467 
    468     ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE,
    469                             PROTOCOL_SSLv23, None)
    470     try:
    471         sock.getpeername()
    472     except socket_error:
    473         # no, no connection yet
    474         pass
    475     else:
    476         # yes, do the handshake
    477         ssl_sock.do_handshake()
    478 
    479     return ssl_sock
    480