From e100aea7aded26a49abe96c3aae2d64ef195f397 Mon Sep 17 00:00:00 2001
From: Stan Ulbrych <stan@python.org>
Date: Mon, 13 Apr 2026 02:14:54 +0100
Subject: [PATCH 1/3] gh-148395: Fix a possible UAF in
 `{LZMA,BZ2,_Zlib}Decompressor` (GH-148396)

Fix dangling input pointer after `MemoryError` in _lzma/_bz2/_ZlibDecompressor.decompress
(cherry picked from commit 8fc66aef6d7b3ae58f43f5c66f9366cc8cbbfcd2)

Co-authored-by: Stan Ulbrych <stan@python.org>
---
 Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst |    5 +++++
 Modules/_bz2module.c                                                     |    1 +
 Modules/_lzmamodule.c                                                    |    1 +
 Modules/zlibmodule.c                                                     |    1 +
 4 files changed, 8 insertions(+)
 create mode 100644 Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst

Index: Python-3.12.13/Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst
===================================================================
--- /dev/null	1970-01-01 00:00:00.000000000 +0000
+++ Python-3.12.13/Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst	2026-04-24 23:01:53.772670857 +0200
@@ -0,0 +1,5 @@
+Fix a dangling input pointer in :class:`lzma.LZMADecompressor`,
+:class:`bz2.BZ2Decompressor`, and internal :class:`!zlib._ZlibDecompressor`
+when memory allocation fails with :exc:`MemoryError`, which could let a
+subsequent :meth:`!decompress` call read or write through a stale pointer to
+the already-released caller buffer.
Index: Python-3.12.13/Modules/_bz2module.c
===================================================================
--- Python-3.12.13.orig/Modules/_bz2module.c	2026-03-03 13:39:30.000000000 +0100
+++ Python-3.12.13/Modules/_bz2module.c	2026-04-24 23:01:53.771388251 +0200
@@ -587,6 +587,7 @@
     return result;
 
 error:
+    bzs->next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
Index: Python-3.12.13/Modules/_lzmamodule.c
===================================================================
--- Python-3.12.13.orig/Modules/_lzmamodule.c	2026-03-03 13:39:30.000000000 +0100
+++ Python-3.12.13/Modules/_lzmamodule.c	2026-04-24 23:01:53.771598998 +0200
@@ -1114,6 +1114,7 @@
     return result;
 
 error:
+    lzs->next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
Index: Python-3.12.13/Modules/zlibmodule.c
===================================================================
--- Python-3.12.13.orig/Modules/zlibmodule.c	2026-03-03 13:39:30.000000000 +0100
+++ Python-3.12.13/Modules/zlibmodule.c	2026-04-24 23:01:53.771855952 +0200
@@ -1645,6 +1645,7 @@
     return result;
 
 error:
+    self->zst.next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
