]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Disable cross origin websockets by default.
authorKyle Kelley <kyle.kelley@rackspace.com>
Fri, 24 Jan 2014 05:25:44 +0000 (23:25 -0600)
committerKyle Kelley <kyle.kelley@rackspace.com>
Thu, 8 May 2014 18:40:28 +0000 (13:40 -0500)
tornado/websocket.py

index 66a4fedf9df6c67c67dd7d3edb933b2604ec5a91..fc61c2f6779068a7744cdbff9f5db8e28233580e 100644 (file)
@@ -41,6 +41,11 @@ from tornado.netutil import Resolver
 from tornado import simple_httpclient
 from tornado.util import bytes_type, unicode_type
 
+try:
+    from urllib.parse import urlparse # py2
+except ImportError:
+    from urlparse import urlparse # py3
+
 try:
     xrange  # py2
 except NameError:
@@ -156,6 +161,32 @@ class WebSocketHandler(tornado.web.RequestHandler):
                 "Sec-WebSocket-Version: 8\r\n\r\n"))
             self.stream.close()
 
+        # Assume cross origin is disallowed by default, while allowing users to
+        # choose
+        if kwargs.get('allow_cross_origin', False):
+            pass
+        # Check that the host and origin match
+        elif not self.same_origin():
+            self.stream.write(tornado.escape.utf8(
+                "HTTP/1.1 403 Cross Origin Websockets Disabled\r\n\r\n"
+            ))
+            self.stream.close()
+
+    def same_origin(self):
+        """Check to see that origin and host match in the headers."""
+        origin_header = self.request.headers.get("Origin")
+        host = self.request.headers.get("Host")
+
+        # If no header is provided, assume we can't verify origin
+        if(origin_header is None or host is None):
+            return False
+
+        parsed_origin = urlparse(origin_header)
+        origin = parsed_origin.netloc
+
+        # Check to see that origin matches host directly, including ports
+        return origin == host
+
     def write_message(self, message, binary=False):
         """Sends the given message to the client of this Web Socket.