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)

Abierto
#134,587 2 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Reproduce la regresión con test_temp.py y StartAppContainer.cpp usando las distribuciones integradas 3.12.3 y 3.12.4. Inspecciona la implementación de tempfile.mkdtemp para Windows y los cambios del descriptor de seguridad asociados con issue 118486. Se considera completado cuando se pueda crear y escribir un archivo dentro del directorio devuelto bajo el AppContainer, mientras el comportamiento existente de los permisos permanece intacto.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
operating-systems
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.