python / python/cpython

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)

未关闭
#134,587 2 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 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

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。