From c8d8173c4b06d06902c99ec010ad785a30952880 Mon Sep 17 00:00:00 2001
From: Stan Ulbrych <stan@python.org>
Date: Mon, 13 Apr 2026 02:14:54 +0100
Subject: [PATCH] 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>
---
 .../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

diff --git a/Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst b/Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst
new file mode 100644
index 00000000000000..9502189ab199c1
--- /dev/null
+++ ./Misc/NEWS.d/next/Security/2026-04-10-16-28-21.gh-issue-148395.kfzm0G.rst
@@ -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.
diff --git a/Modules/_bz2module.c b/Modules/_bz2module.c
index 9e85e0de42cd8d..055ce82e7d2863 100644
--- ./Modules/_bz2module.c
+++ b/Modules/_bz2module.c
@@ -593,6 +593,7 @@ decompress(BZ2Decompressor *d, char *data, size_t len, Py_ssize_t max_length)
     return result;
 
 error:
+    bzs->next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
diff --git a/Modules/_lzmamodule.c b/Modules/_lzmamodule.c
index 462c2181fa6036..6785dc56730c5c 100644
--- ./Modules/_lzmamodule.c
+++ b/Modules/_lzmamodule.c
@@ -1120,6 +1120,7 @@ decompress(Decompressor *d, uint8_t *data, size_t len, Py_ssize_t max_length)
     return result;
 
 error:
+    lzs->next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
index 5b6b0c5cac864a..a86aa5fdbb576c 100644
--- ./Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -1675,6 +1675,7 @@ decompress(ZlibDecompressor *self, uint8_t *data,
     return result;
 
 error:
+    self->zst.next_in = NULL;
     Py_XDECREF(result);
     return NULL;
 }
