[Python-checkins] r85783 - in python/branches/issue5639: Lib/http/client.py Lib/ssl.py Lib/test/test_ssl.py Lib/test/test_urllib2net.py Modules/_ssl.c

antoine.pitrou python-checkins at python.org
Thu Oct 21 22:30:31 CEST 2010


Author: antoine.pitrou
Date: Thu Oct 21 22:30:31 2010
New Revision: 85783

Log:
TLS SNI support (for buildbot testing)



Modified:
   python/branches/issue5639/Lib/http/client.py
   python/branches/issue5639/Lib/ssl.py
   python/branches/issue5639/Lib/test/test_ssl.py
   python/branches/issue5639/Lib/test/test_urllib2net.py
   python/branches/issue5639/Modules/_ssl.c

Modified: python/branches/issue5639/Lib/http/client.py
==============================================================================
--- python/branches/issue5639/Lib/http/client.py	(original)
+++ python/branches/issue5639/Lib/http/client.py	Thu Oct 21 22:30:31 2010
@@ -1081,7 +1081,7 @@
                 self.sock = sock
                 self._tunnel()
 
-            self.sock = self._context.wrap_socket(sock)
+            self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
             try:
                 if self._check_hostname:
                     ssl.match_hostname(self.sock.getpeercert(), self.host)

Modified: python/branches/issue5639/Lib/ssl.py
==============================================================================
--- python/branches/issue5639/Lib/ssl.py	(original)
+++ python/branches/issue5639/Lib/ssl.py	Thu Oct 21 22:30:31 2010
@@ -77,6 +77,7 @@
     SSL_ERROR_EOF,
     SSL_ERROR_INVALID_ERROR_CODE,
     )
+from _ssl import HAS_SNI
 
 from socket import getnameinfo as _getnameinfo
 from socket import error as socket_error
@@ -158,10 +159,12 @@
 
     def wrap_socket(self, sock, server_side=False,
                     do_handshake_on_connect=True,
-                    suppress_ragged_eofs=True):
+                    suppress_ragged_eofs=True,
+                    server_hostname=None):
         return SSLSocket(sock=sock, server_side=server_side,
                          do_handshake_on_connect=do_handshake_on_connect,
                          suppress_ragged_eofs=suppress_ragged_eofs,
+                         server_hostname=server_hostname,
                          _context=self)
 
 
@@ -176,6 +179,7 @@
                  do_handshake_on_connect=True,
                  family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
                  suppress_ragged_eofs=True, ciphers=None,
+                 server_hostname=None,
                  _context=None):
 
         if _context:
@@ -202,7 +206,11 @@
             self.ssl_version = ssl_version
             self.ca_certs = ca_certs
             self.ciphers = ciphers
+        if server_side and server_hostname:
+            raise ValueError("server_hostname can only be specified "
+                             "in client mode")
         self.server_side = server_side
+        self.server_hostname = server_hostname
         self.do_handshake_on_connect = do_handshake_on_connect
         self.suppress_ragged_eofs = suppress_ragged_eofs
         connected = False
@@ -232,7 +240,8 @@
         if connected:
             # create the SSL object
             try:
-                self._sslobj = self.context._wrap_socket(self, server_side)
+                self._sslobj = self.context._wrap_socket(self, server_side,
+                                                         server_hostname)
                 if do_handshake_on_connect:
                     timeout = self.gettimeout()
                     if timeout == 0.0:
@@ -431,7 +440,7 @@
         if self._sslobj:
             raise ValueError("attempt to connect already-connected SSLSocket!")
         socket.connect(self, addr)
-        self._sslobj = self.context._wrap_socket(self, False)
+        self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
         try:
             if self.do_handshake_on_connect:
                 self.do_handshake()

Modified: python/branches/issue5639/Lib/test/test_ssl.py
==============================================================================
--- python/branches/issue5639/Lib/test/test_ssl.py	(original)
+++ python/branches/issue5639/Lib/test/test_ssl.py	Thu Oct 21 22:30:31 2010
@@ -89,6 +89,7 @@
         ssl.CERT_NONE
         ssl.CERT_OPTIONAL
         ssl.CERT_REQUIRED
+        self.assertIn(ssl.HAS_SNI, {True, False})
 
     def test_random(self):
         v = ssl.RAND_status()
@@ -277,6 +278,12 @@
         self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com')
         self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com')
 
+    def test_server_side(self):
+        # server_hostname doesn't work for server sockets
+        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+        sock = socket.socket()
+        self.assertRaises(ValueError, ctx.wrap_socket, sock, True,
+                          server_hostname="some.hostname")
 
 class ContextTests(unittest.TestCase):
 
@@ -441,6 +448,10 @@
                 self.assertEqual({}, s.getpeercert())
             finally:
                 s.close()
+            # Same with a server hostname
+            s = ctx.wrap_socket(socket.socket(socket.AF_INET),
+                                server_hostname="svn.python.org")
+            s.close()
             # This should fail because we have no verification certs
             ctx.verify_mode = ssl.CERT_REQUIRED
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))

Modified: python/branches/issue5639/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/issue5639/Lib/test/test_urllib2net.py	(original)
+++ python/branches/issue5639/Lib/test/test_urllib2net.py	Thu Oct 21 22:30:31 2010
@@ -9,6 +9,10 @@
 import urllib.error
 import urllib.request
 import sys
+try:
+    import ssl
+except ImportError:
+    ssl = None
 
 TIMEOUT = 60  # seconds
 
@@ -278,13 +282,34 @@
         self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
 
 
+ at unittest.skipUnless(ssl, "requires SSL support")
+class HTTPSTests(unittest.TestCase):
+
+    def test_sni(self):
+        # Checks that Server Name Indication works, if supported by the
+        # OpenSSL linked to.
+        # The ssl module itself doesn't have server-side support for SNI,
+        # so we rely on a third-party test site.
+        expect_sni = ssl.HAS_SNI
+        with support.transient_internet("bob.sni.velox.ch"):
+            u = urllib.request.urlopen("https://bob.sni.velox.ch/")
+            contents = u.readall()
+            if expect_sni:
+                self.assertIn(b"Great", contents)
+                self.assertNotIn(b"Unfortunately", contents)
+            else:
+                self.assertNotIn(b"Great", contents)
+                self.assertIn(b"Unfortunately", contents)
+
+
 def test_main():
     support.requires("network")
     support.run_unittest(AuthTests,
-                              OtherNetworkTests,
-                              CloseSocketTest,
-                              TimeoutTest,
-                              )
+                         HTTPSTests,
+                         OtherNetworkTests,
+                         CloseSocketTest,
+                         TimeoutTest,
+                         )
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/issue5639/Modules/_ssl.c
==============================================================================
--- python/branches/issue5639/Modules/_ssl.c	(original)
+++ python/branches/issue5639/Modules/_ssl.c	Thu Oct 21 22:30:31 2010
@@ -281,7 +281,8 @@
 
 static PySSLSocket *
 newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
-               enum py_ssl_server_or_client socket_type)
+               enum py_ssl_server_or_client socket_type,
+               char *server_hostname)
 {
     PySSLSocket *self;
 
@@ -305,6 +306,11 @@
     SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
 #endif
 
+#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
+    if (server_hostname != NULL)
+        SSL_set_tlsext_host_name(self->ssl, server_hostname);
+#endif
+
     /* If the socket is in non-blocking mode or timeout mode, set the BIO
      * to non-blocking mode (blocking is the default)
      */
@@ -1711,16 +1717,31 @@
 static PyObject *
 context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
 {
-    char *kwlist[] = {"sock", "server_side", NULL};
+    char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
     PySocketSockObject *sock;
     int server_side = 0;
+    char *hostname = NULL;
+    PyObject *hostname_obj, *res;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
+    /* server_hostname is either None (or absent), or to be encoded
+       (if necessary) using the idna encoding */
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
                                      PySocketModule.Sock_Type,
-                                     &sock, &server_side))
-        return NULL;
+                                     &sock, &server_side,
+                                     Py_TYPE(Py_None), &hostname_obj)) {
+        PyErr_Clear();
+        if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
+            PySocketModule.Sock_Type,
+            &sock, &server_side,
+            "idna", &hostname))
+            return NULL;
+    }
 
-    return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
+    res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
+                                      hostname);
+    if (hostname != NULL)
+        PyMem_Free(hostname);
+    return res;
 }
 
 static PyObject *
@@ -2090,6 +2111,14 @@
     PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
     PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
 
+#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
+    r = Py_True;
+#else
+    r = Py_False;
+#endif
+    Py_INCREF(r);
+    PyModule_AddObject(m, "HAS_SNI", r);
+
     /* OpenSSL version */
     /* SSLeay() gives us the version of the library linked against,
        which could be different from the headers version.


More information about the Python-checkins mailing list