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)
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
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 https://github.com/python/cpython/issues/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
Linked PRs
- gh-134607
- gh-148804
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
使用 3.12.3 和 3.12.4 嵌入式發行版,透過 test_temp.py 和 StartAppContainer.cpp 重現回歸問題。檢查 tempfile.mkdtemp 的 Windows 實作,以及與 issue 118486 相關的安全性描述項變更。在 AppContainer 下能夠於傳回的目錄中建立並寫入檔案,同時維持現有的權限行為,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- operating-systems
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100