gh-114096: Restore privileges in _winapi.CreateJunction after creating the junction (GH-114089)

This avoids impact on later parts of the application which may be able to do things they otherwise shouldn't.
(cherry picked from commit de4ced54eb)

Co-authored-by: Steve Dower <steve.dower@python.org>
This commit is contained in:
Miss Islington (bot) 2024-01-16 18:39:59 +01:00 committed by GitHub
parent 91739149f0
commit 10f00294a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 7 deletions

View file

@ -530,7 +530,12 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
{
/* Privilege adjustment */
HANDLE token = NULL;
TOKEN_PRIVILEGES tp;
struct {
TOKEN_PRIVILEGES base;
/* overallocate by a few array elements */
LUID_AND_ATTRIBUTES privs[4];
} tp, previousTp;
int previousTpSize = 0;
/* Reparse data buffer */
const USHORT prefix_len = 4;
@ -554,17 +559,21 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
/* Adjust privileges to allow rewriting directory entry as a
junction point. */
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
goto cleanup;
}
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.base.Privileges[0].Luid)) {
goto cleanup;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
NULL, NULL))
tp.base.PrivilegeCount = 1;
tp.base.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(token, FALSE, &tp.base, sizeof(previousTp),
&previousTp.base, &previousTpSize)) {
goto cleanup;
}
if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
goto cleanup;
@ -645,6 +654,11 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
cleanup:
ret = GetLastError();
if (previousTpSize) {
AdjustTokenPrivileges(token, FALSE, &previousTp.base, previousTpSize,
NULL, NULL);
}
if (token != NULL)
CloseHandle(token);
if (junction != NULL)