Skip to contentSkip to conversation

python3-tornado: Fix CVE-2026-123535

PATCH New Yogita Urade 1 participant 3 messages Nov 24

lore
Share & tools
lore
#0 lore raw

PATCH 1/3 python3-tornado: Fix CVE-2026-123535

This patch applies the upstream fix as referenced in [4], using the commit shown in [1], [2] and [3].

[1] https://github.com/tornadoweb/tornado/commit/ab4953f1262636343bcc1875117f7a8c93d10509
[2] https://github.com/tornadoweb/tornado/commit/1fefc3d3df5146a087a2a879424adaed94f35827
[3] https://github.com/tornadoweb/tornado/commit/fb398638efcf023d09282989184c4f97c64982ca
[4] https://security-tracker.debian.org/tracker/CVE-2026-123535

---
 .../python3-tornado/CVE-2026-123535_p1.patch  | 83 +++++++++++++++++++
 .../python3-tornado/CVE-2026-123535_p2.patch  | 30 +++++++
 .../python3-tornado/CVE-2026-123535_p3.patch  | 31 +++++++
 .../python/python3-tornado_6.5.7.bb           |  3 +
 4 files changed, 147 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p3.patch
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p1.patch new file +83 -0
new file mode 100644
index 0000000000..f9ca3e0371
@@ -0,0 +1,83 @@
+From ab4953f1262636343bcc1875117f7a8c93d10509 Mon Sep 17 00:00:00 2001
+From: R0ck3t <[email protected]>
+Date: Tue, 6 Oct 2026 21:33:54 +0800
+Subject: [PATCH] set_cookie: normalize max_age through int() to prevent cookie attribute injection
+
+The max_age parameter was assigned to the cookie Morsel outside the
+attribute-allowlist validation loops (added for CVE-2026-35536 and
+CVE-2026-91991), so a non-int max_age containing ";" would inject
+arbitrary cookie attributes into the Set-Cookie header verbatim.
+Normalizing through int() rejects such values.
+
+Refs GHSA-c6v4-qj2h-f748
+
+CVE: CVE-2026-123535
+Upstream-Status: Backport [https://github.com/tornadoweb/tornado/commit/ab4953f1262636343bcc1875117f7a8c93d10509]
+
+Signed-off-by: Yogita Urade <[email protected]>
+---
+ tornado/test/web_test.py | 20 ++++++++++++++++++++
+ tornado/web.py           |  5 ++++-
+ 2 files changed, 24 insertions(+), 1 deletion(-)
+
+diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py
+index 0dba44a7..1a718488 100644
+--- a/tornado/test/web_test.py
++++ b/tornado/test/web_test.py
+@@ -381,6 +381,16 @@ class CookieTest(WebTestCase):
+             def get(self):
+                 self.set_cookie("foo", "bar", max_age=10)
+ 
++        class SetCookieMaxAgeSanitizedHandler(RequestHandler):
++            def get(self):
++                # A non-int max_age (e.g. an attacker-controlled string
++                # containing cookie attributes) is rejected instead of being
++                # written into the Set-Cookie header verbatim.
++                try:
++                    self.set_cookie("foo", "bar", max_age="86400; Path=/evil")
++                except ValueError:
++                    self.set_status(400)
++
+         class SetCookieExpiresDaysHandler(RequestHandler):
+             def get(self):
+                 self.set_cookie("foo", "bar", expires_days=10)
+@@ -405,6 +415,7 @@ class CookieTest(WebTestCase):
+             ("/forbidden_char", SetCookieForbiddenCharHandler),
+             ("/set_overwrite", SetCookieOverwriteHandler),
+             ("/set_max_age", SetCookieMaxAgeHandler),
++            ("/set_max_age_sanitized", SetCookieMaxAgeSanitizedHandler),
+             ("/set_expires_days", SetCookieExpiresDaysHandler),
+             ("/set_falsy_flags", SetCookieFalsyFlags),
+             ("/set_deprecated", SetCookieDeprecatedArgs),
+@@ -478,6 +489,15 @@ class CookieTest(WebTestCase):
+         headers = response.headers.get_list("Set-Cookie")
+         self.assertEqual(sorted(headers), ["foo=bar; Max-Age=10; Path=/"])
+ 
++    def test_set_cookie_max_age_sanitized(self):
++        # A max_age that is not a valid int could smuggle extra cookie
++        # attributes past the attribute allowlist (GHSA-c6v4-qj2h-f748);
++        # it must be rejected rather than written to the header verbatim.
++        response = self.fetch("/set_max_age_sanitized")
++        self.assertEqual(response.code, 400)
++        for header in response.headers.get_list("Set-Cookie"):
++            self.assertNotIn("evil", header)
++
+     def test_set_cookie_expires_days(self):
+         response = self.fetch("/set_expires_days")
+         header = response.headers.get("Set-Cookie")
+diff --git a/tornado/web.py b/tornado/web.py
+index a61e9594..277a7bf4 100644
+--- a/tornado/web.py
++++ b/tornado/web.py
+@@ -744,7 +744,10 @@ class RequestHandler:
+             morsel["path"] = path
+         if max_age:
+             # Note change from _ to -.
+-            morsel["max-age"] = str(max_age)
++            # Normalize through int() so that a non-int max_age (which could
++            # smuggle extra cookie attributes past the attribute allowlist)
++            # is rejected instead of being written to the header verbatim.
++            morsel["max-age"] = str(int(max_age))
+         if httponly:
+             # Note that SimpleCookie ignores the value here. The presense of an
+             # httponly (or secure) key is treated as true.
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p2.patch new file +30 -0
new file mode 100644
index 0000000000..f0d17bc2e8
@@ -0,0 +1,30 @@
+From 1fefc3d3df5146a087a2a879424adaed94f35827 Mon Sep 17 00:00:00 2001
+From: R0ck3t <[email protected]>
+Date: Tue, 6 Oct 2026 22:22:50 +0800
+Subject: [PATCH] Add type: ignore for intentionally invalid max_age in test
+
+The test deliberately passes a non-int max_age (the injection
+payload from GHSA-c6v4-qj2h-f748), which mypy rightly flags
+against the int | None signature.
+
+CVE: CVE-2026-123535
+Upstream-Status: Backport [https://github.com/tornadoweb/tornado/commit/1fefc3d3df5146a087a2a879424adaed94f35827]
+
+Signed-off-by: Yogita Urade <[email protected]>
+---
+ tornado/test/web_test.py | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py
+index 1a718488..b3bf971e 100644
+--- a/tornado/test/web_test.py
++++ b/tornado/test/web_test.py
+@@ -387,7 +387,7 @@ class CookieTest(WebTestCase):
+                 # containing cookie attributes) is rejected instead of being
+                 # written into the Set-Cookie header verbatim.
+                 try:
+-                    self.set_cookie("foo", "bar", max_age="86400; Path=/evil")
++                    self.set_cookie("foo", "bar", max_age="86400; Path=/evil")  # type: ignore[arg-type]
+                 except ValueError:
+                     self.set_status(400)
+ 
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123535_p3.patch new file +31 -0
new file mode 100644
index 0000000000..1ddf513d16
@@ -0,0 +1,31 @@
+From fb398638efcf023d09282989184c4f97c64982ca Mon Sep 17 00:00:00 2001
+From: R0ck3t <[email protected]>
+Date: Tue, 6 Oct 2026 23:46:18 +0800
+Subject: [PATCH] Shorten test line to satisfy flake8 E501 (100-char limit)
+
+Same injection payload semantics, shorter string.
+
+CVE: CVE-2026-123535
+Upstream-Status: Backport [https://github.com/tornadoweb/tornado/commit/fb398638efcf023d09282989184c4f97c64982ca]
+
+Signed-off-by: Yogita Urade <[email protected]>
+---
+ tornado/test/web_test.py | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py
+index f1ec81f2..7a8f5264 100644
+--- a/tornado/test/web_test.py
++++ b/tornado/test/web_test.py
+@@ -388,7 +388,7 @@ class CookieTest(WebTestCase):
+                 # containing cookie attributes) is rejected instead of being
+                 # written into the Set-Cookie header verbatim.
+                 try:
+-                    self.set_cookie("foo", "bar", max_age="86400; Path=/evil")  # type: ignore[arg-type]
++                    self.set_cookie("foo", "bar", max_age="1; Path=/x")  # type: ignore[arg-type]
+                 except ValueError:
+                     self.set_status(400)
+ 
+-- 
+2.35.6
+
meta-python/recipes-devtools/python/python3-tornado_6.5.7.bb +3 -0
index dd61da78be..dd72e683cf 100644
@@ -22,6 +22,9 @@ SRC_URI += "file://CVE-2026-91990.patch \
             file://CVE-2026-116578_p1.patch \
             file://CVE-2026-116578_p2.patch \
             file://CVE-2026-116578_p3.patch \
+            file://CVE-2026-123535_p1.patch \
+            file://CVE-2026-123535_p2.patch \
+            file://CVE-2026-123535_p3.patch \
 "
 
 inherit pypi python_setuptools_build_meta
Signature · 1 line
2.53.0
#1 lore raw

PATCH 2/3 python3-tornado: Fix CVE-2026-123534

This patch applies the upstream fix as referenced in [4], using the commit shown in [1], [2] and [3].

[1] https://github.com/tornadoweb/tornado/commit/6371c4b67a19766b86d0eb7c7b0c913fc37722fe
[2] https://github.com/tornadoweb/tornado/commit/2b230bf89604fa7cfaf7e1d0922aeb2ed919f3a4
[3] https://github.com/tornadoweb/tornado/commit/c433feb3b2bca6f69f9b30e98af6a66069f1edd4
[4] https://security-tracker.debian.org/tracker/CVE-2026-123534

---
 .../python3-tornado/CVE-2026-123534_p1.patch  | 268 +++++++++++
 .../python3-tornado/CVE-2026-123534_p2.patch  | 425 ++++++++++++++++++
 .../python3-tornado/CVE-2026-123534_p3.patch  |  59 +++
 .../python/python3-tornado_6.5.7.bb           |   3 +
 4 files changed, 755 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p3.patch
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p1.patch new file +268 -0
new file mode 100644
index 0000000000..b6568fb455
@@ -0,0 +1,268 @@
+From 6371c4b67a19766b86d0eb7c7b0c913fc37722fe Mon Sep 17 00:00:00 2001
+From: Claude <[email protected]>
+Date: Thu, 8 Oct 2026 11:45:42 +0000
+Subject: [PATCH] web: Validate paths in StaticFileHandler.get_version
+
+static_url() hashed whatever file get_absolute_path pointed at without
+the checks validate_absolute_path applies when serving. A path with ../
+or a symlink pointing outside the static directory would be read and
+its SHA-512 included in the URL, and a path resolving to a device such
+as /dev/zero (or a FIFO) would block the event loop indefinitely.
+
+get_version now checks that the path is inside static_path, resolves
+symlinks against allowed_symlink_directory (taken from
+static_handler_args, defaulting to the static root), and requires a
+regular file before reading it. The root and symlink-directory logic is
+factored out of validate_absolute_path so both share it.
+
+CVE: CVE-2026-123534
+Upstream-Status: Backport [https://github.com/tornadoweb/tornado/commit/6371c4b67a19766b86d0eb7c7b0c913fc37722fe]
+
+Backport Changes:
+- The Wrynose source already contains the lexical root and symlink checks
+  from its CVE-2026-116578 patches. Adapted the helper refactor to factor
+  the existing root check into _check_in_root and reuse Wrynose's
+  string-valued symlink policy in get_version.
+- Use unittest.TestCase for the new tests because tornado.test.util does
+  not provide TestCase in the target Tornado 6.5.7 source.
+- Keep the existing POSIX-only skip decorator on StaticFileMultiRootTest
+  and add a separate decorator for StaticFileVersionPathTest.
+
+Co-Authored-By: Claude Opus 5.5 <[email protected]>
+Claude-Session: https://claude.ai/code/session_019nvEV873ZwBncgxPP13Xfd
+Signed-off-by: Yogita Urade <[email protected]>
+---
+ tornado/test/web_test.py | 87 ++++++++++++++++++++++++++++++++++++++++++++++++
+ tornado/web.py           | 86 ++++++++++++++++++++++++++++----------
+ 2 files changed, 152 insertions(+), 21 deletions(-)
+
+diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py
+index 0dba44a7..ce6e09ef 100644
+--- a/tornado/test/web_test.py
++++ b/tornado/test/web_test.py
+@@ -49,6 +49,7 @@ import copy
+ import datetime
+ import email.utils
+ import gzip
++import hashlib
+ from io import BytesIO
+ import itertools
+ import logging
+@@ -1729,6 +1730,92 @@ class MultiRootStaticFileHandler(StaticFileHandler):
+ 
+ 
[email protected](os.name != "posix", "non-posix OS")
++class StaticFileVersionPathTest(unittest.TestCase):
++    """``get_version`` (used by ``static_url``) must apply the same path
++    checks as serving the file, so that it never reads, or leaks a hash of,
++    anything outside the static directory.
++    """
++
++    def setUp(self):
++        self.tmpdir = tempfile.mkdtemp()
++        self.addCleanup(shutil.rmtree, self.tmpdir)
++        self.root = os.path.join(self.tmpdir, "static")
++        self.outside = os.path.join(self.tmpdir, "outside")
++        os.mkdir(self.root)
++        os.mkdir(self.outside)
++        with open(os.path.join(self.root, "inside.txt"), "w", encoding="utf-8") as f:
++            f.write("inside")
++        with open(os.path.join(self.outside, "secret.txt"), "w", encoding="utf-8") as f:
++            f.write("secret")
++        os.symlink(
++            os.path.join(self.outside, "secret.txt"),
++            os.path.join(self.root, "link.txt"),
++        )
++        os.symlink(
++            os.path.join(self.root, "inside.txt"),
++            os.path.join(self.root, "internal.txt"),
++        )
++        StaticFileHandler.reset()
++        self.addCleanup(StaticFileHandler.reset)
++        super().setUp()
++
++    def get_version(self, path, **static_handler_args):
++        settings = dict(static_path=self.root)
++        if static_handler_args:
++            settings["static_handler_args"] = static_handler_args
++        return StaticFileHandler.get_version(settings, path)
++
++    def test_regular_file(self):
++        self.assertEqual(
++            self.get_version("inside.txt"), hashlib.sha512(b"inside").hexdigest()
++        )
++
++    def test_symlink_within_root(self):
++        self.assertEqual(
++            self.get_version("internal.txt"), hashlib.sha512(b"inside").hexdigest()
++        )
++
++    def test_traversal(self):
++        with ExpectLog(gen_log, "Could not open static file"):
++            self.assertIsNone(self.get_version("../outside/secret.txt"))
++
++    def test_symlink_escaping_root(self):
++        with ExpectLog(gen_log, "Could not open static file"):
++            self.assertIsNone(self.get_version("link.txt"))
++
++    def test_allowed_symlink_directory(self):
++        # static_handler_args configures the handler that will serve the
++        # file, so get_version honors its allowed_symlink_directory too.
++        self.assertEqual(
++            self.get_version("link.txt", allowed_symlink_directory=self.tmpdir),
++            hashlib.sha512(b"secret").hexdigest(),
++        )
++
++    def test_allowed_symlink_directory_does_not_allow_traversal(self):
++        with ExpectLog(gen_log, "Could not open static file"):
++            self.assertIsNone(
++                self.get_version(
++                    "../outside/secret.txt", allowed_symlink_directory=self.tmpdir
++                )
++            )
++
++    @unittest.skipIf(not os.path.exists("/dev/zero"), "no /dev/zero")
++    def test_device_file(self):
++        # Hashing /dev/zero would never finish. Reach it through a symlink
++        # that is explicitly allowed, so that only the regular-file check
++        # stands in the way.
++        os.symlink("/dev/zero", os.path.join(self.root, "zero"))
++        with ExpectLog(gen_log, "Could not open static file"):
++            self.assertIsNone(self.get_version("zero", allowed_symlink_directory="/"))
++
++    def test_fifo(self):
++        # Opening a FIFO with no writer would block forever.
++        os.mkfifo(os.path.join(self.root, "fifo"))
++        with ExpectLog(gen_log, "Could not open static file"):
++            self.assertIsNone(self.get_version("fifo"))
++
++
+ @unittest.skipIf(os.name != "posix", "non-posix OS")
+ class StaticFileMultiRootTest(WebTestCase):
+     """Subclasses that search several directories and never set
+     ``allowed_symlink_directory`` must keep working (issue #3724).
+diff --git a/tornado/web.py b/tornado/web.py
+index a61e9594..b4c18113 100644
+--- a/tornado/web.py
++++ b/tornado/web.py
+@@ -3028,22 +3028,7 @@ class StaticFileHandler(RequestHandler):
+ 
+         .. versionadded:: 3.1
+         """
+-        # os.path.abspath strips a trailing /.
+-        # We must add it back to `root` so that we only match files
+-        # in a directory named `root` instead of files starting with
+-        # that prefix.
+-        root = os.path.abspath(root)
+-        if not root.endswith(os.path.sep):
+-            # abspath always removes a trailing slash, except when
+-            # root is '/'. This is an unusual case, but several projects
+-            # have independently discovered this technique to disable
+-            # Tornado's path validation and (hopefully) do their own,
+-            # so we need to support it.
+-            root += os.path.sep
+-        # The trailing slash also needs to be temporarily added back
+-        # the requested path so a request to root/ will match.
+-        if not (absolute_path + os.path.sep).startswith(root):
+-            raise HTTPError(403, "%s is not in root static directory", self.path)
++        root = self._check_in_root(root, absolute_path, self.path)
+         # Symlinks may point anywhere inside allowed_symlink_directory, which
+         # defaults to the directory being served. Resolve that default here,
+         # against the same root the checks above used, rather than in
+@@ -3103,6 +3088,32 @@ class StaticFileHandler(RequestHandler):
+         self._stat_result = stat_result
+         return absolute_path
+ 
++    @staticmethod
++    def _check_in_root(root: str, absolute_path: str, path_message: str) -> str:
++        """Checks that ``absolute_path`` (as written) is inside ``root``.
++
++        Returns the normalized root, with a trailing separator. Raises
++        `HTTPError` (403) if the path is outside of it. ``path_message``
++        is used only to build the error message.
++        """
++        # os.path.abspath strips a trailing /.
++        # We must add it back to `root` so that we only match files
++        # in a directory named `root` instead of files starting with
++        # that prefix.
++        root = os.path.abspath(root)
++        if not root.endswith(os.path.sep):
++            # abspath always removes a trailing slash, except when
++            # root is '/'. This is an unusual case, but several projects
++            # have independently discovered this technique to disable
++            # Tornado's path validation and (hopefully) do their own,
++            # so we need to support it.
++            root += os.path.sep
++        # The trailing slash also needs to be temporarily added back
++        # the requested path so a request to root/ will match.
++        if not (absolute_path + os.path.sep).startswith(root):
++            raise HTTPError(403, "%s is not in root static directory", path_message)
++        return root
++
+     @staticmethod
+     def _resolve_symlink_target(
+         absolute_path: str, allowed_symlink_directory: str, path_message: str
+@@ -3346,7 +3357,7 @@ class StaticFileHandler(RequestHandler):
+         return url_path
+ 
+     @classmethod
+-    def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
++    def get_version(cls, settings: dict[str, Any], path: str) -> str | None:
+         """Generate the version string to be used in static URLs.
+ 
+         ``settings`` is the `Application.settings` dictionary and ``path``
+@@ -3358,17 +3369,50 @@ class StaticFileHandler(RequestHandler):
+            This method was previously recommended for subclasses to override;
+            `get_content_version` is now preferred as it allows the base
+            class to handle caching of the result.
++
++        .. versionchanged:: 6.6
++           Paths outside ``static_path`` (including symlinks that point
++           outside of ``allowed_symlink_directory`` as configured in
++           ``static_handler_args``) and paths that are not regular files
++           are no longer read, and get no version.
+         """
+-        abs_path = cls.get_absolute_path(settings["static_path"], path)
+-        return cls._get_cached_version(abs_path)
++        root = settings["static_path"]
++        abs_path = cls.get_absolute_path(root, path)
++        allowed_symlink_directory = settings.get("static_handler_args", {}).get(
++            "allowed_symlink_directory"
++        )
++
++        def validate() -> str:
++            # The same checks validate_absolute_path applies when the file is
++            # served. Without them, static_url() would read (and leak a hash
++            # of) any file on the system named with ../ or reached through a
++            # symlink, and a path like /dev/zero would hang the event loop.
++            checked_root = cls._check_in_root(root, abs_path, path)
++            resolved_path = cls._resolve_symlink_target(
++                abs_path, allowed_symlink_directory or checked_root, path
++            )
++            if not stat.S_ISREG(os.stat(resolved_path).st_mode):
++                raise HTTPError(403, "%s is not a file", path)
++            return resolved_path
++
++        return cls._get_cached_version(abs_path, validate)
+ 
+     @classmethod
+-    def _get_cached_version(cls, abs_path: str) -> Optional[str]:
++    def _get_cached_version(
++        cls, abs_path: str, validate: Callable[[], str] | None = None
++    ) -> str | None:
++        """Returns the (cached) version of the file at ``abs_path``.
++
++        ``validate``, if given, is called before the file is first read; it
++        returns the path to read or raises if the file must not be read.
++        Callers that have already validated ``abs_path`` may omit it.
++        """
+         with cls._lock:
+             hashes = cls._static_hashes
+             if abs_path not in hashes:
+                 try:
+-                    hashes[abs_path] = cls.get_content_version(abs_path)
++                    content_path = abs_path if validate is None else validate()
++                    hashes[abs_path] = cls.get_content_version(content_path)
+                 except Exception:
+                     gen_log.error("Could not open static file %r", abs_path)
+                     hashes[abs_path] = None
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p2.patch new file +425 -0

425 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-tornado/CVE-2026-123534_p3.patch new file +59 -0

59 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-tornado_6.5.7.bb +3 -0
index dd72e683cf..3a131fc382 100644
@@ -25,6 +25,9 @@ SRC_URI += "file://CVE-2026-91990.patch \
             file://CVE-2026-123535_p1.patch \
             file://CVE-2026-123535_p2.patch \
             file://CVE-2026-123535_p3.patch \
+            file://CVE-2026-123534_p1.patch \
+            file://CVE-2026-123534_p2.patch \
+            file://CVE-2026-123534_p3.patch \
 "
 
 inherit pypi python_setuptools_build_meta
Signature · 1 line
2.53.0
#2 lore raw

PATCH 3/3 python3-tornado: Fix CVE-2026-126347

In reply to Yogita Urade

This patch applies the upstream fix as referenced in [2], using the commit shown in [1].

[1] https://github.com/tornadoweb/tornado/commit/c503241622c0efe7c40110d89834ce8b7fead1e4
[2] https://ubuntu.com/security/CVE-2026-126347

---
 .../python3-tornado/CVE-2026-126347.patch     | 220 ++++++++++++++++++
 .../python/python3-tornado_6.5.7.bb           |   1 +
 2 files changed, 221 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-tornado/CVE-2026-126347.patch
meta-python/recipes-devtools/python/python3-tornado/CVE-2026-126347.patch new file +220 -0
new file mode 100644
index 0000000000..fb53985fcf
@@ -0,0 +1,220 @@
+From c503241622c0efe7c40110d89834ce8b7fead1e4 Mon Sep 17 00:00:00 2001
+From: Claude <[email protected]>
+Date: Thu, 29 Oct 2026 19:34:37 +0000
+Subject: [PATCH] web: Fix RedirectHandler open redirect with three or more leading slashes
+
+The scheme/netloc check added in 6.6.0 used urlsplit, which follows RFC
+3986 and sees an empty netloc in "///example.com". Browsers follow the
+WHATWG URL spec, which skips any run of slashes (and backslashes) before
+the host when resolving against an http or https URL, so a template like
+"/{0}" or "/{0}/b" could still be used as an open redirect with a request
+like "/a///example.com/". Collapse leading slash runs before comparing.
+
+Collapsing slashes is not enough on its own, because the expected scheme
+and netloc came from formatting the template with "/" as a placeholder,
+which turns "/{0}/b" into "///b". Instead, take the expected scheme and
+netloc from the part of the template before the first substitution. This
+also fixes a regression in 6.6.0, in which templates like "/{0}.html"
+rejected every request (the placeholder made "//.html").
+
+Also reject templates whose host would come entirely from a substitution
+(such as "https://{0}" or "https:{0}"), which 6.6.0 intended to reject
+but which could get through with extra slashes, and run the check after
+query arguments are appended, since url_concat can change the URL (on
+some Python versions it turns "https:host" into "https:///host").
+Redirect URLs that url_concat cannot parse, or that contain characters
+not allowed in a header, now get a 400 instead of a 500.
+
+CVE: CVE-2026-126347
+Upstream-Status: Backport [https://github.com/tornadoweb/tornado/commit/c503241622c0efe7c40110d89834ce8b7fead1e4]
+
+Co-Authored-By: Claude Opus 5.5 <[email protected]>
+Claude-Session: https://claude.ai/code/session_01VamvWqdwiBTCFwhDLCbBee
+Signed-off-by: Yogita Urade <[email protected]>
+---
+ tornado/test/web_test.py | 80 +++++++++++++++++++++++++++++++++++++++-
+ tornado/web.py           | 49 +++++++++++++++++-------
+ 2 files changed, 115 insertions(+), 14 deletions(-)
+
+diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py
+index 1b6ad2b0..f1ec81f2 100644
+--- a/tornado/test/web_test.py
++++ b/tornado/test/web_test.py
+@@ -3789,6 +3789,9 @@ class RedirectHandlerTest(WebTestCase):
+             ("/src2", WebRedirectHandler, {"url": "/dst2?foo=bar"}),
+             (r"/any/(.*)", WebRedirectHandler, {"url": "{0}"}),
+             (r"/moved(.*)", WebRedirectHandler, {"url": "https://example.com{0}"}),
++            (r"/(.*)/target", WebRedirectHandler, {"url": "/{0}/destination"}),
++            (r"/hostless/(.*)", WebRedirectHandler, {"url": "https://{0}"}),
++            (r"/schemeonly/(.*)", WebRedirectHandler, {"url": "https:{0}"}),
+             (r"/(.*?)/(.*?)/(.*)", WebRedirectHandler, {"url": "/{1}/{0}/{2}"}),
+         ]
+ 
+@@ -3827,7 +3830,81 @@ class RedirectHandlerTest(WebTestCase):
+         # Browsers treat backslashes like slashes and ignore tabs and newlines,
+         # so these variants are also protocol-relative. Path arguments are
+         # url-decoded, so they can be smuggled in with percent-encoding.
+-        for path in ["/a/%5Cexample.com/b", "/a/%09/example.com/b"]:
++        # Browsers also skip any number of slashes before the host, so three
++        # or more slashes are just as protocol-relative as two.
++        for path in [
++            "/a/%5Cexample.com/b",
++            "/a/%09/example.com/b",
++            "/a///example.com/b",
++            "/a////example.com/b",
++            "/a/%2F%2F%5Cexample.com/b",
++        ]:
++            with self.subTest(path=path):
++                with ExpectLog(
++                    gen_log, ".*Redirect URL cannot change the scheme or netloc"
++                ):
++                    response = self.fetch(path, follow_redirects=False)
++                self.assertEqual(response.code, 400)
++
++    def test_substitution_after_first_slash(self):
++        # The substitution comes right after the first slash, so it can add a
++        # second slash (or more) but that must not reject ordinary values.
++        for path, location in [
++            ("/ok/target", "/ok/destination"),
++            ("/a/b/target", "/a/b/destination"),
++            ("/ok/target?x=1", "/ok/destination?x=1"),
++        ]:
++            with self.subTest(path=path):
++                response = self.fetch(path, follow_redirects=False)
++                self.assertEqual(response.code, 301)
++                self.assertEqual(response.headers["Location"], location)
++        for path in [
++            "/%2Fevil.com/target",
++            "/%2F%2Fevil.com/target",
++            "/%5C%5Cevil.com/target",
++            "/%09//evil.com/target",
++            "/%2Fevil.com/target?x=1",
++        ]:
++            with self.subTest(path=path):
++                with ExpectLog(
++                    gen_log, ".*Redirect URL cannot change the scheme or netloc"
++                ):
++                    response = self.fetch(path, follow_redirects=False)
++                self.assertEqual(response.code, 400)
++
++    def test_invalid_characters(self):
++        # These would otherwise be a 500 error from set_header.
++        for path in ["/any/%0Afoo", "/any/a%00b", "/any/%2F%2F%5B?x=1"]:
++            with self.subTest(path=path):
++                with ExpectLog(gen_log, ".*Redirect URL (contains invalid|cannot)"):
++                    response = self.fetch(path, follow_redirects=False)
++                self.assertEqual(response.code, 400)
++
++    def test_non_ascii(self):
++        # Non-ASCII characters (including ones that look like slashes) are
++        # fine, and are sent as UTF-8.
++        for value in ["\u00e9", "\u4e2d\u6587", "\uff0f\uff0fexample.com"]:
++            with self.subTest(value=value):
++                response = self.fetch(
++                    "/any/" + urllib.parse.quote(value), follow_redirects=False
++                )
++                self.assertEqual(response.code, 301)
++                # Header values are decoded as latin1.
++                self.assertEqual(
++                    response.headers["Location"], utf8(value).decode("latin1")
++                )
++
++    def test_substitution_in_host(self):
++        # Substitutions cannot supply the host, even with extra slashes
++        # (which urlsplit and browsers disagree about) or a query string
++        # (which some versions of urlunsplit turn into extra slashes).
++        for path in [
++            "/hostless/evil.com",
++            "/hostless//evil.com",
++            "/schemeonly/evil.com",
++            "/schemeonly/evil.com?x=1",
++            "/schemeonly////evil.com",
++        ]:
+             with self.subTest(path=path):
+                 with ExpectLog(
+                     gen_log, ".*Redirect URL cannot change the scheme or netloc"
+@@ -3856,6 +3933,7 @@ class RedirectHandlerTest(WebTestCase):
+         for path in [
+             "/any/https://evil.com/",
+             "/any/%5C%5Cevil.com/",
++            "/any////evil.com/",
+             "/any/javascript:alert(1)",
+         ]:
+             with self.subTest(path=path):
+diff --git a/tornado/web.py b/tornado/web.py
+index 0609b4f0..6e6725f0 100644
+--- a/tornado/web.py
++++ b/tornado/web.py
+@@ -73,6 +73,7 @@ import os.path
+ import re
+ import socket
+ import stat
++import string
+ import sys
+ import threading
+ import time
+@@ -2713,23 +2714,40 @@ class RedirectHandler(RequestHandler):
+     def get(self, *args: Any, **kwargs: Any) -> None:
+         to_url = self._url.format(*args, **kwargs)
+         # The scheme and netloc of the redirect must come from the template, not
+-        # from the request. Find out what they are by formatting the template
+-        # with a placeholder that cannot extend a scheme or netloc.
+-        expected_url = self._url.format(
+-            *("/" for _ in args), **{k: "/" for k in kwargs}
+-        )
++        # from the request. Find out what they are from the part of the template
++        # before the first substitution. (Formatting the whole template with a
++        # placeholder doesn't work: whatever the placeholder is, it can turn the
++        # template into a URL with a different netloc, as "/" does for "/{0}/b".)
++        prefix = ""
++        has_substitution = False
++        for literal, field, _, _ in string.Formatter().parse(self._url):
++            prefix += literal
++            if field is not None:
++                has_substitution = True
++                break
+         try:
+-            unchanged = _scheme_and_netloc(to_url) == _scheme_and_netloc(expected_url)
++            if self.request.query_arguments:
++                # Query arguments are added before the check because url_concat
++                # can change the rest of the URL.
++                # TODO: figure out typing for the next line.
++                to_url = httputil.url_concat(
++                    to_url,
++                    list(httputil.qs_to_qsl(self.request.query_arguments)),  # type: ignore
++                )
++            scheme, netloc = _scheme_and_netloc(prefix)
++            unchanged = _scheme_and_netloc(to_url) == (scheme, netloc)
++            if has_substitution and scheme in ("http", "https") and not netloc:
++                # The host would come entirely from a substitution (or a
++                # browser would find one where urlsplit doesn't, as in
++                # "https:///host").
++                unchanged = False
+         except ValueError:
+             unchanged = False
+         if not unchanged:
+             raise HTTPError(400, "Redirect URL cannot change the scheme or netloc")
+-        if self.request.query_arguments:
+-            # TODO: figure out typing for the next line.
+-            to_url = httputil.url_concat(
+-                to_url,
+-                list(httputil.qs_to_qsl(self.request.query_arguments)),  # type: ignore
+-            )
++        if httputil._FORBIDDEN_HEADER_CHARS_RE.search(to_url):
++            # Let this be a 400 rather than a 500 from set_header.
++            raise HTTPError(400, "Redirect URL contains invalid characters")
+         self.redirect(to_url, permanent=self._permanent)
+ 
+ 
+@@ -4067,5 +4085,10 @@ def _scheme_and_netloc(url: str) -> tuple[str, str]:
+     Both are empty for a relative URL. Raises `ValueError` for some malformed
+     URLs.
+     """
+-    parts = urllib.parse.urlsplit(_normalize_url_like_browser(url))
++    url = _normalize_url_like_browser(url)
++    # urlsplit follows RFC 3986, in which "///example.com" has an empty netloc,
++    # but browsers resolving it against an http or https URL skip any number of
++    # slashes before the host. Collapse them so urlsplit sees the same host.
++    url = re.sub(r"^//+", "//", url)
++    parts = urllib.parse.urlsplit(url)
+     return parts.scheme.lower(), parts.netloc.lower()
meta-python/recipes-devtools/python/python3-tornado_6.5.7.bb +1 -0
index 3a131fc382..a4fe5b7d07 100644
@@ -28,6 +28,7 @@ SRC_URI += "file://CVE-2026-91990.patch \
             file://CVE-2026-123534_p1.patch \
             file://CVE-2026-123534_p2.patch \
             file://CVE-2026-123534_p3.patch \
+            file://CVE-2026-126347.patch \
 "
 
 inherit pypi python_setuptools_build_meta
Signature · 1 line
2.53.0