Repository navigation
mkdtemp() created directories no longer allows for writing files when running under a Windows AppContainer in 3.12.4 (but works under 3.12.3) #134587
Description
Bug report
Bug description:
Using the StartAppContainer c++ code at the bottom of this report, build the StartAppContainer.exe.
Grab both the 3.12.3 and 3.12.4 embedded distributions of python.
Use this python code:
import tempfile
import os
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
file_path = os.path.join(temp_dir, "tempfile.txt")
content_to_write = "Hello, this is a test."
# Create and write to a file inside the temporary directory
with open(file_path, 'w') as f:
f.write(content_to_write)
# Read the content back to verify
with open(file_path, 'r') as f:
content_read = f.read()
# Verify the content
if content_read == content_to_write:
print("Success: Content verified.")
else:
print("Error: Content does not match.")in a test_temp.py file.
Then from a command line run:
StartAppContainer --grant-read "C:\code\python-3.12.3-embed-amd64" --grant-read "C:\Code\test_temp.py" "C:\code\python-3.12.3-embed-amd64\python.exe" "C:\code\test_temp.py"
and see it works. But run
StartAppContainer --grant-read "C:\code\python-3.12.4-embed-amd64" --grant-read "C:\Code\test_temp.py" "C:\code\python-3.12.4-embed-amd64\python.exe" "C:\code\test_temp.py"
and see it fails with
Traceback (most recent call last):
File "C:\code\test_temp.py", line 11, in <module>
with open(file_path, 'w') as f:
^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\UserName\\AppData\\Local\\Packages\\testpythonappcontainer\\AC\\Temp\\tmp2sy87dk4\\tempfile.txt'
As seen in the error, AppContainer processes get their temp files redirected to %LOCALAPPDATA%\Packages\[PackageName]\AC\Temp. When an AppContainer gets created by the system, %LOCALAPPDATA%\Packages\[PackageName]\AC is explicitly ACL-ed to allow Inherited Full Control of the SID associated with the AppContainer.
I believe this is because of the changes associated with #118486 where the temp directory created with 700 is explicitly no longer inheriting the permissions from their parent.
Is it possible to grab the SID of the process' AppContainer (if any) and append that SID with Full Control to the SDDL being set as the security descriptor on the temp directory?
StartAppContainer.cpp code:
#include <windows.h>
#include <userenv.h>
#include <sddl.h>
#include <iostream>
#include <string>
#include <vector>
#include <aclapi.h>
#pragma comment(lib, "userenv.lib")
#pragma comment(lib, "advapi32.lib")
bool CreateAppContainerSid(const std::wstring& name, PSID* appContainerSid) {
HRESULT hr = CreateAppContainerProfile(name.c_str(), name.c_str(), L"Test AppContainer Profile", nullptr, 0, appContainerSid);
if (FAILED(hr)) {
HRESULT hr = DeriveAppContainerSidFromAppContainerName(name.c_str(), appContainerSid);
if (FAILED(hr)) {
std::wcerr << L"Failed to derive AppContainer SID. Creating profile..." << std::endl;
return false;
}
else
{
std::wcout << L"AppContainer SID derived successfully." << std::endl;
}
}
else
{
std::wcout << L"AppContainer profile created successfully." << std::endl;
}
return true;
}
bool CreatePipes(HANDLE& readOut, HANDLE& writeOut) {
SECURITY_ATTRIBUTES saAttr = {};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = nullptr;
if (!CreatePipe(&readOut, &writeOut, &saAttr, 0)) {
std::cerr << "Stdout pipe creation failed\n";
return false;
}
if (!SetHandleInformation(readOut, HANDLE_FLAG_INHERIT, 0)) {
std::cerr << "Stdout SetHandleInformation failed\n";
return false;
}
return true;
}
void ReadFromPipe(HANDLE readHandle) {
CHAR buffer[4096];
DWORD bytesRead;
while (ReadFile(readHandle, buffer, sizeof(buffer) - 1, &bytesRead, nullptr) && bytesRead > 0) {
buffer[bytesRead] = '\0';
std::cout << buffer;
}
}
bool GrantAccessToPathForAppContainer(const std::wstring& path, PSID appContainerSid, DWORD accessMask) {
EXPLICIT_ACCESSW ea = {};
ea.grfAccessPermissions = accessMask;
ea.grfAccessMode = GRANT_ACCESS;
ea.grfInheritance = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ea.Trustee.pMultipleTrustee = nullptr;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea.Trustee.ptstrName = (LPWSTR)appContainerSid;
PACL oldDacl = nullptr, newDacl = nullptr;
PSECURITY_DESCRIPTOR sd = nullptr;
DWORD result = GetNamedSecurityInfoW(
path.c_str(), SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
nullptr, nullptr, &oldDacl, nullptr, &sd);
if (result != ERROR_SUCCESS) {
std::wcerr << L"Failed to get security info for: " << path << L" Error: " << result << "\n";
return false;
}
result = SetEntriesInAclW(1, &ea, oldDacl, &newDacl);
if (result != ERROR_SUCCESS) {
std::wcerr << L"SetEntriesInAclW failed: " << result << "\n";
if (sd) LocalFree(sd);
return false;
}
result = SetNamedSecurityInfoW(
(LPWSTR)path.c_str(), SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
nullptr, nullptr, newDacl, nullptr);
if (result != ERROR_SUCCESS) {
std::wcerr << L"SetNamedSecurityInfoW failed: " << result << "\n";
}
std::wcout << "Updated ACL for " << path << L" with AppContainer SID\n";
if (sd) LocalFree(sd);
if (newDacl) LocalFree(newDacl);
return result == ERROR_SUCCESS;
}
std::wstring GetLastErrorMessage(DWORD errorCode = GetLastError()) {
LPWSTR buffer = nullptr;
DWORD size = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&buffer,
0,
nullptr);
std::wstring message(buffer, size);
LocalFree(buffer);
return message;
}
int wmain(int argc, wchar_t* argv[]) {
if (argc < 2) {
std::wcerr << L"Usage: AppContainerLauncher.exe <command line>\n";
return 1;
}
std::vector<std::pair<std::wstring, DWORD>> accessRequests;
std::vector<std::wstring> commandParts;
std::wstring appExe;
for (int i = 1; i < argc; ++i) {
std::wstring arg = argv[i];
if (arg == L"--grant-read" && i + 1 < argc) {
accessRequests.emplace_back(argv[++i], FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | GENERIC_READ | GENERIC_EXECUTE);
}
else if (arg == L"--grant-write" && i + 1 < argc) {
accessRequests.emplace_back(argv[++i], FILE_ALL_ACCESS | GENERIC_ALL);
}
else {
commandParts.emplace_back(arg);
}
}
if (commandParts.empty()) {
std::wcerr << L"No command provided.\n";
return 1;
}
std::wstring commandLine;
for (const auto& part : commandParts) {
commandLine += part + L" ";
}
if (commandParts.size() > 0)
appExe = commandParts[0];
std::wstring containerName = L"TestPythonAppContainer";
PSID appContainerSid = nullptr;
if (!CreateAppContainerSid(containerName, &appContainerSid)) {
return 1;
}
for (const auto& p : accessRequests) {
GrantAccessToPathForAppContainer(p.first, appContainerSid, p.second);
}
HANDLE readOut, writeOut;
if (!CreatePipes(readOut, writeOut)) {
return 1;
}
STARTUPINFOEXW siex = {};
PROCESS_INFORMATION pi = {};
SIZE_T attrListSize = 0;
InitializeProcThreadAttributeList(nullptr, 2, 0, &attrListSize);
siex.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attrListSize);
if (!InitializeProcThreadAttributeList(siex.lpAttributeList, 2, 0, &attrListSize)) {
std::cerr << "InitializeProcThreadAttributeList failed\n";
return 1;
}
SECURITY_CAPABILITIES sc = { };
sc.AppContainerSid = appContainerSid;
sc.Capabilities = nullptr;
sc.CapabilityCount = 0;
sc.Reserved = 0;
if (!UpdateProcThreadAttribute(siex.lpAttributeList, 0,
PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
&sc,
sizeof(SECURITY_CAPABILITIES), nullptr, nullptr)) {
std::cerr << "UpdateProcThreadAttribute failed\n";
return 1;
}
HANDLE inheritHandles[] = { writeOut }; // Only pass the write end to the child
if (!UpdateProcThreadAttribute(siex.lpAttributeList, 0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inheritHandles,
sizeof(inheritHandles), nullptr, nullptr)) {
std::cerr << "UpdateProcThreadAttribute failed\n";
return 1;
}
siex.StartupInfo.cb = sizeof(siex);
siex.StartupInfo.hStdOutput = writeOut;
siex.StartupInfo.hStdError = writeOut;
siex.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
BOOL success = CreateProcessW(
nullptr,
&commandLine[0],
nullptr,
nullptr,
TRUE,
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW,
nullptr,
nullptr,
&siex.StartupInfo,
&pi
);
CloseHandle(writeOut); // The child process now owns the write end
if (!success) {
DWORD err = GetLastError();
std::wcerr << L"CreateProcess failed (" << err << L"): " << GetLastErrorMessage(err) << "\n";
return 1;
}
ReadFromPipe(readOut);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(readOut);
if (appContainerSid) {
FreeSid(appContainerSid);
}
DeleteProcThreadAttributeList(siex.lpAttributeList);
HeapFree(GetProcessHeap(), 0, siex.lpAttributeList);
return 0;
}CPython versions tested on:
3.12
Operating systems tested on:
Windows
Activity
alervd commentedon Nov 14, 2025
We're affected too. Any plans on fixing this issue?
DiPaolo commentedon Mar 31, 2026
Same for me. We use pytest's basetemp. And the behavior is the same: newly created directory has no appropriate rights for writing. All the same works well with python 3.11.9
Regular python's mkdir() has the same invalid behavior - no access.
pythongh-134587: Fix os.mkdir(mode=0o700) in Windows AppContainer
fix(package): install through uv on Windows, and stop install() hangi…
test(sandbox): ask uv what it could not open, instead of guessing again
fix(package): pin managed Windows Python to 3.12.3 and drop uv from t…
fix(package): choose an interpreter the sandbox can actually install …
fix(package): rebuild an environment whose interpreter cannot install
fix(windows): make the AppContainer validation lane run pytest, ruff …
peilinchen98 commentedon Oct 13, 2026
Another environment hit by the same change: write-restricted tokens (not only AppContainer).
Setup. Windows 11, Python 3.14.7 and 3.11.16 (both show the same result). Commands run inside the OpenAI Codex CLI Windows sandbox (
unelevatedmode), which launches processes withCreateRestrictedToken(..., WRITE_RESTRICTED, ...). Write access is then granted only where the folder's DACL allows one of the restricting SIDs (per-workspace capability SIDs), which the workspace folder grants with inheritance.Repro (run inside the restricted-token process, in a writable workspace folder):
The folder is created, but the restricting capability SID is not in the new protected DACL, so the write-restricted token can neither write into nor list it.
TemporaryDirectory()cleanup then fails at the listing / attribute-reset step. pytest'stmp_path(which uses 0o700 throughout_pytest/tmpdir.py, including with--basetemp) fails at fixture setup withWinError 5.os.makedirsand default-modeos.mkdirare unaffected.Relation to the open PR. As far as I can tell from its title, gh-148804 targets the AppContainer case. I have not checked whether its approach also adds the restricting SIDs of a write-restricted token; if it does not, this case would remain. A fix that keeps the CVE-2024-4030 protection but preserves inherited ACEs for the token's restricting/capability SIDs (or an opt-out) would cover both.
Workaround we use, in case it helps others: a
sitecustomize.pythat, behind an opt-in environment variable, mapsmode=0o700to the default mode on Windows so new folders inherit the parent DACL, plus pointingTMPDIR/TEMP/TMPat a fresh folder inside the workspace. This deliberately gives up the 0o700 protection, so it is only for sandboxed test runs.