Skip to content

Commit 10f0029

Browse files
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 de4ced5) Co-authored-by: Steve Dower <[email protected]>
1 parent 9173914 commit 10f0029

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Process privileges that are activated for creating directory junctions are
2+
now restored afterwards, avoiding behaviour changes in other parts of the
3+
program.

Modules/_winapi.c

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,12 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
530530
{
531531
/* Privilege adjustment */
532532
HANDLE token = NULL;
533-
TOKEN_PRIVILEGES tp;
533+
struct {
534+
TOKEN_PRIVILEGES base;
535+
/* overallocate by a few array elements */
536+
LUID_AND_ATTRIBUTES privs[4];
537+
} tp, previousTp;
538+
int previousTpSize = 0;
534539

535540
/* Reparse data buffer */
536541
const USHORT prefix_len = 4;
@@ -554,17 +559,21 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
554559

555560
/* Adjust privileges to allow rewriting directory entry as a
556561
junction point. */
557-
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
562+
if (!OpenProcessToken(GetCurrentProcess(),
563+
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
558564
goto cleanup;
565+
}
559566

560-
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
567+
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.base.Privileges[0].Luid)) {
561568
goto cleanup;
569+
}
562570

563-
tp.PrivilegeCount = 1;
564-
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
565-
if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
566-
NULL, NULL))
571+
tp.base.PrivilegeCount = 1;
572+
tp.base.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
573+
if (!AdjustTokenPrivileges(token, FALSE, &tp.base, sizeof(previousTp),
574+
&previousTp.base, &previousTpSize)) {
567575
goto cleanup;
576+
}
568577

569578
if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
570579
goto cleanup;
@@ -645,6 +654,11 @@ _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
645654
cleanup:
646655
ret = GetLastError();
647656

657+
if (previousTpSize) {
658+
AdjustTokenPrivileges(token, FALSE, &previousTp.base, previousTpSize,
659+
NULL, NULL);
660+
}
661+
648662
if (token != NULL)
649663
CloseHandle(token);
650664
if (junction != NULL)

0 commit comments

Comments
 (0)