
From b338d8cee138c2fd98f788ec295f8f2f719f53c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= <bgabor8@bloomberg.net>
Date: Fri, 9 Jan 2026 09:49:49 -0800
Subject: [PATCH] fix: resolve TOCTOU vulnerabilities in app_data and lock
 directory creation
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Use atomic os.makedirs(..., exist_ok=True) operations instead of
check-then-act pattern to prevent symlink-based TOCTOU attacks.

Reported by: tsigouris007

Signed-off-by: Bernát Gábor <bgabor8@bloomberg.net>
---
 docs/changelog/3013.bugfix.rst      |  1 +
 src/virtualenv/app_data/__init__.py | 11 +++++------
 src/virtualenv/util/lock.py         |  7 +++----
 3 files changed, 9 insertions(+), 10 deletions(-)
 create mode 100644 docs/changelog/3013.bugfix.rst

diff --git a/src/virtualenv/app_data/__init__.py b/src/virtualenv/app_data/__init__.py
index d7f148023..7a9d38e92 100644
--- a/src/virtualenv/app_data/__init__.py
+++ b/src/virtualenv/app_data/__init__.py
@@ -36,12 +36,11 @@ def make_app_data(folder, **kwargs):
     if is_read_only:
         return ReadOnlyAppData(folder)
 
-    if not os.path.isdir(folder):
-        try:
-            os.makedirs(folder)
-            LOGGER.debug("created app data folder %s", folder)
-        except OSError as exception:
-            LOGGER.info("could not create app data folder %s due to %r", folder, exception)
+    try:
+        os.makedirs(folder, exist_ok=True)
+        LOGGER.debug("created app data folder %s", folder)
+    except OSError as exception:
+        LOGGER.info("could not create app data folder %s due to %r", folder, exception)
 
     if os.access(folder, os.W_OK):
         return AppDataDiskFolder(folder)
diff --git a/src/virtualenv/util/lock.py b/src/virtualenv/util/lock.py
index b250e032f..82c8eed65 100644
--- a/src/virtualenv/util/lock.py
+++ b/src/virtualenv/util/lock.py
@@ -17,9 +17,8 @@
 class _CountedFileLock(FileLock):
     def __init__(self, lock_file) -> None:
         parent = os.path.dirname(lock_file)
-        if not os.path.isdir(parent):
-            with suppress(OSError):
-                os.makedirs(parent)
+        with suppress(OSError):
+            os.makedirs(parent, exist_ok=True)
 
         super().__init__(lock_file)
         self.count = 0
@@ -117,7 +116,7 @@ def _lock_file(self, lock, no_block=False):  # noqa: FBT002
         # a lock, but that lock might then become expensive, and it's not clear where that lock should live.
         # Instead here we just ignore if we fail to create the directory.
         with suppress(OSError):
-            os.makedirs(str(self.path))
+            os.makedirs(str(self.path), exist_ok=True)
 
         try:
             lock.acquire(0.0001)
